blob: dcb2ad3a7e889a283657fdb0ed49dd581c6e36b1 [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 +000043static cl::opt<bool>
44EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000045 cl::desc("Allow AArch64 SLI/SRI formation"),
46 cl::init(false));
47
48// FIXME: The necessary dtprel relocations don't seem to be supported
49// well in the GNU bfd and gold linkers at the moment. Therefore, by
50// default, for now, fall back to GeneralDynamic code generation.
51cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
52 "aarch64-elf-ldtls-generation", cl::Hidden,
53 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
54 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000055
Matthias Braunaf7d7702015-07-16 20:02:37 +000056/// Value type used for condition codes.
57static const MVT MVT_CC = MVT::i32;
58
Eric Christopher905f12d2015-01-29 00:19:42 +000059AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
60 const AArch64Subtarget &STI)
61 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000062
63 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
64 // we have to make something up. Arbitrarily, choose ZeroOrOne.
65 setBooleanContents(ZeroOrOneBooleanContent);
66 // When comparing vectors the result sets the different elements in the
67 // vector to all-one or all-zero.
68 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
69
70 // Set up the register classes.
71 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
72 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
73
74 if (Subtarget->hasFPARMv8()) {
75 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
76 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
77 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
78 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
79 }
80
81 if (Subtarget->hasNEON()) {
82 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
83 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
84 // Someone set us up the NEON.
85 addDRTypeForNEON(MVT::v2f32);
86 addDRTypeForNEON(MVT::v8i8);
87 addDRTypeForNEON(MVT::v4i16);
88 addDRTypeForNEON(MVT::v2i32);
89 addDRTypeForNEON(MVT::v1i64);
90 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000091 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000092
93 addQRTypeForNEON(MVT::v4f32);
94 addQRTypeForNEON(MVT::v2f64);
95 addQRTypeForNEON(MVT::v16i8);
96 addQRTypeForNEON(MVT::v8i16);
97 addQRTypeForNEON(MVT::v4i32);
98 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +000099 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000100 }
101
102 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000103 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000104
105 // Provide all sorts of operation actions
106 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
107 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
108 setOperationAction(ISD::SETCC, MVT::i32, Custom);
109 setOperationAction(ISD::SETCC, MVT::i64, Custom);
110 setOperationAction(ISD::SETCC, MVT::f32, Custom);
111 setOperationAction(ISD::SETCC, MVT::f64, Custom);
112 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
113 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
114 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
115 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
116 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
117 setOperationAction(ISD::SELECT, MVT::i32, Custom);
118 setOperationAction(ISD::SELECT, MVT::i64, Custom);
119 setOperationAction(ISD::SELECT, MVT::f32, Custom);
120 setOperationAction(ISD::SELECT, MVT::f64, Custom);
121 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
122 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
123 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
124 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
125 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
126 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
127
128 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
129 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
130 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
131
132 setOperationAction(ISD::FREM, MVT::f32, Expand);
133 setOperationAction(ISD::FREM, MVT::f64, Expand);
134 setOperationAction(ISD::FREM, MVT::f80, Expand);
135
136 // Custom lowering hooks are needed for XOR
137 // to fold it into CSINC/CSINV.
138 setOperationAction(ISD::XOR, MVT::i32, Custom);
139 setOperationAction(ISD::XOR, MVT::i64, Custom);
140
141 // Virtually no operation on f128 is legal, but LLVM can't expand them when
142 // there's a valid register class, so we need custom operations in most cases.
143 setOperationAction(ISD::FABS, MVT::f128, Expand);
144 setOperationAction(ISD::FADD, MVT::f128, Custom);
145 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
146 setOperationAction(ISD::FCOS, MVT::f128, Expand);
147 setOperationAction(ISD::FDIV, MVT::f128, Custom);
148 setOperationAction(ISD::FMA, MVT::f128, Expand);
149 setOperationAction(ISD::FMUL, MVT::f128, Custom);
150 setOperationAction(ISD::FNEG, MVT::f128, Expand);
151 setOperationAction(ISD::FPOW, MVT::f128, Expand);
152 setOperationAction(ISD::FREM, MVT::f128, Expand);
153 setOperationAction(ISD::FRINT, MVT::f128, Expand);
154 setOperationAction(ISD::FSIN, MVT::f128, Expand);
155 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
156 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
157 setOperationAction(ISD::FSUB, MVT::f128, Custom);
158 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
159 setOperationAction(ISD::SETCC, MVT::f128, Custom);
160 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
161 setOperationAction(ISD::SELECT, MVT::f128, Custom);
162 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
163 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
164
165 // Lowering for many of the conversions is actually specified by the non-f128
166 // type. The LowerXXX function will be trivial when f128 isn't involved.
167 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
168 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
169 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
170 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
171 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
172 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
173 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
174 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
175 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
176 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
177 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
178 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
179 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
180 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
181
182 // Variable arguments.
183 setOperationAction(ISD::VASTART, MVT::Other, Custom);
184 setOperationAction(ISD::VAARG, MVT::Other, Custom);
185 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
186 setOperationAction(ISD::VAEND, MVT::Other, Expand);
187
188 // Variable-sized objects.
189 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
190 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
191 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
192
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 // Constant pool entries
194 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
195
196 // BlockAddress
197 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
198
199 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
200 setOperationAction(ISD::ADDC, MVT::i32, Custom);
201 setOperationAction(ISD::ADDE, MVT::i32, Custom);
202 setOperationAction(ISD::SUBC, MVT::i32, Custom);
203 setOperationAction(ISD::SUBE, MVT::i32, Custom);
204 setOperationAction(ISD::ADDC, MVT::i64, Custom);
205 setOperationAction(ISD::ADDE, MVT::i64, Custom);
206 setOperationAction(ISD::SUBC, MVT::i64, Custom);
207 setOperationAction(ISD::SUBE, MVT::i64, Custom);
208
209 // AArch64 lacks both left-rotate and popcount instructions.
210 setOperationAction(ISD::ROTL, MVT::i32, Expand);
211 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000212 for (MVT VT : MVT::vector_valuetypes()) {
213 setOperationAction(ISD::ROTL, VT, Expand);
214 setOperationAction(ISD::ROTR, VT, Expand);
215 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000216
217 // AArch64 doesn't have {U|S}MUL_LOHI.
218 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
219 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
220
221
Tim Northover3b0846e2014-05-24 12:50:23 +0000222 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
223 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
224
225 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
226 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000227 for (MVT VT : MVT::vector_valuetypes()) {
228 setOperationAction(ISD::SDIVREM, VT, Expand);
229 setOperationAction(ISD::UDIVREM, VT, Expand);
230 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000231 setOperationAction(ISD::SREM, MVT::i32, Expand);
232 setOperationAction(ISD::SREM, MVT::i64, Expand);
233 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
234 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
235 setOperationAction(ISD::UREM, MVT::i32, Expand);
236 setOperationAction(ISD::UREM, MVT::i64, Expand);
237
238 // Custom lower Add/Sub/Mul with overflow.
239 setOperationAction(ISD::SADDO, MVT::i32, Custom);
240 setOperationAction(ISD::SADDO, MVT::i64, Custom);
241 setOperationAction(ISD::UADDO, MVT::i32, Custom);
242 setOperationAction(ISD::UADDO, MVT::i64, Custom);
243 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
244 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
245 setOperationAction(ISD::USUBO, MVT::i32, Custom);
246 setOperationAction(ISD::USUBO, MVT::i64, Custom);
247 setOperationAction(ISD::SMULO, MVT::i32, Custom);
248 setOperationAction(ISD::SMULO, MVT::i64, Custom);
249 setOperationAction(ISD::UMULO, MVT::i32, Custom);
250 setOperationAction(ISD::UMULO, MVT::i64, Custom);
251
252 setOperationAction(ISD::FSIN, MVT::f32, Expand);
253 setOperationAction(ISD::FSIN, MVT::f64, Expand);
254 setOperationAction(ISD::FCOS, MVT::f32, Expand);
255 setOperationAction(ISD::FCOS, MVT::f64, Expand);
256 setOperationAction(ISD::FPOW, MVT::f32, Expand);
257 setOperationAction(ISD::FPOW, MVT::f64, Expand);
258 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
259 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
260
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000261 // f16 is a storage-only type, always promote it to f32.
262 setOperationAction(ISD::SETCC, MVT::f16, Promote);
263 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
264 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
265 setOperationAction(ISD::SELECT, MVT::f16, Promote);
266 setOperationAction(ISD::FADD, MVT::f16, Promote);
267 setOperationAction(ISD::FSUB, MVT::f16, Promote);
268 setOperationAction(ISD::FMUL, MVT::f16, Promote);
269 setOperationAction(ISD::FDIV, MVT::f16, Promote);
270 setOperationAction(ISD::FREM, MVT::f16, Promote);
271 setOperationAction(ISD::FMA, MVT::f16, Promote);
272 setOperationAction(ISD::FNEG, MVT::f16, Promote);
273 setOperationAction(ISD::FABS, MVT::f16, Promote);
274 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
275 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
276 setOperationAction(ISD::FCOS, MVT::f16, Promote);
277 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
278 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
279 setOperationAction(ISD::FPOW, MVT::f16, Promote);
280 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
281 setOperationAction(ISD::FRINT, MVT::f16, Promote);
282 setOperationAction(ISD::FSIN, MVT::f16, Promote);
283 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
284 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
285 setOperationAction(ISD::FEXP, MVT::f16, Promote);
286 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
287 setOperationAction(ISD::FLOG, MVT::f16, Promote);
288 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
289 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
290 setOperationAction(ISD::FROUND, MVT::f16, Promote);
291 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
292 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
293 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000294 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
295 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000296
Oliver Stannard89d15422014-08-27 16:16:04 +0000297 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
298 // known to be safe.
299 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
300 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
301 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
302 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
303 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
304 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
305 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
306 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
307 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
308 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
309 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
310 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
311
312 // Expand all other v4f16 operations.
313 // FIXME: We could generate better code by promoting some operations to
314 // a pair of v4f32s
315 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
316 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
317 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
318 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
319 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
320 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
321 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
322 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
323 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
324 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
325 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
326 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
327 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
328 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
330 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
331 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
332 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
333 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
334 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
335 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
336 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
337 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
338 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
339 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
340 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
341
342
343 // v8f16 is also a storage-only type, so expand it.
344 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
345 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
346 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
347 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
348 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
349 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
350 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
351 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
352 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
353 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
354 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
355 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
356 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
357 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
358 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
359 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
360 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
361 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
362 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
363 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
364 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
365 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
366 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
367 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
368 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
369 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
370 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
371 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
372 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
373 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
374 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
375
Tim Northover3b0846e2014-05-24 12:50:23 +0000376 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000377 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000378 setOperationAction(ISD::FFLOOR, Ty, Legal);
379 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
380 setOperationAction(ISD::FCEIL, Ty, Legal);
381 setOperationAction(ISD::FRINT, Ty, Legal);
382 setOperationAction(ISD::FTRUNC, Ty, Legal);
383 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000384 setOperationAction(ISD::FMINNUM, Ty, Legal);
385 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000386 setOperationAction(ISD::FMINNAN, Ty, Legal);
387 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000388 }
389
390 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
391
Tim Northovercdf15292016-04-14 17:03:29 +0000392 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
393
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000394 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
395 // This requires the Performance Monitors extension.
396 if (Subtarget->hasPerfMon())
397 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
398
Tim Northover3b0846e2014-05-24 12:50:23 +0000399 if (Subtarget->isTargetMachO()) {
400 // For iOS, we don't want to the normal expansion of a libcall to
401 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
402 // traffic.
403 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
404 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
405 } else {
406 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
407 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
408 }
409
Juergen Ributzka23266502014-12-10 19:43:32 +0000410 // Make floating-point constants legal for the large code model, so they don't
411 // become loads from the constant pool.
412 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
413 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
414 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
415 }
416
Tim Northover3b0846e2014-05-24 12:50:23 +0000417 // AArch64 does not have floating-point extending loads, i1 sign-extending
418 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000419 for (MVT VT : MVT::fp_valuetypes()) {
420 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
421 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
422 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
423 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
424 }
425 for (MVT VT : MVT::integer_valuetypes())
426 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
427
Tim Northover3b0846e2014-05-24 12:50:23 +0000428 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
429 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
430 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
431 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
432 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
433 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
434 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000435
436 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
437 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
438
Tim Northover3b0846e2014-05-24 12:50:23 +0000439 // Indexed loads and stores are supported.
440 for (unsigned im = (unsigned)ISD::PRE_INC;
441 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
442 setIndexedLoadAction(im, MVT::i8, Legal);
443 setIndexedLoadAction(im, MVT::i16, Legal);
444 setIndexedLoadAction(im, MVT::i32, Legal);
445 setIndexedLoadAction(im, MVT::i64, Legal);
446 setIndexedLoadAction(im, MVT::f64, Legal);
447 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000448 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 setIndexedStoreAction(im, MVT::i8, Legal);
450 setIndexedStoreAction(im, MVT::i16, Legal);
451 setIndexedStoreAction(im, MVT::i32, Legal);
452 setIndexedStoreAction(im, MVT::i64, Legal);
453 setIndexedStoreAction(im, MVT::f64, Legal);
454 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000455 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000456 }
457
458 // Trap.
459 setOperationAction(ISD::TRAP, MVT::Other, Legal);
460
461 // We combine OR nodes for bitfield operations.
462 setTargetDAGCombine(ISD::OR);
463
464 // Vector add and sub nodes may conceal a high-half opportunity.
465 // Also, try to fold ADD into CSINC/CSINV..
466 setTargetDAGCombine(ISD::ADD);
467 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000468 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000469 setTargetDAGCombine(ISD::XOR);
470 setTargetDAGCombine(ISD::SINT_TO_FP);
471 setTargetDAGCombine(ISD::UINT_TO_FP);
472
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000473 setTargetDAGCombine(ISD::FP_TO_SINT);
474 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000475 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000476
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
478
479 setTargetDAGCombine(ISD::ANY_EXTEND);
480 setTargetDAGCombine(ISD::ZERO_EXTEND);
481 setTargetDAGCombine(ISD::SIGN_EXTEND);
482 setTargetDAGCombine(ISD::BITCAST);
483 setTargetDAGCombine(ISD::CONCAT_VECTORS);
484 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000485 if (Subtarget->supportsAddressTopByteIgnored())
486 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000487
488 setTargetDAGCombine(ISD::MUL);
489
490 setTargetDAGCombine(ISD::SELECT);
491 setTargetDAGCombine(ISD::VSELECT);
492
493 setTargetDAGCombine(ISD::INTRINSIC_VOID);
494 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
495 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000496 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000497
498 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
499 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
500 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
501
502 setStackPointerRegisterToSaveRestore(AArch64::SP);
503
504 setSchedulingPreference(Sched::Hybrid);
505
506 // Enable TBZ/TBNZ
507 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000508 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000509
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000510 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000511 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000512 // Set preferred alignments.
513 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
514 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000515
Tim Northover3b0846e2014-05-24 12:50:23 +0000516 setHasExtractBitsInsn(true);
517
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000518 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
519
Tim Northover3b0846e2014-05-24 12:50:23 +0000520 if (Subtarget->hasNEON()) {
521 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
522 // silliness like this:
523 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
524 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
525 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
526 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
527 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
528 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
529 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
530 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
531 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
532 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
533 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
534 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
535 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
536 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
537 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
538 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
539 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
540 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
541 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
542 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
543 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
544 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
545 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
546 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
547 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
548
549 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
550 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
551 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
552 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
553 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
554
555 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
556
557 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
558 // elements smaller than i32, so promote the input to i32 first.
559 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
560 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
561 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
562 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000563 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
564 // -> v8f16 conversions.
565 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
566 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
567 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000569 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
570 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
571 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
572 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
573 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000574 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
575 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
576 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
577 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000578
Craig Topperc5551bf2016-04-26 05:26:51 +0000579 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
580 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
581
Craig Topper3b4842b2016-04-28 01:58:21 +0000582 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
583 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
584 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
585 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
586 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
587 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
588 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
589 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
590
Tim Northover3b0846e2014-05-24 12:50:23 +0000591 // AArch64 doesn't have MUL.2d:
592 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000593 // Custom handling for some quad-vector types to detect MULL.
594 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
595 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
596 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
597
Tim Northover3b0846e2014-05-24 12:50:23 +0000598 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
599 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
600 // Likewise, narrowing and extending vector loads/stores aren't handled
601 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000602 for (MVT VT : MVT::vector_valuetypes()) {
603 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000604
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000605 setOperationAction(ISD::MULHS, VT, Expand);
606 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
607 setOperationAction(ISD::MULHU, VT, Expand);
608 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000609
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000610 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000611
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000612 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000613 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000614 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
615 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
616 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
617 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000618 }
619
620 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000621 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000622 setOperationAction(ISD::FFLOOR, Ty, Legal);
623 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
624 setOperationAction(ISD::FCEIL, Ty, Legal);
625 setOperationAction(ISD::FRINT, Ty, Legal);
626 setOperationAction(ISD::FTRUNC, Ty, Legal);
627 setOperationAction(ISD::FROUND, Ty, Legal);
628 }
629 }
James Molloyf089ab72014-08-06 10:42:18 +0000630
Matthias Braun651cff42016-06-02 18:03:53 +0000631 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000632}
633
Craig Topper18e69f42016-04-15 06:20:21 +0000634void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000635 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000636 setOperationAction(ISD::LOAD, VT, Promote);
637 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000638
Craig Topper18e69f42016-04-15 06:20:21 +0000639 setOperationAction(ISD::STORE, VT, Promote);
640 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000641 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000642 setOperationAction(ISD::LOAD, VT, Promote);
643 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000644
Craig Topper18e69f42016-04-15 06:20:21 +0000645 setOperationAction(ISD::STORE, VT, Promote);
646 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000647 }
648
649 // Mark vector float intrinsics as expand.
650 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000651 setOperationAction(ISD::FSIN, VT, Expand);
652 setOperationAction(ISD::FCOS, VT, Expand);
653 setOperationAction(ISD::FPOWI, VT, Expand);
654 setOperationAction(ISD::FPOW, VT, Expand);
655 setOperationAction(ISD::FLOG, VT, Expand);
656 setOperationAction(ISD::FLOG2, VT, Expand);
657 setOperationAction(ISD::FLOG10, VT, Expand);
658 setOperationAction(ISD::FEXP, VT, Expand);
659 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000660
661 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000662 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000663 }
664
Craig Topper18e69f42016-04-15 06:20:21 +0000665 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
666 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
667 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
668 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
669 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
670 setOperationAction(ISD::SRA, VT, Custom);
671 setOperationAction(ISD::SRL, VT, Custom);
672 setOperationAction(ISD::SHL, VT, Custom);
673 setOperationAction(ISD::AND, VT, Custom);
674 setOperationAction(ISD::OR, VT, Custom);
675 setOperationAction(ISD::SETCC, VT, Custom);
676 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000677
Craig Topper18e69f42016-04-15 06:20:21 +0000678 setOperationAction(ISD::SELECT, VT, Expand);
679 setOperationAction(ISD::SELECT_CC, VT, Expand);
680 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000681 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000682 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000683
684 // CNT supports only B element sizes.
685 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000686 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000687
Craig Topper18e69f42016-04-15 06:20:21 +0000688 setOperationAction(ISD::UDIV, VT, Expand);
689 setOperationAction(ISD::SDIV, VT, Expand);
690 setOperationAction(ISD::UREM, VT, Expand);
691 setOperationAction(ISD::SREM, VT, Expand);
692 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000693
Craig Topper18e69f42016-04-15 06:20:21 +0000694 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
695 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000696
Hal Finkelcd8664c2015-12-11 23:11:52 +0000697 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000698 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000699 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000700 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000701
James Molloy63be1982015-08-14 09:08:50 +0000702 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
703 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000704 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
705 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000706 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000707
Tim Northover3b0846e2014-05-24 12:50:23 +0000708 if (Subtarget->isLittleEndian()) {
709 for (unsigned im = (unsigned)ISD::PRE_INC;
710 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000711 setIndexedLoadAction(im, VT, Legal);
712 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000713 }
714 }
715}
716
717void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
718 addRegisterClass(VT, &AArch64::FPR64RegClass);
719 addTypeForNEON(VT, MVT::v2i32);
720}
721
722void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
723 addRegisterClass(VT, &AArch64::FPR128RegClass);
724 addTypeForNEON(VT, MVT::v4i32);
725}
726
Mehdi Amini44ede332015-07-09 02:09:04 +0000727EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
728 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000729 if (!VT.isVector())
730 return MVT::i32;
731 return VT.changeVectorElementTypeToInteger();
732}
733
734/// computeKnownBitsForTargetNode - Determine which of the bits specified in
735/// Mask are known to be either zero or one and return them in the
736/// KnownZero/KnownOne bitsets.
737void AArch64TargetLowering::computeKnownBitsForTargetNode(
738 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
739 const SelectionDAG &DAG, unsigned Depth) const {
740 switch (Op.getOpcode()) {
741 default:
742 break;
743 case AArch64ISD::CSEL: {
744 APInt KnownZero2, KnownOne2;
745 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
746 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
747 KnownZero &= KnownZero2;
748 KnownOne &= KnownOne2;
749 break;
750 }
751 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000752 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000753 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
754 switch (IntID) {
755 default: return;
756 case Intrinsic::aarch64_ldaxr:
757 case Intrinsic::aarch64_ldxr: {
758 unsigned BitWidth = KnownOne.getBitWidth();
759 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
760 unsigned MemBits = VT.getScalarType().getSizeInBits();
761 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
762 return;
763 }
764 }
765 break;
766 }
767 case ISD::INTRINSIC_WO_CHAIN:
768 case ISD::INTRINSIC_VOID: {
769 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
770 switch (IntNo) {
771 default:
772 break;
773 case Intrinsic::aarch64_neon_umaxv:
774 case Intrinsic::aarch64_neon_uminv: {
775 // Figure out the datatype of the vector operand. The UMINV instruction
776 // will zero extend the result, so we can mark as known zero all the
777 // bits larger than the element datatype. 32-bit or larget doesn't need
778 // this as those are legal types and will be handled by isel directly.
779 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
780 unsigned BitWidth = KnownZero.getBitWidth();
781 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
782 assert(BitWidth >= 8 && "Unexpected width!");
783 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
784 KnownZero |= Mask;
785 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
786 assert(BitWidth >= 16 && "Unexpected width!");
787 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
788 KnownZero |= Mask;
789 }
790 break;
791 } break;
792 }
793 }
794 }
795}
796
Mehdi Aminieaabc512015-07-09 15:12:23 +0000797MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
798 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000799 return MVT::i64;
800}
801
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000802bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
803 unsigned AddrSpace,
804 unsigned Align,
805 bool *Fast) const {
806 if (Subtarget->requiresStrictAlign())
807 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000808
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000809 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +0000810 // Some CPUs are fine with unaligned stores except for 128-bit ones.
811 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000812 // See comments in performSTORECombine() for more details about
813 // these conditions.
814
815 // Code that uses clang vector extensions can mark that it
816 // wants unaligned accesses to be treated as fast by
817 // underspecifying alignment to be 1 or 2.
818 Align <= 2 ||
819
820 // Disregard v2i64. Memcpy lowering produces those and splitting
821 // them regresses performance on micro-benchmarks and olden/bh.
822 VT == MVT::v2i64;
823 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000824 return true;
825}
826
Tim Northover3b0846e2014-05-24 12:50:23 +0000827FastISel *
828AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
829 const TargetLibraryInfo *libInfo) const {
830 return AArch64::createFastISel(funcInfo, libInfo);
831}
832
833const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000834 switch ((AArch64ISD::NodeType)Opcode) {
835 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000836 case AArch64ISD::CALL: return "AArch64ISD::CALL";
837 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
838 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
839 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
840 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
841 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
842 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
843 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
844 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
845 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
846 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
847 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000848 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000849 case AArch64ISD::ADC: return "AArch64ISD::ADC";
850 case AArch64ISD::SBC: return "AArch64ISD::SBC";
851 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
852 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
853 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
854 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
855 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000856 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
857 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
858 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000859 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000860 case AArch64ISD::DUP: return "AArch64ISD::DUP";
861 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
862 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
863 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
864 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
865 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
866 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
867 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
868 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
869 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
870 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
871 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
872 case AArch64ISD::BICi: return "AArch64ISD::BICi";
873 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
874 case AArch64ISD::BSL: return "AArch64ISD::BSL";
875 case AArch64ISD::NEG: return "AArch64ISD::NEG";
876 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
877 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
878 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
879 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
880 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
881 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
882 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
883 case AArch64ISD::REV16: return "AArch64ISD::REV16";
884 case AArch64ISD::REV32: return "AArch64ISD::REV32";
885 case AArch64ISD::REV64: return "AArch64ISD::REV64";
886 case AArch64ISD::EXT: return "AArch64ISD::EXT";
887 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
888 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
889 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
890 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
891 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
892 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
893 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
894 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
895 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
896 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
897 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
898 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
899 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
900 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
901 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
902 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
903 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
904 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
905 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
906 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
907 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000908 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
909 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
910 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
911 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
912 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
913 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000914 case AArch64ISD::NOT: return "AArch64ISD::NOT";
915 case AArch64ISD::BIT: return "AArch64ISD::BIT";
916 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
917 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
918 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
919 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
920 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000921 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000922 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
923 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000924 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000925 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
926 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
927 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
928 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
929 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
930 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
931 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
932 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
933 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
934 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
935 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
936 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
937 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
938 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
939 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
940 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
941 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
942 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
943 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
944 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
945 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
946 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
947 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
948 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
949 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
950 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
951 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
952 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
953 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000954 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
955 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezesbcb95cd2016-05-04 20:18:27 +0000956 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
957 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Tim Northover3b0846e2014-05-24 12:50:23 +0000958 }
Matthias Braund04893f2015-05-07 21:33:59 +0000959 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000960}
961
962MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000963AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +0000964 MachineBasicBlock *MBB) const {
965 // We materialise the F128CSEL pseudo-instruction as some control flow and a
966 // phi node:
967
968 // OrigBB:
969 // [... previous instrs leading to comparison ...]
970 // b.ne TrueBB
971 // b EndBB
972 // TrueBB:
973 // ; Fallthrough
974 // EndBB:
975 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
976
Tim Northover3b0846e2014-05-24 12:50:23 +0000977 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000978 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000979 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000980 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000981 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000982
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000983 unsigned DestReg = MI.getOperand(0).getReg();
984 unsigned IfTrueReg = MI.getOperand(1).getReg();
985 unsigned IfFalseReg = MI.getOperand(2).getReg();
986 unsigned CondCode = MI.getOperand(3).getImm();
987 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +0000988
989 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
990 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
991 MF->insert(It, TrueBB);
992 MF->insert(It, EndBB);
993
994 // Transfer rest of current basic-block to EndBB
995 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
996 MBB->end());
997 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
998
999 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1000 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1001 MBB->addSuccessor(TrueBB);
1002 MBB->addSuccessor(EndBB);
1003
1004 // TrueBB falls through to the end.
1005 TrueBB->addSuccessor(EndBB);
1006
1007 if (!NZCVKilled) {
1008 TrueBB->addLiveIn(AArch64::NZCV);
1009 EndBB->addLiveIn(AArch64::NZCV);
1010 }
1011
1012 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1013 .addReg(IfTrueReg)
1014 .addMBB(TrueBB)
1015 .addReg(IfFalseReg)
1016 .addMBB(MBB);
1017
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001018 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001019 return EndBB;
1020}
1021
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001022MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1023 MachineInstr &MI, MachineBasicBlock *BB) const {
1024 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001025 default:
1026#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001027 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001028#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
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001138/// Convert a DAG fp condition code to an AArch64 CC.
1139/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1140/// should be AND'ed instead of OR'ed.
1141static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1142 AArch64CC::CondCode &CondCode,
1143 AArch64CC::CondCode &CondCode2) {
1144 CondCode2 = AArch64CC::AL;
1145 switch (CC) {
1146 default:
1147 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1148 assert(CondCode2 == AArch64CC::AL);
1149 break;
1150 case ISD::SETONE:
1151 // (a one b)
1152 // == ((a olt b) || (a ogt b))
1153 // == ((a ord b) && (a une b))
1154 CondCode = AArch64CC::VC;
1155 CondCode2 = AArch64CC::NE;
1156 break;
1157 case ISD::SETUEQ:
1158 // (a ueq b)
1159 // == ((a uno b) || (a oeq b))
1160 // == ((a ule b) && (a uge b))
1161 CondCode = AArch64CC::PL;
1162 CondCode2 = AArch64CC::LE;
1163 break;
1164 }
1165}
1166
Tim Northover3b0846e2014-05-24 12:50:23 +00001167/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1168/// CC usable with the vector instructions. Fewer operations are available
1169/// without a real NZCV register, so we have to use less efficient combinations
1170/// to get the same effect.
1171static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1172 AArch64CC::CondCode &CondCode,
1173 AArch64CC::CondCode &CondCode2,
1174 bool &Invert) {
1175 Invert = false;
1176 switch (CC) {
1177 default:
1178 // Mostly the scalar mappings work fine.
1179 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1180 break;
1181 case ISD::SETUO:
1182 Invert = true; // Fallthrough
1183 case ISD::SETO:
1184 CondCode = AArch64CC::MI;
1185 CondCode2 = AArch64CC::GE;
1186 break;
1187 case ISD::SETUEQ:
1188 case ISD::SETULT:
1189 case ISD::SETULE:
1190 case ISD::SETUGT:
1191 case ISD::SETUGE:
1192 // All of the compare-mask comparisons are ordered, but we can switch
1193 // between the two by a double inversion. E.g. ULE == !OGT.
1194 Invert = true;
1195 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1196 break;
1197 }
1198}
1199
1200static bool isLegalArithImmed(uint64_t C) {
1201 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1202 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1203}
1204
1205static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001206 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001207 EVT VT = LHS.getValueType();
1208
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001209 if (VT.isFloatingPoint()) {
1210 assert(VT != MVT::f128);
1211 if (VT == MVT::f16) {
1212 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1213 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001214 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001215 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001216 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001217 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001218
1219 // The CMP instruction is just an alias for SUBS, and representing it as
1220 // SUBS means that it's possible to get CSE with subtract operations.
1221 // A later phase can perform the optimization of setting the destination
1222 // register to WZR/XZR if it ends up being unused.
1223 unsigned Opcode = AArch64ISD::SUBS;
1224
Artyom Skrobov314ee042015-11-25 19:41:11 +00001225 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001226 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1227 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1228 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1229 // can be set differently by this operation. It comes down to whether
1230 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1231 // everything is fine. If not then the optimization is wrong. Thus general
1232 // comparisons are only valid if op2 != 0.
1233
1234 // So, finally, the only LLVM-native comparisons that don't mention C and V
1235 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1236 // the absence of information about op2.
1237 Opcode = AArch64ISD::ADDS;
1238 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001239 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001240 !isUnsignedIntSetCC(CC)) {
1241 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1242 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1243 // of the signed comparisons.
1244 Opcode = AArch64ISD::ANDS;
1245 RHS = LHS.getOperand(1);
1246 LHS = LHS.getOperand(0);
1247 }
1248
Matthias Braunaf7d7702015-07-16 20:02:37 +00001249 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001250 .getValue(1);
1251}
1252
Matthias Braunaf7d7702015-07-16 20:02:37 +00001253/// \defgroup AArch64CCMP CMP;CCMP matching
1254///
1255/// These functions deal with the formation of CMP;CCMP;... sequences.
1256/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1257/// a comparison. They set the NZCV flags to a predefined value if their
1258/// predicate is false. This allows to express arbitrary conjunctions, for
1259/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1260/// expressed as:
1261/// cmp A
1262/// ccmp B, inv(CB), CA
1263/// check for CB flags
1264///
1265/// In general we can create code for arbitrary "... (and (and A B) C)"
1266/// sequences. We can also implement some "or" expressions, because "(or A B)"
1267/// is equivalent to "not (and (not A) (not B))" and we can implement some
1268/// negation operations:
1269/// We can negate the results of a single comparison by inverting the flags
1270/// used when the predicate fails and inverting the flags tested in the next
1271/// instruction; We can also negate the results of the whole previous
1272/// conditional compare sequence by inverting the flags tested in the next
1273/// instruction. However there is no way to negate the result of a partial
1274/// sequence.
1275///
1276/// Therefore on encountering an "or" expression we can negate the subtree on
1277/// one side and have to be able to push the negate to the leafs of the subtree
1278/// on the other side (see also the comments in code). As complete example:
1279/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1280/// (and (setCC (cmp C)) (setCD (cmp D)))"
1281/// is transformed to
1282/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1283/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1284/// and implemented as:
1285/// cmp C
1286/// ccmp D, inv(CD), CC
1287/// ccmp A, CA, inv(CD)
1288/// ccmp B, CB, inv(CA)
1289/// check for CB flags
1290/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1291/// by conditional compare sequences.
1292/// @{
1293
Geoff Berrye41c2df2015-07-20 22:03:52 +00001294/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001295static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1296 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001297 AArch64CC::CondCode Predicate,
1298 AArch64CC::CondCode OutCC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001299 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001300 unsigned Opcode = 0;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001301 if (LHS.getValueType().isFloatingPoint()) {
1302 assert(LHS.getValueType() != MVT::f128);
1303 if (LHS.getValueType() == MVT::f16) {
1304 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1305 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1306 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001307 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001308 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001309 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001310 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001311 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1312 Opcode = AArch64ISD::CCMN;
1313 RHS = RHS.getOperand(1);
1314 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001315 }
1316 if (Opcode == 0)
1317 Opcode = AArch64ISD::CCMP;
1318
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001319 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1320 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1321 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001322 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1323 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1324}
1325
1326/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1327/// CanPushNegate is set to true if we can push a negate operation through
1328/// the tree in a was that we are left with AND operations and negate operations
1329/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1330/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1331/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001332static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001333 unsigned Depth = 0) {
1334 if (!Val.hasOneUse())
1335 return false;
1336 unsigned Opcode = Val->getOpcode();
1337 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001338 if (Val->getOperand(0).getValueType() == MVT::f128)
1339 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001340 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001341 return true;
1342 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001343 // Protect against exponential runtime and stack overflow.
1344 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001345 return false;
1346 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1347 SDValue O0 = Val->getOperand(0);
1348 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001349 bool CanNegateL;
1350 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001351 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001352 bool CanNegateR;
1353 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001354 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001355
1356 if (Opcode == ISD::OR) {
1357 // For an OR expression we need to be able to negate at least one side or
1358 // we cannot do the transformation at all.
1359 if (!CanNegateL && !CanNegateR)
1360 return false;
1361 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1362 // can negate the x and y subtrees.
1363 CanNegate = CanNegateL && CanNegateR;
1364 } else {
1365 // If the operands are OR expressions then we finally need to negate their
1366 // outputs, we can only do that for the operand with emitted last by
1367 // negating OutCC, not for both operands.
1368 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1369 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1370 if (NeedsNegOutL && NeedsNegOutR)
1371 return false;
1372 // We cannot negate an AND operation (it would become an OR),
1373 CanNegate = false;
1374 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001375 return true;
1376 }
1377 return false;
1378}
1379
1380/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1381/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1382/// Tries to transform the given i1 producing node @p Val to a series compare
1383/// and conditional compare operations. @returns an NZCV flags producing node
1384/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1385/// transformation was not possible.
1386/// On recursive invocations @p PushNegate may be set to true to have negation
1387/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1388/// for the comparisons in the current subtree; @p Depth limits the search
1389/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001390static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1391 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1392 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001393 // We're at a tree leaf, produce a conditional comparison operation.
1394 unsigned Opcode = Val->getOpcode();
1395 if (Opcode == ISD::SETCC) {
1396 SDValue LHS = Val->getOperand(0);
1397 SDValue RHS = Val->getOperand(1);
1398 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1399 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001400 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001401 CC = getSetCCInverse(CC, isInteger);
1402 SDLoc DL(Val);
1403 // Determine OutCC and handle FP special case.
1404 if (isInteger) {
1405 OutCC = changeIntCCToAArch64CC(CC);
1406 } else {
1407 assert(LHS.getValueType().isFloatingPoint());
1408 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001409 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1410 // Some floating point conditions can't be tested with a single condition
1411 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001412 if (ExtraCC != AArch64CC::AL) {
1413 SDValue ExtraCmp;
1414 if (!CCOp.getNode())
1415 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001416 else
1417 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1418 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001419 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001420 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001421 }
1422 }
1423
1424 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001425 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001426 return emitComparison(LHS, RHS, CC, DL, DAG);
1427 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001428 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001429 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001430 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001431 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1432 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001433
1434 // Check if both sides can be transformed.
1435 SDValue LHS = Val->getOperand(0);
1436 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001437
Matthias Braunfdef49b2016-01-23 04:05:22 +00001438 // In case of an OR we need to negate our operands and the result.
1439 // (A v B) <=> not(not(A) ^ not(B))
1440 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001441 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001442 // predicate flags giving us a free negation for one side. The other side
1443 // must be negatable by itself.
1444 if (NegateOpsAndResult) {
1445 // See which side we can negate.
1446 bool CanNegateL;
1447 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1448 assert(isValidL && "Valid conjunction/disjunction tree");
1449 (void)isValidL;
1450
1451#ifndef NDEBUG
1452 bool CanNegateR;
1453 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1454 assert(isValidR && "Valid conjunction/disjunction tree");
1455 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1456#endif
1457
1458 // Order the side which we cannot negate to RHS so we can emit it first.
1459 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001460 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001461 } else {
1462 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001463 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001464 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001465 // Order the side where we need to negate the output flags to RHS so it
1466 // gets emitted first.
1467 if (NeedsNegOutL)
1468 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001469 }
1470
1471 // Emit RHS. If we want to negate the tree we only need to push a negate
1472 // through if we are already in a PushNegate case, otherwise we can negate
1473 // the "flags to test" afterwards.
1474 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001475 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1476 CCOp, Predicate);
1477 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001478 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001479 // Emit LHS. We may need to negate it.
1480 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1481 NegateOpsAndResult, CmpR,
1482 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001483 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001484 // (or absorb the Negate parameter).
1485 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001486 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1487 return CmpL;
1488}
1489
Matthias Braunfdef49b2016-01-23 04:05:22 +00001490/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1491/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1492/// \see emitConjunctionDisjunctionTreeRec().
1493static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1494 AArch64CC::CondCode &OutCC) {
1495 bool CanNegate;
1496 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1497 return SDValue();
1498
1499 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1500 AArch64CC::AL);
1501}
1502
Matthias Braunaf7d7702015-07-16 20:02:37 +00001503/// @}
1504
Tim Northover3b0846e2014-05-24 12:50:23 +00001505static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001506 SDValue &AArch64cc, SelectionDAG &DAG,
1507 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001508 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1509 EVT VT = RHS.getValueType();
1510 uint64_t C = RHSC->getZExtValue();
1511 if (!isLegalArithImmed(C)) {
1512 // Constant does not fit, try adjusting it by one?
1513 switch (CC) {
1514 default:
1515 break;
1516 case ISD::SETLT:
1517 case ISD::SETGE:
1518 if ((VT == MVT::i32 && C != 0x80000000 &&
1519 isLegalArithImmed((uint32_t)(C - 1))) ||
1520 (VT == MVT::i64 && C != 0x80000000ULL &&
1521 isLegalArithImmed(C - 1ULL))) {
1522 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1523 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001524 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001525 }
1526 break;
1527 case ISD::SETULT:
1528 case ISD::SETUGE:
1529 if ((VT == MVT::i32 && C != 0 &&
1530 isLegalArithImmed((uint32_t)(C - 1))) ||
1531 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1532 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1533 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001534 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001535 }
1536 break;
1537 case ISD::SETLE:
1538 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001539 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001540 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001541 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001542 isLegalArithImmed(C + 1ULL))) {
1543 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1544 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001545 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001546 }
1547 break;
1548 case ISD::SETULE:
1549 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001550 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001551 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001552 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001553 isLegalArithImmed(C + 1ULL))) {
1554 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1555 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001556 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001557 }
1558 break;
1559 }
1560 }
1561 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001562 SDValue Cmp;
1563 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001564 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001565 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1566
1567 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1568 // For the i8 operand, the largest immediate is 255, so this can be easily
1569 // encoded in the compare instruction. For the i16 operand, however, the
1570 // largest immediate cannot be encoded in the compare.
1571 // Therefore, use a sign extending load and cmn to avoid materializing the
1572 // -1 constant. For example,
1573 // movz w1, #65535
1574 // ldrh w0, [x0, #0]
1575 // cmp w0, w1
1576 // >
1577 // ldrsh w0, [x0, #0]
1578 // cmn w0, #1
1579 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1580 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001581 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001582 // transformation is profitable.
1583 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1584 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1585 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1586 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1587 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1588 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1589 SDValue SExt =
1590 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1591 DAG.getValueType(MVT::i16));
1592 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1593 RHS.getValueType()),
1594 CC, dl, DAG);
1595 AArch64CC = changeIntCCToAArch64CC(CC);
1596 }
1597 }
1598
1599 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1600 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1601 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1602 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001603 }
1604 }
1605 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001606
1607 if (!Cmp) {
1608 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1609 AArch64CC = changeIntCCToAArch64CC(CC);
1610 }
1611 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001612 return Cmp;
1613}
1614
1615static std::pair<SDValue, SDValue>
1616getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1617 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1618 "Unsupported value type");
1619 SDValue Value, Overflow;
1620 SDLoc DL(Op);
1621 SDValue LHS = Op.getOperand(0);
1622 SDValue RHS = Op.getOperand(1);
1623 unsigned Opc = 0;
1624 switch (Op.getOpcode()) {
1625 default:
1626 llvm_unreachable("Unknown overflow instruction!");
1627 case ISD::SADDO:
1628 Opc = AArch64ISD::ADDS;
1629 CC = AArch64CC::VS;
1630 break;
1631 case ISD::UADDO:
1632 Opc = AArch64ISD::ADDS;
1633 CC = AArch64CC::HS;
1634 break;
1635 case ISD::SSUBO:
1636 Opc = AArch64ISD::SUBS;
1637 CC = AArch64CC::VS;
1638 break;
1639 case ISD::USUBO:
1640 Opc = AArch64ISD::SUBS;
1641 CC = AArch64CC::LO;
1642 break;
1643 // Multiply needs a little bit extra work.
1644 case ISD::SMULO:
1645 case ISD::UMULO: {
1646 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001647 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001648 if (Op.getValueType() == MVT::i32) {
1649 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1650 // For a 32 bit multiply with overflow check we want the instruction
1651 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1652 // need to generate the following pattern:
1653 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1654 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1655 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1656 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1657 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001658 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001659 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1660 // operation. We need to clear out the upper 32 bits, because we used a
1661 // widening multiply that wrote all 64 bits. In the end this should be a
1662 // noop.
1663 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1664 if (IsSigned) {
1665 // The signed overflow check requires more than just a simple check for
1666 // any bit set in the upper 32 bits of the result. These bits could be
1667 // just the sign bits of a negative number. To perform the overflow
1668 // check we have to arithmetic shift right the 32nd bit of the result by
1669 // 31 bits. Then we compare the result to the upper 32 bits.
1670 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001671 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001672 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1673 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001674 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001675 // It is important that LowerBits is last, otherwise the arithmetic
1676 // shift will not be folded into the compare (SUBS).
1677 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1678 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1679 .getValue(1);
1680 } else {
1681 // The overflow check for unsigned multiply is easy. We only need to
1682 // check if any of the upper 32 bits are set. This can be done with a
1683 // CMP (shifted register). For that we need to generate the following
1684 // pattern:
1685 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1686 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001687 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001688 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1689 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001690 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1691 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001692 UpperBits).getValue(1);
1693 }
1694 break;
1695 }
1696 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1697 // For the 64 bit multiply
1698 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1699 if (IsSigned) {
1700 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1701 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001702 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001703 // It is important that LowerBits is last, otherwise the arithmetic
1704 // shift will not be folded into the compare (SUBS).
1705 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1706 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1707 .getValue(1);
1708 } else {
1709 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1710 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1711 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001712 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1713 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001714 UpperBits).getValue(1);
1715 }
1716 break;
1717 }
1718 } // switch (...)
1719
1720 if (Opc) {
1721 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1722
1723 // Emit the AArch64 operation with overflow check.
1724 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1725 Overflow = Value.getValue(1);
1726 }
1727 return std::make_pair(Value, Overflow);
1728}
1729
1730SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1731 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001732 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001733 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001734}
1735
1736static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1737 SDValue Sel = Op.getOperand(0);
1738 SDValue Other = Op.getOperand(1);
1739
1740 // If neither operand is a SELECT_CC, give up.
1741 if (Sel.getOpcode() != ISD::SELECT_CC)
1742 std::swap(Sel, Other);
1743 if (Sel.getOpcode() != ISD::SELECT_CC)
1744 return Op;
1745
1746 // The folding we want to perform is:
1747 // (xor x, (select_cc a, b, cc, 0, -1) )
1748 // -->
1749 // (csel x, (xor x, -1), cc ...)
1750 //
1751 // The latter will get matched to a CSINV instruction.
1752
1753 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1754 SDValue LHS = Sel.getOperand(0);
1755 SDValue RHS = Sel.getOperand(1);
1756 SDValue TVal = Sel.getOperand(2);
1757 SDValue FVal = Sel.getOperand(3);
1758 SDLoc dl(Sel);
1759
1760 // FIXME: This could be generalized to non-integer comparisons.
1761 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1762 return Op;
1763
1764 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1765 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1766
Eric Christopher572e03a2015-06-19 01:53:21 +00001767 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001768 if (!CFVal || !CTVal)
1769 return Op;
1770
1771 // We can commute the SELECT_CC by inverting the condition. This
1772 // might be needed to make this fit into a CSINV pattern.
1773 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1774 std::swap(TVal, FVal);
1775 std::swap(CTVal, CFVal);
1776 CC = ISD::getSetCCInverse(CC, true);
1777 }
1778
1779 // If the constants line up, perform the transform!
1780 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1781 SDValue CCVal;
1782 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1783
1784 FVal = Other;
1785 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001786 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001787
1788 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1789 CCVal, Cmp);
1790 }
1791
1792 return Op;
1793}
1794
1795static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1796 EVT VT = Op.getValueType();
1797
1798 // Let legalize expand this if it isn't a legal type yet.
1799 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1800 return SDValue();
1801
1802 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1803
1804 unsigned Opc;
1805 bool ExtraOp = false;
1806 switch (Op.getOpcode()) {
1807 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001808 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001809 case ISD::ADDC:
1810 Opc = AArch64ISD::ADDS;
1811 break;
1812 case ISD::SUBC:
1813 Opc = AArch64ISD::SUBS;
1814 break;
1815 case ISD::ADDE:
1816 Opc = AArch64ISD::ADCS;
1817 ExtraOp = true;
1818 break;
1819 case ISD::SUBE:
1820 Opc = AArch64ISD::SBCS;
1821 ExtraOp = true;
1822 break;
1823 }
1824
1825 if (!ExtraOp)
1826 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1827 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1828 Op.getOperand(2));
1829}
1830
1831static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1832 // Let legalize expand this if it isn't a legal type yet.
1833 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1834 return SDValue();
1835
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001836 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001837 AArch64CC::CondCode CC;
1838 // The actual operation that sets the overflow or carry flag.
1839 SDValue Value, Overflow;
1840 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1841
1842 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001843 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1844 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001845
1846 // We use an inverted condition, because the conditional select is inverted
1847 // too. This will allow it to be selected to a single instruction:
1848 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001849 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1850 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001851 CCVal, Overflow);
1852
1853 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001854 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001855}
1856
1857// Prefetch operands are:
1858// 1: Address to prefetch
1859// 2: bool isWrite
1860// 3: int locality (0 = no locality ... 3 = extreme locality)
1861// 4: bool isDataCache
1862static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1863 SDLoc DL(Op);
1864 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1865 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001866 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001867
1868 bool IsStream = !Locality;
1869 // When the locality number is set
1870 if (Locality) {
1871 // The front-end should have filtered out the out-of-range values
1872 assert(Locality <= 3 && "Prefetch locality out-of-range");
1873 // The locality degree is the opposite of the cache speed.
1874 // Put the number the other way around.
1875 // The encoding starts at 0 for level 1
1876 Locality = 3 - Locality;
1877 }
1878
1879 // built the mask value encoding the expected behavior.
1880 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001881 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001882 (Locality << 1) | // Cache level bits
1883 (unsigned)IsStream; // Stream bit
1884 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001885 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001886}
1887
1888SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1889 SelectionDAG &DAG) const {
1890 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1891
1892 RTLIB::Libcall LC;
1893 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1894
1895 return LowerF128Call(Op, DAG, LC);
1896}
1897
1898SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1899 SelectionDAG &DAG) const {
1900 if (Op.getOperand(0).getValueType() != MVT::f128) {
1901 // It's legal except when f128 is involved
1902 return Op;
1903 }
1904
1905 RTLIB::Libcall LC;
1906 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1907
1908 // FP_ROUND node has a second operand indicating whether it is known to be
1909 // precise. That doesn't take part in the LibCall so we can't directly use
1910 // LowerF128Call.
1911 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001912 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1913 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001914}
1915
1916static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1917 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1918 // Any additional optimization in this function should be recorded
1919 // in the cost tables.
1920 EVT InVT = Op.getOperand(0).getValueType();
1921 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001922 unsigned NumElts = InVT.getVectorNumElements();
1923
1924 // f16 vectors are promoted to f32 before a conversion.
1925 if (InVT.getVectorElementType() == MVT::f16) {
1926 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1927 SDLoc dl(Op);
1928 return DAG.getNode(
1929 Op.getOpcode(), dl, Op.getValueType(),
1930 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1931 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001932
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001933 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001934 SDLoc dl(Op);
1935 SDValue Cv =
1936 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1937 Op.getOperand(0));
1938 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001939 }
1940
1941 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001942 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001943 MVT ExtVT =
1944 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1945 VT.getVectorNumElements());
1946 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001947 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1948 }
1949
1950 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001951 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001952}
1953
1954SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1955 SelectionDAG &DAG) const {
1956 if (Op.getOperand(0).getValueType().isVector())
1957 return LowerVectorFP_TO_INT(Op, DAG);
1958
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001959 // f16 conversions are promoted to f32.
1960 if (Op.getOperand(0).getValueType() == MVT::f16) {
1961 SDLoc dl(Op);
1962 return DAG.getNode(
1963 Op.getOpcode(), dl, Op.getValueType(),
1964 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1965 }
1966
Tim Northover3b0846e2014-05-24 12:50:23 +00001967 if (Op.getOperand(0).getValueType() != MVT::f128) {
1968 // It's legal except when f128 is involved
1969 return Op;
1970 }
1971
1972 RTLIB::Libcall LC;
1973 if (Op.getOpcode() == ISD::FP_TO_SINT)
1974 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1975 else
1976 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1977
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001978 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001979 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001980}
1981
1982static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1983 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1984 // Any additional optimization in this function should be recorded
1985 // in the cost tables.
1986 EVT VT = Op.getValueType();
1987 SDLoc dl(Op);
1988 SDValue In = Op.getOperand(0);
1989 EVT InVT = In.getValueType();
1990
Tim Northoveref0d7602014-06-15 09:27:06 +00001991 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1992 MVT CastVT =
1993 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1994 InVT.getVectorNumElements());
1995 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001996 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001997 }
1998
Tim Northoveref0d7602014-06-15 09:27:06 +00001999 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2000 unsigned CastOpc =
2001 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2002 EVT CastVT = VT.changeVectorElementTypeToInteger();
2003 In = DAG.getNode(CastOpc, dl, CastVT, In);
2004 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002005 }
2006
Tim Northoveref0d7602014-06-15 09:27:06 +00002007 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002008}
2009
2010SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2011 SelectionDAG &DAG) const {
2012 if (Op.getValueType().isVector())
2013 return LowerVectorINT_TO_FP(Op, DAG);
2014
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002015 // f16 conversions are promoted to f32.
2016 if (Op.getValueType() == MVT::f16) {
2017 SDLoc dl(Op);
2018 return DAG.getNode(
2019 ISD::FP_ROUND, dl, MVT::f16,
2020 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002021 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002022 }
2023
Tim Northover3b0846e2014-05-24 12:50:23 +00002024 // i128 conversions are libcalls.
2025 if (Op.getOperand(0).getValueType() == MVT::i128)
2026 return SDValue();
2027
2028 // Other conversions are legal, unless it's to the completely software-based
2029 // fp128.
2030 if (Op.getValueType() != MVT::f128)
2031 return Op;
2032
2033 RTLIB::Libcall LC;
2034 if (Op.getOpcode() == ISD::SINT_TO_FP)
2035 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2036 else
2037 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2038
2039 return LowerF128Call(Op, DAG, LC);
2040}
2041
2042SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2043 SelectionDAG &DAG) const {
2044 // For iOS, we want to call an alternative entry point: __sincos_stret,
2045 // which returns the values in two S / D registers.
2046 SDLoc dl(Op);
2047 SDValue Arg = Op.getOperand(0);
2048 EVT ArgVT = Arg.getValueType();
2049 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2050
2051 ArgListTy Args;
2052 ArgListEntry Entry;
2053
2054 Entry.Node = Arg;
2055 Entry.Ty = ArgTy;
2056 Entry.isSExt = false;
2057 Entry.isZExt = false;
2058 Args.push_back(Entry);
2059
2060 const char *LibcallName =
2061 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002062 SDValue Callee =
2063 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002064
Reid Kleckner343c3952014-11-20 23:51:47 +00002065 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002066 TargetLowering::CallLoweringInfo CLI(DAG);
2067 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00002068 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002069
2070 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2071 return CallResult.first;
2072}
2073
Tim Northoverf8bfe212014-07-18 13:07:05 +00002074static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2075 if (Op.getValueType() != MVT::f16)
2076 return SDValue();
2077
2078 assert(Op.getOperand(0).getValueType() == MVT::i16);
2079 SDLoc DL(Op);
2080
2081 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2082 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2083 return SDValue(
2084 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002085 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002086 0);
2087}
2088
Chad Rosierd9d0f862014-10-08 02:31:24 +00002089static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2090 if (OrigVT.getSizeInBits() >= 64)
2091 return OrigVT;
2092
2093 assert(OrigVT.isSimple() && "Expecting a simple value type");
2094
2095 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2096 switch (OrigSimpleTy) {
2097 default: llvm_unreachable("Unexpected Vector Type");
2098 case MVT::v2i8:
2099 case MVT::v2i16:
2100 return MVT::v2i32;
2101 case MVT::v4i8:
2102 return MVT::v4i16;
2103 }
2104}
2105
2106static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2107 const EVT &OrigTy,
2108 const EVT &ExtTy,
2109 unsigned ExtOpcode) {
2110 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2111 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2112 // 64-bits we need to insert a new extension so that it will be 64-bits.
2113 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2114 if (OrigTy.getSizeInBits() >= 64)
2115 return N;
2116
2117 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2118 EVT NewVT = getExtensionTo64Bits(OrigTy);
2119
2120 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2121}
2122
2123static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2124 bool isSigned) {
2125 EVT VT = N->getValueType(0);
2126
2127 if (N->getOpcode() != ISD::BUILD_VECTOR)
2128 return false;
2129
Pete Cooper3af9a252015-06-26 18:17:36 +00002130 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002131 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2132 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2133 unsigned HalfSize = EltSize / 2;
2134 if (isSigned) {
2135 if (!isIntN(HalfSize, C->getSExtValue()))
2136 return false;
2137 } else {
2138 if (!isUIntN(HalfSize, C->getZExtValue()))
2139 return false;
2140 }
2141 continue;
2142 }
2143 return false;
2144 }
2145
2146 return true;
2147}
2148
2149static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2150 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2151 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2152 N->getOperand(0)->getValueType(0),
2153 N->getValueType(0),
2154 N->getOpcode());
2155
2156 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2157 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002158 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002159 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2160 unsigned NumElts = VT.getVectorNumElements();
2161 MVT TruncVT = MVT::getIntegerVT(EltSize);
2162 SmallVector<SDValue, 8> Ops;
2163 for (unsigned i = 0; i != NumElts; ++i) {
2164 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2165 const APInt &CInt = C->getAPIntValue();
2166 // Element types smaller than 32 bits are not legal, so use i32 elements.
2167 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002168 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002169 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002170 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002171}
2172
2173static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2174 if (N->getOpcode() == ISD::SIGN_EXTEND)
2175 return true;
2176 if (isExtendedBUILD_VECTOR(N, DAG, true))
2177 return true;
2178 return false;
2179}
2180
2181static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2182 if (N->getOpcode() == ISD::ZERO_EXTEND)
2183 return true;
2184 if (isExtendedBUILD_VECTOR(N, DAG, false))
2185 return true;
2186 return false;
2187}
2188
2189static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2190 unsigned Opcode = N->getOpcode();
2191 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2192 SDNode *N0 = N->getOperand(0).getNode();
2193 SDNode *N1 = N->getOperand(1).getNode();
2194 return N0->hasOneUse() && N1->hasOneUse() &&
2195 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2196 }
2197 return false;
2198}
2199
2200static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2201 unsigned Opcode = N->getOpcode();
2202 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2203 SDNode *N0 = N->getOperand(0).getNode();
2204 SDNode *N1 = N->getOperand(1).getNode();
2205 return N0->hasOneUse() && N1->hasOneUse() &&
2206 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2207 }
2208 return false;
2209}
2210
2211static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2212 // Multiplications are only custom-lowered for 128-bit vectors so that
2213 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2214 EVT VT = Op.getValueType();
2215 assert(VT.is128BitVector() && VT.isInteger() &&
2216 "unexpected type for custom-lowering ISD::MUL");
2217 SDNode *N0 = Op.getOperand(0).getNode();
2218 SDNode *N1 = Op.getOperand(1).getNode();
2219 unsigned NewOpc = 0;
2220 bool isMLA = false;
2221 bool isN0SExt = isSignExtended(N0, DAG);
2222 bool isN1SExt = isSignExtended(N1, DAG);
2223 if (isN0SExt && isN1SExt)
2224 NewOpc = AArch64ISD::SMULL;
2225 else {
2226 bool isN0ZExt = isZeroExtended(N0, DAG);
2227 bool isN1ZExt = isZeroExtended(N1, DAG);
2228 if (isN0ZExt && isN1ZExt)
2229 NewOpc = AArch64ISD::UMULL;
2230 else if (isN1SExt || isN1ZExt) {
2231 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2232 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2233 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2234 NewOpc = AArch64ISD::SMULL;
2235 isMLA = true;
2236 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2237 NewOpc = AArch64ISD::UMULL;
2238 isMLA = true;
2239 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2240 std::swap(N0, N1);
2241 NewOpc = AArch64ISD::UMULL;
2242 isMLA = true;
2243 }
2244 }
2245
2246 if (!NewOpc) {
2247 if (VT == MVT::v2i64)
2248 // Fall through to expand this. It is not legal.
2249 return SDValue();
2250 else
2251 // Other vector multiplications are legal.
2252 return Op;
2253 }
2254 }
2255
2256 // Legalize to a S/UMULL instruction
2257 SDLoc DL(Op);
2258 SDValue Op0;
2259 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2260 if (!isMLA) {
2261 Op0 = skipExtensionForVectorMULL(N0, DAG);
2262 assert(Op0.getValueType().is64BitVector() &&
2263 Op1.getValueType().is64BitVector() &&
2264 "unexpected types for extended operands to VMULL");
2265 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2266 }
2267 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2268 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2269 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2270 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2271 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2272 EVT Op1VT = Op1.getValueType();
2273 return DAG.getNode(N0->getOpcode(), DL, VT,
2274 DAG.getNode(NewOpc, DL, VT,
2275 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2276 DAG.getNode(NewOpc, DL, VT,
2277 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2278}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002279
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002280SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2281 SelectionDAG &DAG) const {
2282 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2283 SDLoc dl(Op);
2284 switch (IntNo) {
2285 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002286 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002287 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2288 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2289 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002290 case Intrinsic::aarch64_neon_smax:
2291 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2292 Op.getOperand(1), Op.getOperand(2));
2293 case Intrinsic::aarch64_neon_umax:
2294 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2295 Op.getOperand(1), Op.getOperand(2));
2296 case Intrinsic::aarch64_neon_smin:
2297 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2298 Op.getOperand(1), Op.getOperand(2));
2299 case Intrinsic::aarch64_neon_umin:
2300 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2301 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002302 }
2303}
2304
Tim Northover3b0846e2014-05-24 12:50:23 +00002305SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2306 SelectionDAG &DAG) const {
2307 switch (Op.getOpcode()) {
2308 default:
2309 llvm_unreachable("unimplemented operand");
2310 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002311 case ISD::BITCAST:
2312 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002313 case ISD::GlobalAddress:
2314 return LowerGlobalAddress(Op, DAG);
2315 case ISD::GlobalTLSAddress:
2316 return LowerGlobalTLSAddress(Op, DAG);
2317 case ISD::SETCC:
2318 return LowerSETCC(Op, DAG);
2319 case ISD::BR_CC:
2320 return LowerBR_CC(Op, DAG);
2321 case ISD::SELECT:
2322 return LowerSELECT(Op, DAG);
2323 case ISD::SELECT_CC:
2324 return LowerSELECT_CC(Op, DAG);
2325 case ISD::JumpTable:
2326 return LowerJumpTable(Op, DAG);
2327 case ISD::ConstantPool:
2328 return LowerConstantPool(Op, DAG);
2329 case ISD::BlockAddress:
2330 return LowerBlockAddress(Op, DAG);
2331 case ISD::VASTART:
2332 return LowerVASTART(Op, DAG);
2333 case ISD::VACOPY:
2334 return LowerVACOPY(Op, DAG);
2335 case ISD::VAARG:
2336 return LowerVAARG(Op, DAG);
2337 case ISD::ADDC:
2338 case ISD::ADDE:
2339 case ISD::SUBC:
2340 case ISD::SUBE:
2341 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2342 case ISD::SADDO:
2343 case ISD::UADDO:
2344 case ISD::SSUBO:
2345 case ISD::USUBO:
2346 case ISD::SMULO:
2347 case ISD::UMULO:
2348 return LowerXALUO(Op, DAG);
2349 case ISD::FADD:
2350 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2351 case ISD::FSUB:
2352 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2353 case ISD::FMUL:
2354 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2355 case ISD::FDIV:
2356 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2357 case ISD::FP_ROUND:
2358 return LowerFP_ROUND(Op, DAG);
2359 case ISD::FP_EXTEND:
2360 return LowerFP_EXTEND(Op, DAG);
2361 case ISD::FRAMEADDR:
2362 return LowerFRAMEADDR(Op, DAG);
2363 case ISD::RETURNADDR:
2364 return LowerRETURNADDR(Op, DAG);
2365 case ISD::INSERT_VECTOR_ELT:
2366 return LowerINSERT_VECTOR_ELT(Op, DAG);
2367 case ISD::EXTRACT_VECTOR_ELT:
2368 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2369 case ISD::BUILD_VECTOR:
2370 return LowerBUILD_VECTOR(Op, DAG);
2371 case ISD::VECTOR_SHUFFLE:
2372 return LowerVECTOR_SHUFFLE(Op, DAG);
2373 case ISD::EXTRACT_SUBVECTOR:
2374 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2375 case ISD::SRA:
2376 case ISD::SRL:
2377 case ISD::SHL:
2378 return LowerVectorSRA_SRL_SHL(Op, DAG);
2379 case ISD::SHL_PARTS:
2380 return LowerShiftLeftParts(Op, DAG);
2381 case ISD::SRL_PARTS:
2382 case ISD::SRA_PARTS:
2383 return LowerShiftRightParts(Op, DAG);
2384 case ISD::CTPOP:
2385 return LowerCTPOP(Op, DAG);
2386 case ISD::FCOPYSIGN:
2387 return LowerFCOPYSIGN(Op, DAG);
2388 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002389 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002390 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002391 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002392 case ISD::XOR:
2393 return LowerXOR(Op, DAG);
2394 case ISD::PREFETCH:
2395 return LowerPREFETCH(Op, DAG);
2396 case ISD::SINT_TO_FP:
2397 case ISD::UINT_TO_FP:
2398 return LowerINT_TO_FP(Op, DAG);
2399 case ISD::FP_TO_SINT:
2400 case ISD::FP_TO_UINT:
2401 return LowerFP_TO_INT(Op, DAG);
2402 case ISD::FSINCOS:
2403 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002404 case ISD::MUL:
2405 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002406 case ISD::INTRINSIC_WO_CHAIN:
2407 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002408 }
2409}
2410
Tim Northover3b0846e2014-05-24 12:50:23 +00002411//===----------------------------------------------------------------------===//
2412// Calling Convention Implementation
2413//===----------------------------------------------------------------------===//
2414
2415#include "AArch64GenCallingConv.inc"
2416
Robin Morisset039781e2014-08-29 21:53:01 +00002417/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002418CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2419 bool IsVarArg) const {
2420 switch (CC) {
2421 default:
2422 llvm_unreachable("Unsupported calling convention.");
2423 case CallingConv::WebKit_JS:
2424 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002425 case CallingConv::GHC:
2426 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002427 case CallingConv::C:
2428 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002429 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002430 case CallingConv::CXX_FAST_TLS:
Tim Northover3b0846e2014-05-24 12:50:23 +00002431 if (!Subtarget->isTargetDarwin())
2432 return CC_AArch64_AAPCS;
2433 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2434 }
2435}
2436
2437SDValue AArch64TargetLowering::LowerFormalArguments(
2438 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002439 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2440 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002441 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002442 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002443
2444 // Assign locations to all of the incoming arguments.
2445 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002446 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2447 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002448
2449 // At this point, Ins[].VT may already be promoted to i32. To correctly
2450 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2451 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2452 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2453 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2454 // LocVT.
2455 unsigned NumArgs = Ins.size();
2456 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2457 unsigned CurArgIdx = 0;
2458 for (unsigned i = 0; i != NumArgs; ++i) {
2459 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002460 if (Ins[i].isOrigArg()) {
2461 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2462 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002463
Andrew Trick05938a52015-02-16 18:10:47 +00002464 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002465 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2466 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002467 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2468 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2469 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2470 ValVT = MVT::i8;
2471 else if (ActualMVT == MVT::i16)
2472 ValVT = MVT::i16;
2473 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002474 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2475 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002476 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002477 assert(!Res && "Call operand has unhandled type");
2478 (void)Res;
2479 }
2480 assert(ArgLocs.size() == Ins.size());
2481 SmallVector<SDValue, 16> ArgValues;
2482 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2483 CCValAssign &VA = ArgLocs[i];
2484
2485 if (Ins[i].Flags.isByVal()) {
2486 // Byval is used for HFAs in the PCS, but the system should work in a
2487 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002488 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002489 int Size = Ins[i].Flags.getByValSize();
2490 unsigned NumRegs = (Size + 7) / 8;
2491
2492 // FIXME: This works on big-endian for composite byvals, which are the common
2493 // case. It should also work for fundamental types too.
2494 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002495 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002496 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002497 InVals.push_back(FrameIdxN);
2498
2499 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002500 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002501
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002502 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002503 // Arguments stored in registers.
2504 EVT RegVT = VA.getLocVT();
2505
2506 SDValue ArgValue;
2507 const TargetRegisterClass *RC;
2508
2509 if (RegVT == MVT::i32)
2510 RC = &AArch64::GPR32RegClass;
2511 else if (RegVT == MVT::i64)
2512 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002513 else if (RegVT == MVT::f16)
2514 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002515 else if (RegVT == MVT::f32)
2516 RC = &AArch64::FPR32RegClass;
2517 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2518 RC = &AArch64::FPR64RegClass;
2519 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2520 RC = &AArch64::FPR128RegClass;
2521 else
2522 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2523
2524 // Transform the arguments in physical registers into virtual ones.
2525 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2526 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2527
2528 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2529 // to 64 bits. Insert an assert[sz]ext to capture this, then
2530 // truncate to the right size.
2531 switch (VA.getLocInfo()) {
2532 default:
2533 llvm_unreachable("Unknown loc info!");
2534 case CCValAssign::Full:
2535 break;
2536 case CCValAssign::BCvt:
2537 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2538 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002539 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002540 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002541 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002542 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2543 // nodes after our lowering.
2544 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002545 break;
2546 }
2547
2548 InVals.push_back(ArgValue);
2549
2550 } else { // VA.isRegLoc()
2551 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2552 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002553 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002554
2555 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002556 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2557 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002558 BEAlign = 8 - ArgSize;
2559
Matthias Braun941a7052016-07-28 18:40:00 +00002560 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002561
2562 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002563 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002564 SDValue ArgValue;
2565
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002566 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002567 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002568 MVT MemVT = VA.getValVT();
2569
Tim Northover47e003c2014-05-26 17:21:53 +00002570 switch (VA.getLocInfo()) {
2571 default:
2572 break;
Tim Northover6890add2014-06-03 13:54:53 +00002573 case CCValAssign::BCvt:
2574 MemVT = VA.getLocVT();
2575 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002576 case CCValAssign::SExt:
2577 ExtType = ISD::SEXTLOAD;
2578 break;
2579 case CCValAssign::ZExt:
2580 ExtType = ISD::ZEXTLOAD;
2581 break;
2582 case CCValAssign::AExt:
2583 ExtType = ISD::EXTLOAD;
2584 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002585 }
2586
Alex Lorenze40c8a22015-08-11 23:09:45 +00002587 ArgValue = DAG.getExtLoad(
2588 ExtType, DL, VA.getLocVT(), Chain, FIN,
2589 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002590 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002591
Tim Northover3b0846e2014-05-24 12:50:23 +00002592 InVals.push_back(ArgValue);
2593 }
2594 }
2595
2596 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002597 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002598 if (isVarArg) {
2599 if (!Subtarget->isTargetDarwin()) {
2600 // The AAPCS variadic function ABI is identical to the non-variadic
2601 // one. As a result there may be more arguments in registers and we should
2602 // save them for future reference.
2603 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2604 }
2605
Tim Northover3b0846e2014-05-24 12:50:23 +00002606 // This will point to the next argument passed via stack.
2607 unsigned StackOffset = CCInfo.getNextStackOffset();
2608 // We currently pass all varargs at 8-byte alignment.
2609 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002610 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002611 }
2612
Tim Northover3b0846e2014-05-24 12:50:23 +00002613 unsigned StackArgSize = CCInfo.getNextStackOffset();
2614 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2615 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2616 // This is a non-standard ABI so by fiat I say we're allowed to make full
2617 // use of the stack area to be popped, which must be aligned to 16 bytes in
2618 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002619 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002620
2621 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2622 // a multiple of 16.
2623 FuncInfo->setArgumentStackToRestore(StackArgSize);
2624
2625 // This realignment carries over to the available bytes below. Our own
2626 // callers will guarantee the space is free by giving an aligned value to
2627 // CALLSEQ_START.
2628 }
2629 // Even if we're not expected to free up the space, it's useful to know how
2630 // much is there while considering tail calls (because we can reuse it).
2631 FuncInfo->setBytesInStackArgArea(StackArgSize);
2632
2633 return Chain;
2634}
2635
2636void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002637 SelectionDAG &DAG,
2638 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002639 SDValue &Chain) const {
2640 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002641 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002642 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002643 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002644
2645 SmallVector<SDValue, 8> MemOps;
2646
2647 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2648 AArch64::X3, AArch64::X4, AArch64::X5,
2649 AArch64::X6, AArch64::X7 };
2650 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002651 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002652
2653 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2654 int GPRIdx = 0;
2655 if (GPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002656 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002657
Mehdi Amini44ede332015-07-09 02:09:04 +00002658 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002659
2660 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2661 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2662 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002663 SDValue Store = DAG.getStore(
2664 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002665 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002666 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002667 FIN =
2668 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002669 }
2670 }
2671 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2672 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2673
2674 if (Subtarget->hasFPARMv8()) {
2675 static const MCPhysReg FPRArgRegs[] = {
2676 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2677 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2678 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002679 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002680
2681 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2682 int FPRIdx = 0;
2683 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002684 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002685
Mehdi Amini44ede332015-07-09 02:09:04 +00002686 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002687
2688 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2689 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2690 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2691
Alex Lorenze40c8a22015-08-11 23:09:45 +00002692 SDValue Store = DAG.getStore(
2693 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002694 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00002695 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002696 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2697 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002698 }
2699 }
2700 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2701 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2702 }
2703
2704 if (!MemOps.empty()) {
2705 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2706 }
2707}
2708
2709/// LowerCallResult - Lower the result values of a call into the
2710/// appropriate copies out of appropriate physical registers.
2711SDValue AArch64TargetLowering::LowerCallResult(
2712 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002713 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2714 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002715 SDValue ThisVal) const {
2716 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2717 ? RetCC_AArch64_WebKit_JS
2718 : RetCC_AArch64_AAPCS;
2719 // Assign locations to each value returned by this call.
2720 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002721 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2722 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002723 CCInfo.AnalyzeCallResult(Ins, RetCC);
2724
2725 // Copy all of the result registers out of their specified physreg.
2726 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2727 CCValAssign VA = RVLocs[i];
2728
2729 // Pass 'this' value directly from the argument to return value, to avoid
2730 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00002731 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002732 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2733 "unexpected return calling convention register assignment");
2734 InVals.push_back(ThisVal);
2735 continue;
2736 }
2737
2738 SDValue Val =
2739 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2740 Chain = Val.getValue(1);
2741 InFlag = Val.getValue(2);
2742
2743 switch (VA.getLocInfo()) {
2744 default:
2745 llvm_unreachable("Unknown loc info!");
2746 case CCValAssign::Full:
2747 break;
2748 case CCValAssign::BCvt:
2749 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2750 break;
2751 }
2752
2753 InVals.push_back(Val);
2754 }
2755
2756 return Chain;
2757}
2758
2759bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2760 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00002761 const SmallVectorImpl<ISD::OutputArg> &Outs,
2762 const SmallVectorImpl<SDValue> &OutVals,
2763 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2764 // For CallingConv::C this function knows whether the ABI needs
2765 // changing. That's not true for other conventions so they will have to opt in
2766 // manually.
2767 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2768 return false;
2769
Matthias Braun8d414362016-03-30 22:46:04 +00002770 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002771 const Function *CallerF = MF.getFunction();
2772 CallingConv::ID CallerCC = CallerF->getCallingConv();
2773 bool CCMatch = CallerCC == CalleeCC;
2774
2775 // Byval parameters hand the function a pointer directly into the stack area
2776 // we want to reuse during a tail call. Working around this *is* possible (see
2777 // X86) but less efficient and uglier in LowerCall.
2778 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2779 e = CallerF->arg_end();
2780 i != e; ++i)
2781 if (i->hasByValAttr())
2782 return false;
2783
2784 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
Eric Christopher114fa1c2016-02-29 22:50:49 +00002785 return IsTailCallConvention(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002786 }
2787
Oliver Stannard12993dd2014-08-18 12:42:15 +00002788 // Externally-defined functions with weak linkage should not be
2789 // tail-called on AArch64 when the OS does not support dynamic
2790 // pre-emption of symbols, as the AAELF spec requires normal calls
2791 // to undefined weak functions to be replaced with a NOP or jump to the
2792 // next instruction. The behaviour of branch instructions in this
2793 // situation (as used for tail calls) is implementation-defined, so we
2794 // cannot rely on the linker replacing the tail call with a return.
2795 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2796 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002797 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002798 if (GV->hasExternalWeakLinkage() &&
2799 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002800 return false;
2801 }
2802
Tim Northover3b0846e2014-05-24 12:50:23 +00002803 // Now we search for cases where we can use a tail call without changing the
2804 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2805 // concept.
2806
2807 // I want anyone implementing a new calling convention to think long and hard
2808 // about this assert.
2809 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2810 "Unexpected variadic calling convention");
2811
Matthias Braun8d414362016-03-30 22:46:04 +00002812 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00002813 if (isVarArg && !Outs.empty()) {
2814 // At least two cases here: if caller is fastcc then we can't have any
2815 // memory arguments (we'd be expected to clean up the stack afterwards). If
2816 // caller is C then we could potentially use its argument area.
2817
2818 // FIXME: for now we take the most conservative of these in both cases:
2819 // disallow all variadic memory operands.
2820 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002821 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002822
2823 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002824 for (const CCValAssign &ArgLoc : ArgLocs)
2825 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002826 return false;
2827 }
2828
Matthias Braun8d414362016-03-30 22:46:04 +00002829 // Check that the call results are passed in the same way.
2830 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2831 CCAssignFnForCall(CalleeCC, isVarArg),
2832 CCAssignFnForCall(CallerCC, isVarArg)))
2833 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00002834 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00002835 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2836 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00002837 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00002838 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2839 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00002840 return false;
2841 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002842
2843 // Nothing more to check if the callee is taking no arguments
2844 if (Outs.empty())
2845 return true;
2846
2847 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002848 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002849
2850 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2851
2852 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2853
Matthias Braun74a0bd32016-04-13 21:43:16 +00002854 // If the stack arguments for this call do not fit into our own save area then
2855 // the call cannot be made tail.
2856 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2857 return false;
2858
Matthias Braun46b0f032016-04-14 01:10:42 +00002859 const MachineRegisterInfo &MRI = MF.getRegInfo();
2860 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2861 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00002862
2863 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00002864}
2865
2866SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2867 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00002868 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00002869 int ClobberedFI) const {
2870 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00002871 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2872 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002873
2874 // Include the original chain at the beginning of the list. When this is
2875 // used by target LowerCall hooks, this helps legalize find the
2876 // CALLSEQ_BEGIN node.
2877 ArgChains.push_back(Chain);
2878
2879 // Add a chain value for each stack argument corresponding
2880 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2881 UE = DAG.getEntryNode().getNode()->use_end();
2882 U != UE; ++U)
2883 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2884 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2885 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002886 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00002887 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00002888 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002889
2890 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2891 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2892 ArgChains.push_back(SDValue(L, 1));
2893 }
2894
2895 // Build a tokenfactor for all the chains.
2896 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2897}
2898
2899bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2900 bool TailCallOpt) const {
2901 return CallCC == CallingConv::Fast && TailCallOpt;
2902}
2903
2904bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002905 return CallCC == CallingConv::Fast ||
2906 CallCC == CallingConv::PreserveMost;
Tim Northover3b0846e2014-05-24 12:50:23 +00002907}
2908
2909/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2910/// and add input and output parameter nodes.
2911SDValue
2912AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2913 SmallVectorImpl<SDValue> &InVals) const {
2914 SelectionDAG &DAG = CLI.DAG;
2915 SDLoc &DL = CLI.DL;
2916 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2917 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2918 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2919 SDValue Chain = CLI.Chain;
2920 SDValue Callee = CLI.Callee;
2921 bool &IsTailCall = CLI.IsTailCall;
2922 CallingConv::ID CallConv = CLI.CallConv;
2923 bool IsVarArg = CLI.IsVarArg;
2924
2925 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002926 bool IsThisReturn = false;
2927
2928 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2929 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2930 bool IsSibCall = false;
2931
2932 if (IsTailCall) {
2933 // Check if it's really possible to do a tail call.
2934 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00002935 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002936 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2937 report_fatal_error("failed to perform tail call elimination on a call "
2938 "site marked musttail");
2939
2940 // A sibling call is one where we're under the usual C ABI and not planning
2941 // to change that but can still do a tail call:
2942 if (!TailCallOpt && IsTailCall)
2943 IsSibCall = true;
2944
2945 if (IsTailCall)
2946 ++NumTailCalls;
2947 }
2948
2949 // Analyze operands of the call, assigning locations to each operand.
2950 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002951 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2952 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002953
2954 if (IsVarArg) {
2955 // Handle fixed and variable vector arguments differently.
2956 // Variable vector arguments always go into memory.
2957 unsigned NumArgs = Outs.size();
2958
2959 for (unsigned i = 0; i != NumArgs; ++i) {
2960 MVT ArgVT = Outs[i].VT;
2961 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2962 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2963 /*IsVarArg=*/ !Outs[i].IsFixed);
2964 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2965 assert(!Res && "Call operand has unhandled type");
2966 (void)Res;
2967 }
2968 } else {
2969 // At this point, Outs[].VT may already be promoted to i32. To correctly
2970 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2971 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2972 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2973 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2974 // LocVT.
2975 unsigned NumArgs = Outs.size();
2976 for (unsigned i = 0; i != NumArgs; ++i) {
2977 MVT ValVT = Outs[i].VT;
2978 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002979 EVT ActualVT = getValueType(DAG.getDataLayout(),
2980 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002981 /*AllowUnknown*/ true);
2982 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2983 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2984 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002985 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002986 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002987 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002988 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002989
2990 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002991 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002992 assert(!Res && "Call operand has unhandled type");
2993 (void)Res;
2994 }
2995 }
2996
2997 // Get a count of how many bytes are to be pushed on the stack.
2998 unsigned NumBytes = CCInfo.getNextStackOffset();
2999
3000 if (IsSibCall) {
3001 // Since we're not changing the ABI to make this a tail call, the memory
3002 // operands are already available in the caller's incoming argument space.
3003 NumBytes = 0;
3004 }
3005
3006 // FPDiff is the byte offset of the call's argument area from the callee's.
3007 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3008 // by this amount for a tail call. In a sibling call it must be 0 because the
3009 // caller will deallocate the entire stack and the callee still expects its
3010 // arguments to begin at SP+0. Completely unused for non-tail calls.
3011 int FPDiff = 0;
3012
3013 if (IsTailCall && !IsSibCall) {
3014 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3015
3016 // Since callee will pop argument stack as a tail call, we must keep the
3017 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003018 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003019
3020 // FPDiff will be negative if this tail call requires more space than we
3021 // would automatically have in our incoming argument space. Positive if we
3022 // can actually shrink the stack.
3023 FPDiff = NumReusableBytes - NumBytes;
3024
3025 // The stack pointer must be 16-byte aligned at all times it's used for a
3026 // memory operation, which in practice means at *all* times and in
3027 // particular across call boundaries. Therefore our own arguments started at
3028 // a 16-byte aligned SP and the delta applied for the tail call should
3029 // satisfy the same constraint.
3030 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3031 }
3032
3033 // Adjust the stack pointer for the new arguments...
3034 // These operations are automatically eliminated by the prolog/epilog pass
3035 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003036 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3037 true),
3038 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003039
Mehdi Amini44ede332015-07-09 02:09:04 +00003040 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3041 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003042
3043 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3044 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003045 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003046
3047 // Walk the register/memloc assignments, inserting copies/loads.
3048 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3049 ++i, ++realArgIdx) {
3050 CCValAssign &VA = ArgLocs[i];
3051 SDValue Arg = OutVals[realArgIdx];
3052 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3053
3054 // Promote the value if needed.
3055 switch (VA.getLocInfo()) {
3056 default:
3057 llvm_unreachable("Unknown loc info!");
3058 case CCValAssign::Full:
3059 break;
3060 case CCValAssign::SExt:
3061 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3062 break;
3063 case CCValAssign::ZExt:
3064 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3065 break;
3066 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003067 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3068 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3069 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3070 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3071 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003072 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3073 break;
3074 case CCValAssign::BCvt:
3075 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3076 break;
3077 case CCValAssign::FPExt:
3078 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3079 break;
3080 }
3081
3082 if (VA.isRegLoc()) {
3083 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3084 assert(VA.getLocVT() == MVT::i64 &&
3085 "unexpected calling convention register assignment");
3086 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3087 "unexpected use of 'returned'");
3088 IsThisReturn = true;
3089 }
3090 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3091 } else {
3092 assert(VA.isMemLoc());
3093
3094 SDValue DstAddr;
3095 MachinePointerInfo DstInfo;
3096
3097 // FIXME: This works on big-endian for composite byvals, which are the
3098 // common case. It should also work for fundamental types too.
3099 uint32_t BEAlign = 0;
3100 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003101 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003102 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003103 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3104 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003105 if (OpSize < 8)
3106 BEAlign = 8 - OpSize;
3107 }
3108 unsigned LocMemOffset = VA.getLocMemOffset();
3109 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003110 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003111 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003112
3113 if (IsTailCall) {
3114 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003115 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003116
Mehdi Amini44ede332015-07-09 02:09:04 +00003117 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003118 DstInfo =
3119 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003120
3121 // Make sure any stack arguments overlapping with where we're storing
3122 // are loaded before this eventual operation. Otherwise they'll be
3123 // clobbered.
3124 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3125 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003126 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003127
Mehdi Amini44ede332015-07-09 02:09:04 +00003128 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003129 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3130 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003131 }
3132
3133 if (Outs[i].Flags.isByVal()) {
3134 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003135 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003136 SDValue Cpy = DAG.getMemcpy(
3137 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003138 /*isVol = */ false, /*AlwaysInline = */ false,
3139 /*isTailCall = */ false,
3140 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003141
3142 MemOpChains.push_back(Cpy);
3143 } else {
3144 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3145 // promoted to a legal register type i32, we should truncate Arg back to
3146 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003147 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3148 VA.getValVT() == MVT::i16)
3149 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003150
Justin Lebar9c375812016-07-15 18:27:10 +00003151 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003152 MemOpChains.push_back(Store);
3153 }
3154 }
3155 }
3156
3157 if (!MemOpChains.empty())
3158 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3159
3160 // Build a sequence of copy-to-reg nodes chained together with token chain
3161 // and flag operands which copy the outgoing args into the appropriate regs.
3162 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003163 for (auto &RegToPass : RegsToPass) {
3164 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3165 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003166 InFlag = Chain.getValue(1);
3167 }
3168
3169 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3170 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3171 // node so that legalize doesn't hack it.
3172 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3173 Subtarget->isTargetMachO()) {
3174 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3175 const GlobalValue *GV = G->getGlobal();
3176 bool InternalLinkage = GV->hasInternalLinkage();
3177 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003178 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003179 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003180 Callee =
3181 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3182 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003183 }
3184 } else if (ExternalSymbolSDNode *S =
3185 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3186 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003187 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3188 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003189 }
3190 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3191 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003192 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003193 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3194 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003195 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003196 }
3197
3198 // We don't usually want to end the call-sequence here because we would tidy
3199 // the frame up *after* the call, however in the ABI-changing tail-call case
3200 // we've carefully laid out the parameters so that when sp is reset they'll be
3201 // in the correct location.
3202 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003203 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3204 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003205 InFlag = Chain.getValue(1);
3206 }
3207
3208 std::vector<SDValue> Ops;
3209 Ops.push_back(Chain);
3210 Ops.push_back(Callee);
3211
3212 if (IsTailCall) {
3213 // Each tail call may have to adjust the stack by a different amount, so
3214 // this information must travel along with the operation for eventual
3215 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003216 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003217 }
3218
3219 // Add argument registers to the end of the list so that they are known live
3220 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003221 for (auto &RegToPass : RegsToPass)
3222 Ops.push_back(DAG.getRegister(RegToPass.first,
3223 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003224
3225 // Add a register mask operand representing the call-preserved registers.
3226 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003227 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003228 if (IsThisReturn) {
3229 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003230 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003231 if (!Mask) {
3232 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003233 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003234 }
3235 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003236 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003237
3238 assert(Mask && "Missing call preserved mask for calling convention");
3239 Ops.push_back(DAG.getRegisterMask(Mask));
3240
3241 if (InFlag.getNode())
3242 Ops.push_back(InFlag);
3243
3244 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3245
3246 // If we're doing a tall call, use a TC_RETURN here rather than an
3247 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003248 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003249 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003250 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003251 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003252
3253 // Returns a chain and a flag for retval copy to use.
3254 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3255 InFlag = Chain.getValue(1);
3256
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003257 uint64_t CalleePopBytes =
3258 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003259
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003260 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3261 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003262 InFlag, DL);
3263 if (!Ins.empty())
3264 InFlag = Chain.getValue(1);
3265
3266 // Handle result values, copying them out of physregs into vregs that we
3267 // return.
3268 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3269 InVals, IsThisReturn,
3270 IsThisReturn ? OutVals[0] : SDValue());
3271}
3272
3273bool AArch64TargetLowering::CanLowerReturn(
3274 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3275 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3276 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3277 ? RetCC_AArch64_WebKit_JS
3278 : RetCC_AArch64_AAPCS;
3279 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003280 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003281 return CCInfo.CheckReturn(Outs, RetCC);
3282}
3283
3284SDValue
3285AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3286 bool isVarArg,
3287 const SmallVectorImpl<ISD::OutputArg> &Outs,
3288 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003289 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003290 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3291 ? RetCC_AArch64_WebKit_JS
3292 : RetCC_AArch64_AAPCS;
3293 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003294 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3295 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003296 CCInfo.AnalyzeReturn(Outs, RetCC);
3297
3298 // Copy the result values into the output registers.
3299 SDValue Flag;
3300 SmallVector<SDValue, 4> RetOps(1, Chain);
3301 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3302 ++i, ++realRVLocIdx) {
3303 CCValAssign &VA = RVLocs[i];
3304 assert(VA.isRegLoc() && "Can only return in registers!");
3305 SDValue Arg = OutVals[realRVLocIdx];
3306
3307 switch (VA.getLocInfo()) {
3308 default:
3309 llvm_unreachable("Unknown loc info!");
3310 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003311 if (Outs[i].ArgVT == MVT::i1) {
3312 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3313 // value. This is strictly redundant on Darwin (which uses "zeroext
3314 // i1"), but will be optimised out before ISel.
3315 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3316 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3317 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003318 break;
3319 case CCValAssign::BCvt:
3320 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3321 break;
3322 }
3323
3324 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3325 Flag = Chain.getValue(1);
3326 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3327 }
Manman Rencbe4f942015-12-16 21:04:19 +00003328 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3329 const MCPhysReg *I =
3330 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3331 if (I) {
3332 for (; *I; ++I) {
3333 if (AArch64::GPR64RegClass.contains(*I))
3334 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3335 else if (AArch64::FPR64RegClass.contains(*I))
3336 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3337 else
3338 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3339 }
3340 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003341
3342 RetOps[0] = Chain; // Update chain.
3343
3344 // Add the flag if we have it.
3345 if (Flag.getNode())
3346 RetOps.push_back(Flag);
3347
3348 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3349}
3350
3351//===----------------------------------------------------------------------===//
3352// Other Lowering Code
3353//===----------------------------------------------------------------------===//
3354
3355SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3356 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003357 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003358 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003359 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3360 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003361 unsigned char OpFlags =
3362 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3363
3364 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3365 "unexpected offset in global node");
3366
3367 // This also catched the large code model case for Darwin.
3368 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3369 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3370 // FIXME: Once remat is capable of dealing with instructions with register
3371 // operands, expand this into two nodes instead of using a wrapper node.
3372 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3373 }
3374
3375 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3376 const unsigned char MO_NC = AArch64II::MO_NC;
3377 return DAG.getNode(
3378 AArch64ISD::WrapperLarge, DL, PtrVT,
3379 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3380 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3381 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3382 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3383 } else {
3384 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3385 // the only correct model on Darwin.
3386 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3387 OpFlags | AArch64II::MO_PAGE);
3388 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3389 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3390
3391 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3392 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3393 }
3394}
3395
3396/// \brief Convert a TLS address reference into the correct sequence of loads
3397/// and calls to compute the variable's address (for Darwin, currently) and
3398/// return an SDValue containing the final node.
3399
3400/// Darwin only has one TLS scheme which must be capable of dealing with the
3401/// fully general situation, in the worst case. This means:
3402/// + "extern __thread" declaration.
3403/// + Defined in a possibly unknown dynamic library.
3404///
3405/// The general system is that each __thread variable has a [3 x i64] descriptor
3406/// which contains information used by the runtime to calculate the address. The
3407/// only part of this the compiler needs to know about is the first xword, which
3408/// contains a function pointer that must be called with the address of the
3409/// entire descriptor in "x0".
3410///
3411/// Since this descriptor may be in a different unit, in general even the
3412/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3413/// is:
3414/// adrp x0, _var@TLVPPAGE
3415/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3416/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3417/// ; the function pointer
3418/// blr x1 ; Uses descriptor address in x0
3419/// ; Address of _var is now in x0.
3420///
3421/// If the address of _var's descriptor *is* known to the linker, then it can
3422/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3423/// a slight efficiency gain.
3424SDValue
3425AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3426 SelectionDAG &DAG) const {
3427 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3428
3429 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003430 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003431 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3432
3433 SDValue TLVPAddr =
3434 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3435 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3436
3437 // The first entry in the descriptor is a function pointer that we must call
3438 // to obtain the address of the variable.
3439 SDValue Chain = DAG.getEntryNode();
3440 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003441 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00003442 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3443 /* Alignment = */ 8, MachineMemOperand::MONonTemporal |
3444 MachineMemOperand::MOInvariant);
Tim Northover3b0846e2014-05-24 12:50:23 +00003445 Chain = FuncTLVGet.getValue(1);
3446
Matthias Braun941a7052016-07-28 18:40:00 +00003447 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3448 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003449
3450 // TLS calls preserve all registers except those that absolutely must be
3451 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3452 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003453 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003454 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003455
3456 // Finally, we can make the call. This is just a degenerate version of a
3457 // normal AArch64 call node: x0 takes the address of the descriptor, and
3458 // returns the address of the variable in this thread.
3459 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3460 Chain =
3461 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3462 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3463 DAG.getRegisterMask(Mask), Chain.getValue(1));
3464 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3465}
3466
3467/// When accessing thread-local variables under either the general-dynamic or
3468/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3469/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003470/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003471///
Kristof Beylsaea84612015-03-04 09:12:08 +00003472/// The sequence is:
3473/// adrp x0, :tlsdesc:var
3474/// ldr x1, [x0, #:tlsdesc_lo12:var]
3475/// add x0, x0, #:tlsdesc_lo12:var
3476/// .tlsdesccall var
3477/// blr x1
3478/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003479///
Kristof Beylsaea84612015-03-04 09:12:08 +00003480/// The above sequence must be produced unscheduled, to enable the linker to
3481/// optimize/relax this sequence.
3482/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3483/// above sequence, and expanded really late in the compilation flow, to ensure
3484/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003485SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3486 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003487 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003488 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003489
Kristof Beylsaea84612015-03-04 09:12:08 +00003490 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003491 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003492
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003493 Chain =
3494 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003495 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003496
3497 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3498}
3499
3500SDValue
3501AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3502 SelectionDAG &DAG) const {
3503 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3504 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3505 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003506 // Different choices can be made for the maximum size of the TLS area for a
3507 // module. For the small address model, the default TLS size is 16MiB and the
3508 // maximum TLS size is 4GiB.
3509 // FIXME: add -mtls-size command line option and make it control the 16MiB
3510 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003511 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3512
3513 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003514
3515 if (DAG.getTarget().Options.EmulatedTLS)
3516 return LowerToTLSEmulatedModel(GA, DAG);
3517
Kristof Beylsaea84612015-03-04 09:12:08 +00003518 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3519 if (Model == TLSModel::LocalDynamic)
3520 Model = TLSModel::GeneralDynamic;
3521 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003522
3523 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003524 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003525 SDLoc DL(Op);
3526 const GlobalValue *GV = GA->getGlobal();
3527
3528 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3529
3530 if (Model == TLSModel::LocalExec) {
3531 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003532 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003533 SDValue LoVar = DAG.getTargetGlobalAddress(
3534 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003535 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003536
Kristof Beylsaea84612015-03-04 09:12:08 +00003537 SDValue TPWithOff_lo =
3538 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003539 HiVar,
3540 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003541 0);
3542 SDValue TPWithOff =
3543 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003544 LoVar,
3545 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003546 0);
3547 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003548 } else if (Model == TLSModel::InitialExec) {
3549 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3550 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3551 } else if (Model == TLSModel::LocalDynamic) {
3552 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3553 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3554 // the beginning of the module's TLS region, followed by a DTPREL offset
3555 // calculation.
3556
3557 // These accesses will need deduplicating if there's more than one.
3558 AArch64FunctionInfo *MFI =
3559 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3560 MFI->incNumLocalDynamicTLSAccesses();
3561
Tim Northover3b0846e2014-05-24 12:50:23 +00003562 // The call needs a relocation too for linker relaxation. It doesn't make
3563 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3564 // the address.
3565 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3566 AArch64II::MO_TLS);
3567
3568 // Now we can calculate the offset from TPIDR_EL0 to this module's
3569 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003570 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003571
3572 // Now use :dtprel_whatever: operations to calculate this variable's offset
3573 // in its thread-storage area.
3574 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003575 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003576 SDValue LoVar = DAG.getTargetGlobalAddress(
3577 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003578 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3579
Kristof Beylsaea84612015-03-04 09:12:08 +00003580 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003581 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003582 0);
3583 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003584 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003585 0);
3586 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003587 // The call needs a relocation too for linker relaxation. It doesn't make
3588 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3589 // the address.
3590 SDValue SymAddr =
3591 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3592
3593 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003594 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003595 } else
3596 llvm_unreachable("Unsupported ELF TLS access model");
3597
3598 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3599}
3600
3601SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3602 SelectionDAG &DAG) const {
3603 if (Subtarget->isTargetDarwin())
3604 return LowerDarwinGlobalTLSAddress(Op, DAG);
3605 else if (Subtarget->isTargetELF())
3606 return LowerELFGlobalTLSAddress(Op, DAG);
3607
3608 llvm_unreachable("Unexpected platform trying to use TLS");
3609}
3610SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3611 SDValue Chain = Op.getOperand(0);
3612 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3613 SDValue LHS = Op.getOperand(2);
3614 SDValue RHS = Op.getOperand(3);
3615 SDValue Dest = Op.getOperand(4);
3616 SDLoc dl(Op);
3617
3618 // Handle f128 first, since lowering it will result in comparing the return
3619 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3620 // is expecting to deal with.
3621 if (LHS.getValueType() == MVT::f128) {
3622 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3623
3624 // If softenSetCCOperands returned a scalar, we need to compare the result
3625 // against zero to select between true and false values.
3626 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003627 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003628 CC = ISD::SETNE;
3629 }
3630 }
3631
3632 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3633 // instruction.
3634 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003635 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003636 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3637 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3638 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3639 "Unexpected condition code.");
3640 // Only lower legal XALUO ops.
3641 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3642 return SDValue();
3643
3644 // The actual operation with overflow check.
3645 AArch64CC::CondCode OFCC;
3646 SDValue Value, Overflow;
3647 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3648
3649 if (CC == ISD::SETNE)
3650 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003651 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003652
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003653 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3654 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003655 }
3656
3657 if (LHS.getValueType().isInteger()) {
3658 assert((LHS.getValueType() == RHS.getValueType()) &&
3659 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3660
3661 // If the RHS of the comparison is zero, we can potentially fold this
3662 // to a specialized branch.
3663 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3664 if (RHSC && RHSC->getZExtValue() == 0) {
3665 if (CC == ISD::SETEQ) {
3666 // See if we can use a TBZ to fold in an AND as well.
3667 // TBZ has a smaller branch displacement than CBZ. If the offset is
3668 // out of bounds, a late MI-layer pass rewrites branches.
3669 // 403.gcc is an example that hits this case.
3670 if (LHS.getOpcode() == ISD::AND &&
3671 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3672 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3673 SDValue Test = LHS.getOperand(0);
3674 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003675 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003676 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3677 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003678 }
3679
3680 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3681 } else if (CC == ISD::SETNE) {
3682 // See if we can use a TBZ to fold in an AND as well.
3683 // TBZ has a smaller branch displacement than CBZ. If the offset is
3684 // out of bounds, a late MI-layer pass rewrites branches.
3685 // 403.gcc is an example that hits this case.
3686 if (LHS.getOpcode() == ISD::AND &&
3687 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3688 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3689 SDValue Test = LHS.getOperand(0);
3690 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003691 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003692 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3693 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003694 }
3695
3696 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003697 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3698 // Don't combine AND since emitComparison converts the AND to an ANDS
3699 // (a.k.a. TST) and the test in the test bit and branch instruction
3700 // becomes redundant. This would also increase register pressure.
3701 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3702 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003703 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003704 }
3705 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003706 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3707 LHS.getOpcode() != ISD::AND) {
3708 // Don't combine AND since emitComparison converts the AND to an ANDS
3709 // (a.k.a. TST) and the test in the test bit and branch instruction
3710 // becomes redundant. This would also increase register pressure.
3711 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3712 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003713 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003714 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003715
3716 SDValue CCVal;
3717 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3718 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3719 Cmp);
3720 }
3721
3722 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3723
3724 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3725 // clean. Some of them require two branches to implement.
3726 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3727 AArch64CC::CondCode CC1, CC2;
3728 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003729 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003730 SDValue BR1 =
3731 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3732 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003733 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003734 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3735 Cmp);
3736 }
3737
3738 return BR1;
3739}
3740
3741SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3742 SelectionDAG &DAG) const {
3743 EVT VT = Op.getValueType();
3744 SDLoc DL(Op);
3745
3746 SDValue In1 = Op.getOperand(0);
3747 SDValue In2 = Op.getOperand(1);
3748 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003749
3750 if (SrcVT.bitsLT(VT))
3751 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3752 else if (SrcVT.bitsGT(VT))
3753 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003754
3755 EVT VecVT;
3756 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003757 uint64_t EltMask;
3758 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003759 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3760 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003761 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003762 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003763
3764 if (!VT.isVector()) {
3765 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3766 DAG.getUNDEF(VecVT), In1);
3767 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3768 DAG.getUNDEF(VecVT), In2);
3769 } else {
3770 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3771 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3772 }
3773 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3774 EltVT = MVT::i64;
3775 VecVT = MVT::v2i64;
3776
Eric Christopher572e03a2015-06-19 01:53:21 +00003777 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003778 // immediate moves cannot materialize that in a single instruction for
3779 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003780 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003781
3782 if (!VT.isVector()) {
3783 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3784 DAG.getUNDEF(VecVT), In1);
3785 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3786 DAG.getUNDEF(VecVT), In2);
3787 } else {
3788 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3789 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3790 }
3791 } else {
3792 llvm_unreachable("Invalid type for copysign!");
3793 }
3794
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003795 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003796
3797 // If we couldn't materialize the mask above, then the mask vector will be
3798 // the zero vector, and we need to negate it here.
3799 if (VT == MVT::f64 || VT == MVT::v2f64) {
3800 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3801 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3802 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3803 }
3804
3805 SDValue Sel =
3806 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3807
3808 if (VT == MVT::f32)
3809 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3810 else if (VT == MVT::f64)
3811 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3812 else
3813 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3814}
3815
3816SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003817 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3818 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003819 return SDValue();
3820
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003821 if (!Subtarget->hasNEON())
3822 return SDValue();
3823
Tim Northover3b0846e2014-05-24 12:50:23 +00003824 // While there is no integer popcount instruction, it can
3825 // be more efficiently lowered to the following sequence that uses
3826 // AdvSIMD registers/instructions as long as the copies to/from
3827 // the AdvSIMD registers are cheap.
3828 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3829 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3830 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3831 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3832 SDValue Val = Op.getOperand(0);
3833 SDLoc DL(Op);
3834 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003835
Hao Liue0335d72015-01-30 02:13:53 +00003836 if (VT == MVT::i32)
3837 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3838 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003839
Hao Liue0335d72015-01-30 02:13:53 +00003840 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003841 SDValue UaddLV = DAG.getNode(
3842 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003843 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003844
3845 if (VT == MVT::i64)
3846 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3847 return UaddLV;
3848}
3849
3850SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3851
3852 if (Op.getValueType().isVector())
3853 return LowerVSETCC(Op, DAG);
3854
3855 SDValue LHS = Op.getOperand(0);
3856 SDValue RHS = Op.getOperand(1);
3857 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3858 SDLoc dl(Op);
3859
3860 // We chose ZeroOrOneBooleanContents, so use zero and one.
3861 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003862 SDValue TVal = DAG.getConstant(1, dl, VT);
3863 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003864
3865 // Handle f128 first, since one possible outcome is a normal integer
3866 // comparison which gets picked up by the next if statement.
3867 if (LHS.getValueType() == MVT::f128) {
3868 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3869
3870 // If softenSetCCOperands returned a scalar, use it.
3871 if (!RHS.getNode()) {
3872 assert(LHS.getValueType() == Op.getValueType() &&
3873 "Unexpected setcc expansion!");
3874 return LHS;
3875 }
3876 }
3877
3878 if (LHS.getValueType().isInteger()) {
3879 SDValue CCVal;
3880 SDValue Cmp =
3881 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3882
3883 // Note that we inverted the condition above, so we reverse the order of
3884 // the true and false operands here. This will allow the setcc to be
3885 // matched to a single CSINC instruction.
3886 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3887 }
3888
3889 // Now we know we're dealing with FP values.
3890 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3891
3892 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3893 // and do the comparison.
3894 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3895
3896 AArch64CC::CondCode CC1, CC2;
3897 changeFPCCToAArch64CC(CC, CC1, CC2);
3898 if (CC2 == AArch64CC::AL) {
3899 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003900 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003901
3902 // Note that we inverted the condition above, so we reverse the order of
3903 // the true and false operands here. This will allow the setcc to be
3904 // matched to a single CSINC instruction.
3905 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3906 } else {
3907 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3908 // totally clean. Some of them require two CSELs to implement. As is in
3909 // this case, we emit the first CSEL and then emit a second using the output
3910 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3911
3912 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003913 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003914 SDValue CS1 =
3915 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3916
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003917 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003918 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3919 }
3920}
3921
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003922SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3923 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003924 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003925 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003926 // Handle f128 first, because it will result in a comparison of some RTLIB
3927 // call result against zero.
3928 if (LHS.getValueType() == MVT::f128) {
3929 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3930
3931 // If softenSetCCOperands returned a scalar, we need to compare the result
3932 // against zero to select between true and false values.
3933 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003934 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003935 CC = ISD::SETNE;
3936 }
3937 }
3938
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003939 // Also handle f16, for which we need to do a f32 comparison.
3940 if (LHS.getValueType() == MVT::f16) {
3941 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3942 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3943 }
3944
3945 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003946 if (LHS.getValueType().isInteger()) {
3947 assert((LHS.getValueType() == RHS.getValueType()) &&
3948 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3949
3950 unsigned Opcode = AArch64ISD::CSEL;
3951
3952 // If both the TVal and the FVal are constants, see if we can swap them in
3953 // order to for a CSINV or CSINC out of them.
3954 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3955 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3956
3957 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3958 std::swap(TVal, FVal);
3959 std::swap(CTVal, CFVal);
3960 CC = ISD::getSetCCInverse(CC, true);
3961 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3962 std::swap(TVal, FVal);
3963 std::swap(CTVal, CFVal);
3964 CC = ISD::getSetCCInverse(CC, true);
3965 } else if (TVal.getOpcode() == ISD::XOR) {
3966 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3967 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003968 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003969 std::swap(TVal, FVal);
3970 std::swap(CTVal, CFVal);
3971 CC = ISD::getSetCCInverse(CC, true);
3972 }
3973 } else if (TVal.getOpcode() == ISD::SUB) {
3974 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3975 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003976 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003977 std::swap(TVal, FVal);
3978 std::swap(CTVal, CFVal);
3979 CC = ISD::getSetCCInverse(CC, true);
3980 }
3981 } else if (CTVal && CFVal) {
3982 const int64_t TrueVal = CTVal->getSExtValue();
3983 const int64_t FalseVal = CFVal->getSExtValue();
3984 bool Swap = false;
3985
3986 // If both TVal and FVal are constants, see if FVal is the
3987 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3988 // instead of a CSEL in that case.
3989 if (TrueVal == ~FalseVal) {
3990 Opcode = AArch64ISD::CSINV;
3991 } else if (TrueVal == -FalseVal) {
3992 Opcode = AArch64ISD::CSNEG;
3993 } else if (TVal.getValueType() == MVT::i32) {
3994 // If our operands are only 32-bit wide, make sure we use 32-bit
3995 // arithmetic for the check whether we can use CSINC. This ensures that
3996 // the addition in the check will wrap around properly in case there is
3997 // an overflow (which would not be the case if we do the check with
3998 // 64-bit arithmetic).
3999 const uint32_t TrueVal32 = CTVal->getZExtValue();
4000 const uint32_t FalseVal32 = CFVal->getZExtValue();
4001
4002 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4003 Opcode = AArch64ISD::CSINC;
4004
4005 if (TrueVal32 > FalseVal32) {
4006 Swap = true;
4007 }
4008 }
4009 // 64-bit check whether we can use CSINC.
4010 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4011 Opcode = AArch64ISD::CSINC;
4012
4013 if (TrueVal > FalseVal) {
4014 Swap = true;
4015 }
4016 }
4017
4018 // Swap TVal and FVal if necessary.
4019 if (Swap) {
4020 std::swap(TVal, FVal);
4021 std::swap(CTVal, CFVal);
4022 CC = ISD::getSetCCInverse(CC, true);
4023 }
4024
4025 if (Opcode != AArch64ISD::CSEL) {
4026 // Drop FVal since we can get its value by simply inverting/negating
4027 // TVal.
4028 FVal = TVal;
4029 }
4030 }
4031
4032 SDValue CCVal;
4033 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4034
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004035 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004036 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4037 }
4038
4039 // Now we know we're dealing with FP values.
4040 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4041 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004042 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004043 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4044
4045 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4046 // clean. Some of them require two CSELs to implement.
4047 AArch64CC::CondCode CC1, CC2;
4048 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004049 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004050 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4051
4052 // If we need a second CSEL, emit it, using the output of the first as the
4053 // RHS. We're effectively OR'ing the two CC's together.
4054 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004055 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004056 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4057 }
4058
4059 // Otherwise, return the output of the first CSEL.
4060 return CS1;
4061}
4062
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004063SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4064 SelectionDAG &DAG) const {
4065 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4066 SDValue LHS = Op.getOperand(0);
4067 SDValue RHS = Op.getOperand(1);
4068 SDValue TVal = Op.getOperand(2);
4069 SDValue FVal = Op.getOperand(3);
4070 SDLoc DL(Op);
4071 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4072}
4073
4074SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4075 SelectionDAG &DAG) const {
4076 SDValue CCVal = Op->getOperand(0);
4077 SDValue TVal = Op->getOperand(1);
4078 SDValue FVal = Op->getOperand(2);
4079 SDLoc DL(Op);
4080
4081 unsigned Opc = CCVal.getOpcode();
4082 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4083 // instruction.
4084 if (CCVal.getResNo() == 1 &&
4085 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4086 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4087 // Only lower legal XALUO ops.
4088 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4089 return SDValue();
4090
4091 AArch64CC::CondCode OFCC;
4092 SDValue Value, Overflow;
4093 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004094 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004095
4096 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4097 CCVal, Overflow);
4098 }
4099
4100 // Lower it the same way as we would lower a SELECT_CC node.
4101 ISD::CondCode CC;
4102 SDValue LHS, RHS;
4103 if (CCVal.getOpcode() == ISD::SETCC) {
4104 LHS = CCVal.getOperand(0);
4105 RHS = CCVal.getOperand(1);
4106 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4107 } else {
4108 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004109 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004110 CC = ISD::SETNE;
4111 }
4112 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4113}
4114
Tim Northover3b0846e2014-05-24 12:50:23 +00004115SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4116 SelectionDAG &DAG) const {
4117 // Jump table entries as PC relative offsets. No additional tweaking
4118 // is necessary here. Just get the address of the jump table.
4119 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004120 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004121 SDLoc DL(Op);
4122
4123 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4124 !Subtarget->isTargetMachO()) {
4125 const unsigned char MO_NC = AArch64II::MO_NC;
4126 return DAG.getNode(
4127 AArch64ISD::WrapperLarge, DL, PtrVT,
4128 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4129 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4130 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4131 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4132 AArch64II::MO_G0 | MO_NC));
4133 }
4134
4135 SDValue Hi =
4136 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4137 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4138 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4139 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4140 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4141}
4142
4143SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4144 SelectionDAG &DAG) const {
4145 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004146 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004147 SDLoc DL(Op);
4148
4149 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4150 // Use the GOT for the large code model on iOS.
4151 if (Subtarget->isTargetMachO()) {
4152 SDValue GotAddr = DAG.getTargetConstantPool(
4153 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4154 AArch64II::MO_GOT);
4155 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4156 }
4157
4158 const unsigned char MO_NC = AArch64II::MO_NC;
4159 return DAG.getNode(
4160 AArch64ISD::WrapperLarge, DL, PtrVT,
4161 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4162 CP->getOffset(), AArch64II::MO_G3),
4163 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4164 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4165 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4166 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4167 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4168 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4169 } else {
4170 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4171 // ELF, the only valid one on Darwin.
4172 SDValue Hi =
4173 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4174 CP->getOffset(), AArch64II::MO_PAGE);
4175 SDValue Lo = DAG.getTargetConstantPool(
4176 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4177 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4178
4179 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4180 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4181 }
4182}
4183
4184SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4185 SelectionDAG &DAG) const {
4186 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004187 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004188 SDLoc DL(Op);
4189 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4190 !Subtarget->isTargetMachO()) {
4191 const unsigned char MO_NC = AArch64II::MO_NC;
4192 return DAG.getNode(
4193 AArch64ISD::WrapperLarge, DL, PtrVT,
4194 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4195 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4196 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4197 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4198 } else {
4199 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4200 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4201 AArch64II::MO_NC);
4202 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4203 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4204 }
4205}
4206
4207SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4208 SelectionDAG &DAG) const {
4209 AArch64FunctionInfo *FuncInfo =
4210 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4211
4212 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004213 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4214 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004215 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4216 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004217 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004218}
4219
4220SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4221 SelectionDAG &DAG) const {
4222 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4223 // Standard, section B.3.
4224 MachineFunction &MF = DAG.getMachineFunction();
4225 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004226 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004227 SDLoc DL(Op);
4228
4229 SDValue Chain = Op.getOperand(0);
4230 SDValue VAList = Op.getOperand(1);
4231 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4232 SmallVector<SDValue, 4> MemOps;
4233
4234 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004235 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004236 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004237 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004238
4239 // void *__gr_top at offset 8
4240 int GPRSize = FuncInfo->getVarArgsGPRSize();
4241 if (GPRSize > 0) {
4242 SDValue GRTop, GRTopAddr;
4243
Mehdi Amini44ede332015-07-09 02:09:04 +00004244 GRTopAddr =
4245 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004246
Mehdi Amini44ede332015-07-09 02:09:04 +00004247 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4248 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4249 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004250
4251 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004252 MachinePointerInfo(SV, 8),
4253 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004254 }
4255
4256 // void *__vr_top at offset 16
4257 int FPRSize = FuncInfo->getVarArgsFPRSize();
4258 if (FPRSize > 0) {
4259 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004260 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4261 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004262
Mehdi Amini44ede332015-07-09 02:09:04 +00004263 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4264 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4265 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004266
4267 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004268 MachinePointerInfo(SV, 16),
4269 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004270 }
4271
4272 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004273 SDValue GROffsAddr =
4274 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004275 MemOps.push_back(DAG.getStore(
4276 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4277 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004278
4279 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004280 SDValue VROffsAddr =
4281 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004282 MemOps.push_back(DAG.getStore(
4283 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4284 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004285
4286 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4287}
4288
4289SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4290 SelectionDAG &DAG) const {
4291 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4292 : LowerAAPCS_VASTART(Op, DAG);
4293}
4294
4295SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4296 SelectionDAG &DAG) const {
4297 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4298 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004299 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004300 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4301 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4302 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4303
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004304 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4305 Op.getOperand(2),
4306 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004307 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004308 MachinePointerInfo(SrcSV));
4309}
4310
4311SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4312 assert(Subtarget->isTargetDarwin() &&
4313 "automatic va_arg instruction only works on Darwin");
4314
4315 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4316 EVT VT = Op.getValueType();
4317 SDLoc DL(Op);
4318 SDValue Chain = Op.getOperand(0);
4319 SDValue Addr = Op.getOperand(1);
4320 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004321 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004322
Justin Lebar9c375812016-07-15 18:27:10 +00004323 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004324 Chain = VAList.getValue(1);
4325
4326 if (Align > 8) {
4327 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004328 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4329 DAG.getConstant(Align - 1, DL, PtrVT));
4330 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4331 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004332 }
4333
4334 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004335 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004336
4337 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4338 // up to 64 bits. At the very least, we have to increase the striding of the
4339 // vaargs list to match this, and for FP values we need to introduce
4340 // FP_ROUND nodes as well.
4341 if (VT.isInteger() && !VT.isVector())
4342 ArgSize = 8;
4343 bool NeedFPTrunc = false;
4344 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4345 ArgSize = 8;
4346 NeedFPTrunc = true;
4347 }
4348
4349 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004350 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4351 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004352 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004353 SDValue APStore =
4354 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004355
4356 // Load the actual argument out of the pointer VAList
4357 if (NeedFPTrunc) {
4358 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004359 SDValue WideFP =
4360 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004361 // Round the value down to an f32.
4362 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004363 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004364 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4365 // Merge the rounded value with the chain output of the load.
4366 return DAG.getMergeValues(Ops, DL);
4367 }
4368
Justin Lebar9c375812016-07-15 18:27:10 +00004369 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004370}
4371
4372SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4373 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004374 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4375 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004376
4377 EVT VT = Op.getValueType();
4378 SDLoc DL(Op);
4379 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4380 SDValue FrameAddr =
4381 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4382 while (Depth--)
4383 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004384 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004385 return FrameAddr;
4386}
4387
4388// FIXME? Maybe this could be a TableGen attribute on some registers and
4389// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004390unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4391 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004392 unsigned Reg = StringSwitch<unsigned>(RegName)
4393 .Case("sp", AArch64::SP)
4394 .Default(0);
4395 if (Reg)
4396 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004397 report_fatal_error(Twine("Invalid register name \""
4398 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004399}
4400
4401SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4402 SelectionDAG &DAG) const {
4403 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004404 MachineFrameInfo &MFI = MF.getFrameInfo();
4405 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004406
4407 EVT VT = Op.getValueType();
4408 SDLoc DL(Op);
4409 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4410 if (Depth) {
4411 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004412 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004413 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4414 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004415 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004416 }
4417
4418 // Return LR, which contains the return address. Mark it an implicit live-in.
4419 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4420 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4421}
4422
4423/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4424/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4425SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4426 SelectionDAG &DAG) const {
4427 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4428 EVT VT = Op.getValueType();
4429 unsigned VTBits = VT.getSizeInBits();
4430 SDLoc dl(Op);
4431 SDValue ShOpLo = Op.getOperand(0);
4432 SDValue ShOpHi = Op.getOperand(1);
4433 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004434 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4435
4436 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4437
4438 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004439 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004440 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4441
4442 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4443 // is "undef". We wanted 0, so CSEL it directly.
4444 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4445 ISD::SETEQ, dl, DAG);
4446 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4447 HiBitsForLo =
4448 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4449 HiBitsForLo, CCVal, Cmp);
4450
Tim Northover3b0846e2014-05-24 12:50:23 +00004451 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004452 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004453
Tim Northoverf3be9d52015-12-02 00:33:54 +00004454 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4455 SDValue LoForNormalShift =
4456 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004457
Tim Northoverf3be9d52015-12-02 00:33:54 +00004458 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4459 dl, DAG);
4460 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4461 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4462 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4463 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004464
4465 // AArch64 shifts larger than the register width are wrapped rather than
4466 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004467 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4468 SDValue HiForBigShift =
4469 Opc == ISD::SRA
4470 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4471 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4472 : DAG.getConstant(0, dl, VT);
4473 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4474 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004475
4476 SDValue Ops[2] = { Lo, Hi };
4477 return DAG.getMergeValues(Ops, dl);
4478}
4479
Tim Northoverf3be9d52015-12-02 00:33:54 +00004480
Tim Northover3b0846e2014-05-24 12:50:23 +00004481/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4482/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4483SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004484 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004485 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4486 EVT VT = Op.getValueType();
4487 unsigned VTBits = VT.getSizeInBits();
4488 SDLoc dl(Op);
4489 SDValue ShOpLo = Op.getOperand(0);
4490 SDValue ShOpHi = Op.getOperand(1);
4491 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004492
4493 assert(Op.getOpcode() == ISD::SHL_PARTS);
4494 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004495 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004496 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4497
4498 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4499 // is "undef". We wanted 0, so CSEL it directly.
4500 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4501 ISD::SETEQ, dl, DAG);
4502 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4503 LoBitsForHi =
4504 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4505 LoBitsForHi, CCVal, Cmp);
4506
Tim Northover3b0846e2014-05-24 12:50:23 +00004507 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004508 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004509 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4510 SDValue HiForNormalShift =
4511 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004512
Tim Northoverf3be9d52015-12-02 00:33:54 +00004513 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004514
Tim Northoverf3be9d52015-12-02 00:33:54 +00004515 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4516 dl, DAG);
4517 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4518 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4519 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004520
4521 // AArch64 shifts of larger than register sizes are wrapped rather than
4522 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004523 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4524 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4525 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4526 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004527
4528 SDValue Ops[2] = { Lo, Hi };
4529 return DAG.getMergeValues(Ops, dl);
4530}
4531
4532bool AArch64TargetLowering::isOffsetFoldingLegal(
4533 const GlobalAddressSDNode *GA) const {
4534 // The AArch64 target doesn't support folding offsets into global addresses.
4535 return false;
4536}
4537
4538bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4539 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4540 // FIXME: We should be able to handle f128 as well with a clever lowering.
4541 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4542 return true;
4543
4544 if (VT == MVT::f64)
4545 return AArch64_AM::getFP64Imm(Imm) != -1;
4546 else if (VT == MVT::f32)
4547 return AArch64_AM::getFP32Imm(Imm) != -1;
4548 return false;
4549}
4550
4551//===----------------------------------------------------------------------===//
4552// AArch64 Optimization Hooks
4553//===----------------------------------------------------------------------===//
4554
Evandro Menezesbcb95cd2016-05-04 20:18:27 +00004555/// getEstimate - Return the appropriate estimate DAG for either the reciprocal
4556/// or the reciprocal square root.
4557static SDValue getEstimate(const AArch64Subtarget &ST,
4558 const AArch64TargetLowering::DAGCombinerInfo &DCI, unsigned Opcode,
4559 const SDValue &Operand, unsigned &ExtraSteps) {
4560 if (!ST.hasNEON())
4561 return SDValue();
4562
4563 EVT VT = Operand.getValueType();
Evandro Menezes238fa762016-07-19 22:31:11 +00004564 if (VT != MVT::f64 && VT != MVT::v1f64 && VT != MVT::v2f64 &&
4565 VT != MVT::f32 && VT != MVT::v1f32 &&
4566 VT != MVT::v2f32 && VT != MVT::v4f32 &&
4567 (!ST.hasFullFP16() ||
4568 (VT != MVT::f16 && VT != MVT::v4f16 && VT != MVT::v8f16)))
4569 return SDValue();
Evandro Menezesbcb95cd2016-05-04 20:18:27 +00004570
4571 std::string RecipOp;
4572 RecipOp = Opcode == (AArch64ISD::FRECPE) ? "div": "sqrt";
4573 RecipOp = ((VT.isVector()) ? "vec-": "") + RecipOp;
4574 RecipOp += (VT.getScalarType() == MVT::f64) ? "d": "f";
4575
4576 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
4577 if (!Recips.isEnabled(RecipOp))
4578 return SDValue();
4579
4580 ExtraSteps = Recips.getRefinementSteps(RecipOp);
4581 return DCI.DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4582}
4583
4584SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4585 DAGCombinerInfo &DCI, unsigned &ExtraSteps) const {
4586 return getEstimate(*Subtarget, DCI, AArch64ISD::FRECPE, Operand, ExtraSteps);
4587}
4588
4589SDValue AArch64TargetLowering::getRsqrtEstimate(SDValue Operand,
4590 DAGCombinerInfo &DCI, unsigned &ExtraSteps, bool &UseOneConst) const {
4591 UseOneConst = true;
4592 return getEstimate(*Subtarget, DCI, AArch64ISD::FRSQRTE, Operand, ExtraSteps);
4593}
4594
Tim Northover3b0846e2014-05-24 12:50:23 +00004595//===----------------------------------------------------------------------===//
4596// AArch64 Inline Assembly Support
4597//===----------------------------------------------------------------------===//
4598
4599// Table of Constraints
4600// TODO: This is the current set of constraints supported by ARM for the
4601// compiler, not all of them may make sense, e.g. S may be difficult to support.
4602//
4603// r - A general register
4604// w - An FP/SIMD register of some size in the range v0-v31
4605// x - An FP/SIMD register of some size in the range v0-v15
4606// I - Constant that can be used with an ADD instruction
4607// J - Constant that can be used with a SUB instruction
4608// K - Constant that can be used with a 32-bit logical instruction
4609// L - Constant that can be used with a 64-bit logical instruction
4610// M - Constant that can be used as a 32-bit MOV immediate
4611// N - Constant that can be used as a 64-bit MOV immediate
4612// Q - A memory reference with base register and no offset
4613// S - A symbolic address
4614// Y - Floating point constant zero
4615// Z - Integer constant zero
4616//
4617// Note that general register operands will be output using their 64-bit x
4618// register name, whatever the size of the variable, unless the asm operand
4619// is prefixed by the %w modifier. Floating-point and SIMD register operands
4620// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4621// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00004622const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4623 // At this point, we have to lower this constraint to something else, so we
4624 // lower it to an "r" or "w". However, by doing this we will force the result
4625 // to be in register, while the X constraint is much more permissive.
4626 //
4627 // Although we are correct (we are free to emit anything, without
4628 // constraints), we might break use cases that would expect us to be more
4629 // efficient and emit something else.
4630 if (!Subtarget->hasFPARMv8())
4631 return "r";
4632
4633 if (ConstraintVT.isFloatingPoint())
4634 return "w";
4635
4636 if (ConstraintVT.isVector() &&
4637 (ConstraintVT.getSizeInBits() == 64 ||
4638 ConstraintVT.getSizeInBits() == 128))
4639 return "w";
4640
4641 return "r";
4642}
Tim Northover3b0846e2014-05-24 12:50:23 +00004643
4644/// getConstraintType - Given a constraint letter, return the type of
4645/// constraint it is for this target.
4646AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004647AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004648 if (Constraint.size() == 1) {
4649 switch (Constraint[0]) {
4650 default:
4651 break;
4652 case 'z':
4653 return C_Other;
4654 case 'x':
4655 case 'w':
4656 return C_RegisterClass;
4657 // An address with a single base register. Due to the way we
4658 // currently handle addresses it is the same as 'r'.
4659 case 'Q':
4660 return C_Memory;
4661 }
4662 }
4663 return TargetLowering::getConstraintType(Constraint);
4664}
4665
4666/// Examine constraint type and operand type and determine a weight value.
4667/// This object must already have been set up with the operand type
4668/// and the current alternative constraint selected.
4669TargetLowering::ConstraintWeight
4670AArch64TargetLowering::getSingleConstraintMatchWeight(
4671 AsmOperandInfo &info, const char *constraint) const {
4672 ConstraintWeight weight = CW_Invalid;
4673 Value *CallOperandVal = info.CallOperandVal;
4674 // If we don't have a value, we can't do a match,
4675 // but allow it at the lowest weight.
4676 if (!CallOperandVal)
4677 return CW_Default;
4678 Type *type = CallOperandVal->getType();
4679 // Look at the constraint type.
4680 switch (*constraint) {
4681 default:
4682 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4683 break;
4684 case 'x':
4685 case 'w':
4686 if (type->isFloatingPointTy() || type->isVectorTy())
4687 weight = CW_Register;
4688 break;
4689 case 'z':
4690 weight = CW_Constant;
4691 break;
4692 }
4693 return weight;
4694}
4695
4696std::pair<unsigned, const TargetRegisterClass *>
4697AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004698 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004699 if (Constraint.size() == 1) {
4700 switch (Constraint[0]) {
4701 case 'r':
4702 if (VT.getSizeInBits() == 64)
4703 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4704 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4705 case 'w':
Akira Hatanakab8d28732016-07-21 21:39:05 +00004706 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00004707 return std::make_pair(0U, &AArch64::FPR32RegClass);
4708 if (VT.getSizeInBits() == 64)
4709 return std::make_pair(0U, &AArch64::FPR64RegClass);
4710 if (VT.getSizeInBits() == 128)
4711 return std::make_pair(0U, &AArch64::FPR128RegClass);
4712 break;
4713 // The instructions that this constraint is designed for can
4714 // only take 128-bit registers so just use that regclass.
4715 case 'x':
4716 if (VT.getSizeInBits() == 128)
4717 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4718 break;
4719 }
4720 }
4721 if (StringRef("{cc}").equals_lower(Constraint))
4722 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4723
4724 // Use the default implementation in TargetLowering to convert the register
4725 // constraint into a member of a register class.
4726 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004727 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004728
4729 // Not found as a standard register?
4730 if (!Res.second) {
4731 unsigned Size = Constraint.size();
4732 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4733 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004734 int RegNo;
4735 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4736 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00004737 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00004738 // By default we'll emit v0-v31 for this unless there's a modifier where
4739 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00004740 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4741 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4742 Res.second = &AArch64::FPR64RegClass;
4743 } else {
4744 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4745 Res.second = &AArch64::FPR128RegClass;
4746 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004747 }
4748 }
4749 }
4750
4751 return Res;
4752}
4753
4754/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4755/// vector. If it is invalid, don't add anything to Ops.
4756void AArch64TargetLowering::LowerAsmOperandForConstraint(
4757 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4758 SelectionDAG &DAG) const {
4759 SDValue Result;
4760
4761 // Currently only support length 1 constraints.
4762 if (Constraint.length() != 1)
4763 return;
4764
4765 char ConstraintLetter = Constraint[0];
4766 switch (ConstraintLetter) {
4767 default:
4768 break;
4769
4770 // This set of constraints deal with valid constants for various instructions.
4771 // Validate and return a target constant for them if we can.
4772 case 'z': {
4773 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004774 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004775 return;
4776
4777 if (Op.getValueType() == MVT::i64)
4778 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4779 else
4780 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4781 break;
4782 }
4783
4784 case 'I':
4785 case 'J':
4786 case 'K':
4787 case 'L':
4788 case 'M':
4789 case 'N':
4790 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4791 if (!C)
4792 return;
4793
4794 // Grab the value and do some validation.
4795 uint64_t CVal = C->getZExtValue();
4796 switch (ConstraintLetter) {
4797 // The I constraint applies only to simple ADD or SUB immediate operands:
4798 // i.e. 0 to 4095 with optional shift by 12
4799 // The J constraint applies only to ADD or SUB immediates that would be
4800 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4801 // instruction [or vice versa], in other words -1 to -4095 with optional
4802 // left shift by 12.
4803 case 'I':
4804 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4805 break;
4806 return;
4807 case 'J': {
4808 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004809 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4810 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004811 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004812 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004813 return;
4814 }
4815 // The K and L constraints apply *only* to logical immediates, including
4816 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4817 // been removed and MOV should be used). So these constraints have to
4818 // distinguish between bit patterns that are valid 32-bit or 64-bit
4819 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4820 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4821 // versa.
4822 case 'K':
4823 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4824 break;
4825 return;
4826 case 'L':
4827 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4828 break;
4829 return;
4830 // The M and N constraints are a superset of K and L respectively, for use
4831 // with the MOV (immediate) alias. As well as the logical immediates they
4832 // also match 32 or 64-bit immediates that can be loaded either using a
4833 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4834 // (M) or 64-bit 0x1234000000000000 (N) etc.
4835 // As a note some of this code is liberally stolen from the asm parser.
4836 case 'M': {
4837 if (!isUInt<32>(CVal))
4838 return;
4839 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4840 break;
4841 if ((CVal & 0xFFFF) == CVal)
4842 break;
4843 if ((CVal & 0xFFFF0000ULL) == CVal)
4844 break;
4845 uint64_t NCVal = ~(uint32_t)CVal;
4846 if ((NCVal & 0xFFFFULL) == NCVal)
4847 break;
4848 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4849 break;
4850 return;
4851 }
4852 case 'N': {
4853 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4854 break;
4855 if ((CVal & 0xFFFFULL) == CVal)
4856 break;
4857 if ((CVal & 0xFFFF0000ULL) == CVal)
4858 break;
4859 if ((CVal & 0xFFFF00000000ULL) == CVal)
4860 break;
4861 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4862 break;
4863 uint64_t NCVal = ~CVal;
4864 if ((NCVal & 0xFFFFULL) == NCVal)
4865 break;
4866 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4867 break;
4868 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4869 break;
4870 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4871 break;
4872 return;
4873 }
4874 default:
4875 return;
4876 }
4877
4878 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004879 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004880 break;
4881 }
4882
4883 if (Result.getNode()) {
4884 Ops.push_back(Result);
4885 return;
4886 }
4887
4888 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4889}
4890
4891//===----------------------------------------------------------------------===//
4892// AArch64 Advanced SIMD Support
4893//===----------------------------------------------------------------------===//
4894
4895/// WidenVector - Given a value in the V64 register class, produce the
4896/// equivalent value in the V128 register class.
4897static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4898 EVT VT = V64Reg.getValueType();
4899 unsigned NarrowSize = VT.getVectorNumElements();
4900 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4901 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4902 SDLoc DL(V64Reg);
4903
4904 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004905 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004906}
4907
4908/// getExtFactor - Determine the adjustment factor for the position when
4909/// generating an "extract from vector registers" instruction.
4910static unsigned getExtFactor(SDValue &V) {
4911 EVT EltType = V.getValueType().getVectorElementType();
4912 return EltType.getSizeInBits() / 8;
4913}
4914
4915/// NarrowVector - Given a value in the V128 register class, produce the
4916/// equivalent value in the V64 register class.
4917static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4918 EVT VT = V128Reg.getValueType();
4919 unsigned WideSize = VT.getVectorNumElements();
4920 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4921 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4922 SDLoc DL(V128Reg);
4923
4924 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4925}
4926
4927// Gather data to see if the operation can be modelled as a
4928// shuffle in combination with VEXTs.
4929SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4930 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004931 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004932 SDLoc dl(Op);
4933 EVT VT = Op.getValueType();
4934 unsigned NumElts = VT.getVectorNumElements();
4935
Tim Northover7324e842014-07-24 15:39:55 +00004936 struct ShuffleSourceInfo {
4937 SDValue Vec;
4938 unsigned MinElt;
4939 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004940
Tim Northover7324e842014-07-24 15:39:55 +00004941 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4942 // be compatible with the shuffle we intend to construct. As a result
4943 // ShuffleVec will be some sliding window into the original Vec.
4944 SDValue ShuffleVec;
4945
4946 // Code should guarantee that element i in Vec starts at element "WindowBase
4947 // + i * WindowScale in ShuffleVec".
4948 int WindowBase;
4949 int WindowScale;
4950
4951 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4952 ShuffleSourceInfo(SDValue Vec)
4953 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4954 WindowScale(1) {}
4955 };
4956
4957 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4958 // node.
4959 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004960 for (unsigned i = 0; i < NumElts; ++i) {
4961 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00004962 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00004963 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004964 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4965 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004966 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004967 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00004968 return SDValue();
4969 }
4970
Tim Northover7324e842014-07-24 15:39:55 +00004971 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004972 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004973 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4974 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004975 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004976
Tim Northover7324e842014-07-24 15:39:55 +00004977 // Update the minimum and maximum lane number seen.
4978 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4979 Source->MinElt = std::min(Source->MinElt, EltNo);
4980 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004981 }
4982
4983 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004984 // are involved.
4985 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004986 return SDValue();
4987
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004988 // Find out the smallest element size among result and two sources, and use
4989 // it as element size to build the shuffle_vector.
4990 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004991 for (auto &Source : Sources) {
4992 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004993 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4994 SmallestEltTy = SrcEltTy;
4995 }
4996 }
4997 unsigned ResMultiplier =
4998 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004999 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5000 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005001
Tim Northover7324e842014-07-24 15:39:55 +00005002 // If the source vector is too wide or too narrow, we may nevertheless be able
5003 // to construct a compatible shuffle either by concatenating it with UNDEF or
5004 // extracting a suitable range of elements.
5005 for (auto &Src : Sources) {
5006 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005007
Tim Northover7324e842014-07-24 15:39:55 +00005008 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005009 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005010
5011 // This stage of the search produces a source with the same element type as
5012 // the original, but with a total width matching the BUILD_VECTOR output.
5013 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005014 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5015 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005016
5017 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5018 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005019 // We can pad out the smaller vector for free, so if it's part of a
5020 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005021 Src.ShuffleVec =
5022 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5023 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005024 continue;
5025 }
5026
Tim Northover7324e842014-07-24 15:39:55 +00005027 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005028
James Molloyf497d552014-10-17 17:06:31 +00005029 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005030 // Span too large for a VEXT to cope
5031 return SDValue();
5032 }
5033
James Molloyf497d552014-10-17 17:06:31 +00005034 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005035 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005036 Src.ShuffleVec =
5037 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005038 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005039 Src.WindowBase = -NumSrcElts;
5040 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005041 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005042 Src.ShuffleVec =
5043 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005044 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005045 } else {
5046 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005047 SDValue VEXTSrc1 =
5048 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005049 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005050 SDValue VEXTSrc2 =
5051 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005052 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005053 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5054
5055 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005056 VEXTSrc2,
5057 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005058 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005059 }
5060 }
5061
Tim Northover7324e842014-07-24 15:39:55 +00005062 // Another possible incompatibility occurs from the vector element types. We
5063 // can fix this by bitcasting the source vectors to the same type we intend
5064 // for the shuffle.
5065 for (auto &Src : Sources) {
5066 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5067 if (SrcEltTy == SmallestEltTy)
5068 continue;
5069 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5070 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5071 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5072 Src.WindowBase *= Src.WindowScale;
5073 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005074
Tim Northover7324e842014-07-24 15:39:55 +00005075 // Final sanity check before we try to actually produce a shuffle.
5076 DEBUG(
5077 for (auto Src : Sources)
5078 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5079 );
5080
5081 // The stars all align, our next step is to produce the mask for the shuffle.
5082 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5083 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005084 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005085 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005086 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005087 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005088
Tim Northover7324e842014-07-24 15:39:55 +00005089 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5090 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5091
5092 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5093 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5094 // segment.
5095 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5096 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5097 VT.getVectorElementType().getSizeInBits());
5098 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5099
5100 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5101 // starting at the appropriate offset.
5102 int *LaneMask = &Mask[i * ResMultiplier];
5103
5104 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5105 ExtractBase += NumElts * (Src - Sources.begin());
5106 for (int j = 0; j < LanesDefined; ++j)
5107 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005108 }
5109
5110 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005111 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5112 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005113
Tim Northover7324e842014-07-24 15:39:55 +00005114 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5115 for (unsigned i = 0; i < Sources.size(); ++i)
5116 ShuffleOps[i] = Sources[i].ShuffleVec;
5117
5118 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005119 ShuffleOps[1], Mask);
Tim Northover7324e842014-07-24 15:39:55 +00005120 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005121}
5122
5123// check if an EXT instruction can handle the shuffle mask when the
5124// vector sources of the shuffle are the same.
5125static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5126 unsigned NumElts = VT.getVectorNumElements();
5127
5128 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5129 if (M[0] < 0)
5130 return false;
5131
5132 Imm = M[0];
5133
5134 // If this is a VEXT shuffle, the immediate value is the index of the first
5135 // element. The other shuffle indices must be the successive elements after
5136 // the first one.
5137 unsigned ExpectedElt = Imm;
5138 for (unsigned i = 1; i < NumElts; ++i) {
5139 // Increment the expected index. If it wraps around, just follow it
5140 // back to index zero and keep going.
5141 ++ExpectedElt;
5142 if (ExpectedElt == NumElts)
5143 ExpectedElt = 0;
5144
5145 if (M[i] < 0)
5146 continue; // ignore UNDEF indices
5147 if (ExpectedElt != static_cast<unsigned>(M[i]))
5148 return false;
5149 }
5150
5151 return true;
5152}
5153
5154// check if an EXT instruction can handle the shuffle mask when the
5155// vector sources of the shuffle are different.
5156static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5157 unsigned &Imm) {
5158 // Look for the first non-undef element.
5159 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5160 [](int Elt) {return Elt >= 0;});
5161
5162 // Benefit form APInt to handle overflow when calculating expected element.
5163 unsigned NumElts = VT.getVectorNumElements();
5164 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5165 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5166 // The following shuffle indices must be the successive elements after the
5167 // first real element.
5168 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5169 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5170 if (FirstWrongElt != M.end())
5171 return false;
5172
5173 // The index of an EXT is the first element if it is not UNDEF.
5174 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005175 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005176 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5177 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5178 // ExpectedElt is the last mask index plus 1.
5179 Imm = ExpectedElt.getZExtValue();
5180
5181 // There are two difference cases requiring to reverse input vectors.
5182 // For example, for vector <4 x i32> we have the following cases,
5183 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5184 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5185 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5186 // to reverse two input vectors.
5187 if (Imm < NumElts)
5188 ReverseEXT = true;
5189 else
5190 Imm -= NumElts;
5191
5192 return true;
5193}
5194
5195/// isREVMask - Check if a vector shuffle corresponds to a REV
5196/// instruction with the specified blocksize. (The order of the elements
5197/// within each block of the vector is reversed.)
5198static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5199 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5200 "Only possible block sizes for REV are: 16, 32, 64");
5201
5202 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5203 if (EltSz == 64)
5204 return false;
5205
5206 unsigned NumElts = VT.getVectorNumElements();
5207 unsigned BlockElts = M[0] + 1;
5208 // If the first shuffle index is UNDEF, be optimistic.
5209 if (M[0] < 0)
5210 BlockElts = BlockSize / EltSz;
5211
5212 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5213 return false;
5214
5215 for (unsigned i = 0; i < NumElts; ++i) {
5216 if (M[i] < 0)
5217 continue; // ignore UNDEF indices
5218 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5219 return false;
5220 }
5221
5222 return true;
5223}
5224
5225static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5226 unsigned NumElts = VT.getVectorNumElements();
5227 WhichResult = (M[0] == 0 ? 0 : 1);
5228 unsigned Idx = WhichResult * NumElts / 2;
5229 for (unsigned i = 0; i != NumElts; i += 2) {
5230 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5231 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5232 return false;
5233 Idx += 1;
5234 }
5235
5236 return true;
5237}
5238
5239static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5240 unsigned NumElts = VT.getVectorNumElements();
5241 WhichResult = (M[0] == 0 ? 0 : 1);
5242 for (unsigned i = 0; i != NumElts; ++i) {
5243 if (M[i] < 0)
5244 continue; // ignore UNDEF indices
5245 if ((unsigned)M[i] != 2 * i + WhichResult)
5246 return false;
5247 }
5248
5249 return true;
5250}
5251
5252static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5253 unsigned NumElts = VT.getVectorNumElements();
5254 WhichResult = (M[0] == 0 ? 0 : 1);
5255 for (unsigned i = 0; i < NumElts; i += 2) {
5256 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5257 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5258 return false;
5259 }
5260 return true;
5261}
5262
5263/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5264/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5265/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5266static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5267 unsigned NumElts = VT.getVectorNumElements();
5268 WhichResult = (M[0] == 0 ? 0 : 1);
5269 unsigned Idx = WhichResult * NumElts / 2;
5270 for (unsigned i = 0; i != NumElts; i += 2) {
5271 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5272 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5273 return false;
5274 Idx += 1;
5275 }
5276
5277 return true;
5278}
5279
5280/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5281/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5282/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5283static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5284 unsigned Half = VT.getVectorNumElements() / 2;
5285 WhichResult = (M[0] == 0 ? 0 : 1);
5286 for (unsigned j = 0; j != 2; ++j) {
5287 unsigned Idx = WhichResult;
5288 for (unsigned i = 0; i != Half; ++i) {
5289 int MIdx = M[i + j * Half];
5290 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5291 return false;
5292 Idx += 2;
5293 }
5294 }
5295
5296 return true;
5297}
5298
5299/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5300/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5301/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5302static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5303 unsigned NumElts = VT.getVectorNumElements();
5304 WhichResult = (M[0] == 0 ? 0 : 1);
5305 for (unsigned i = 0; i < NumElts; i += 2) {
5306 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5307 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5308 return false;
5309 }
5310 return true;
5311}
5312
5313static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5314 bool &DstIsLeft, int &Anomaly) {
5315 if (M.size() != static_cast<size_t>(NumInputElements))
5316 return false;
5317
5318 int NumLHSMatch = 0, NumRHSMatch = 0;
5319 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5320
5321 for (int i = 0; i < NumInputElements; ++i) {
5322 if (M[i] == -1) {
5323 ++NumLHSMatch;
5324 ++NumRHSMatch;
5325 continue;
5326 }
5327
5328 if (M[i] == i)
5329 ++NumLHSMatch;
5330 else
5331 LastLHSMismatch = i;
5332
5333 if (M[i] == i + NumInputElements)
5334 ++NumRHSMatch;
5335 else
5336 LastRHSMismatch = i;
5337 }
5338
5339 if (NumLHSMatch == NumInputElements - 1) {
5340 DstIsLeft = true;
5341 Anomaly = LastLHSMismatch;
5342 return true;
5343 } else if (NumRHSMatch == NumInputElements - 1) {
5344 DstIsLeft = false;
5345 Anomaly = LastRHSMismatch;
5346 return true;
5347 }
5348
5349 return false;
5350}
5351
5352static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5353 if (VT.getSizeInBits() != 128)
5354 return false;
5355
5356 unsigned NumElts = VT.getVectorNumElements();
5357
5358 for (int I = 0, E = NumElts / 2; I != E; I++) {
5359 if (Mask[I] != I)
5360 return false;
5361 }
5362
5363 int Offset = NumElts / 2;
5364 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5365 if (Mask[I] != I + SplitLHS * Offset)
5366 return false;
5367 }
5368
5369 return true;
5370}
5371
5372static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5373 SDLoc DL(Op);
5374 EVT VT = Op.getValueType();
5375 SDValue V0 = Op.getOperand(0);
5376 SDValue V1 = Op.getOperand(1);
5377 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5378
5379 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5380 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5381 return SDValue();
5382
5383 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5384
5385 if (!isConcatMask(Mask, VT, SplitV0))
5386 return SDValue();
5387
5388 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5389 VT.getVectorNumElements() / 2);
5390 if (SplitV0) {
5391 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005392 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005393 }
5394 if (V1.getValueType().getSizeInBits() == 128) {
5395 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005396 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005397 }
5398 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5399}
5400
5401/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5402/// the specified operations to build the shuffle.
5403static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5404 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005405 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005406 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5407 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5408 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5409
5410 enum {
5411 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5412 OP_VREV,
5413 OP_VDUP0,
5414 OP_VDUP1,
5415 OP_VDUP2,
5416 OP_VDUP3,
5417 OP_VEXT1,
5418 OP_VEXT2,
5419 OP_VEXT3,
5420 OP_VUZPL, // VUZP, left result
5421 OP_VUZPR, // VUZP, right result
5422 OP_VZIPL, // VZIP, left result
5423 OP_VZIPR, // VZIP, right result
5424 OP_VTRNL, // VTRN, left result
5425 OP_VTRNR // VTRN, right result
5426 };
5427
5428 if (OpNum == OP_COPY) {
5429 if (LHSID == (1 * 9 + 2) * 9 + 3)
5430 return LHS;
5431 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5432 return RHS;
5433 }
5434
5435 SDValue OpLHS, OpRHS;
5436 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5437 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5438 EVT VT = OpLHS.getValueType();
5439
5440 switch (OpNum) {
5441 default:
5442 llvm_unreachable("Unknown shuffle opcode!");
5443 case OP_VREV:
5444 // VREV divides the vector in half and swaps within the half.
5445 if (VT.getVectorElementType() == MVT::i32 ||
5446 VT.getVectorElementType() == MVT::f32)
5447 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5448 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005449 if (VT.getVectorElementType() == MVT::i16 ||
5450 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005451 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5452 // vrev <4 x i8> -> REV16
5453 assert(VT.getVectorElementType() == MVT::i8);
5454 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5455 case OP_VDUP0:
5456 case OP_VDUP1:
5457 case OP_VDUP2:
5458 case OP_VDUP3: {
5459 EVT EltTy = VT.getVectorElementType();
5460 unsigned Opcode;
5461 if (EltTy == MVT::i8)
5462 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005463 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005464 Opcode = AArch64ISD::DUPLANE16;
5465 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5466 Opcode = AArch64ISD::DUPLANE32;
5467 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5468 Opcode = AArch64ISD::DUPLANE64;
5469 else
5470 llvm_unreachable("Invalid vector element type?");
5471
5472 if (VT.getSizeInBits() == 64)
5473 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005474 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005475 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5476 }
5477 case OP_VEXT1:
5478 case OP_VEXT2:
5479 case OP_VEXT3: {
5480 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5481 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005482 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005483 }
5484 case OP_VUZPL:
5485 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5486 OpRHS);
5487 case OP_VUZPR:
5488 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5489 OpRHS);
5490 case OP_VZIPL:
5491 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5492 OpRHS);
5493 case OP_VZIPR:
5494 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5495 OpRHS);
5496 case OP_VTRNL:
5497 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5498 OpRHS);
5499 case OP_VTRNR:
5500 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5501 OpRHS);
5502 }
5503}
5504
5505static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5506 SelectionDAG &DAG) {
5507 // Check to see if we can use the TBL instruction.
5508 SDValue V1 = Op.getOperand(0);
5509 SDValue V2 = Op.getOperand(1);
5510 SDLoc DL(Op);
5511
5512 EVT EltVT = Op.getValueType().getVectorElementType();
5513 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5514
5515 SmallVector<SDValue, 8> TBLMask;
5516 for (int Val : ShuffleMask) {
5517 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5518 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005519 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005520 }
5521 }
5522
5523 MVT IndexVT = MVT::v8i8;
5524 unsigned IndexLen = 8;
5525 if (Op.getValueType().getSizeInBits() == 128) {
5526 IndexVT = MVT::v16i8;
5527 IndexLen = 16;
5528 }
5529
5530 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5531 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5532
5533 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005534 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005535 if (IndexLen == 8)
5536 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5537 Shuffle = DAG.getNode(
5538 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005539 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005540 DAG.getBuildVector(IndexVT, DL,
5541 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005542 } else {
5543 if (IndexLen == 8) {
5544 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5545 Shuffle = DAG.getNode(
5546 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005547 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005548 DAG.getBuildVector(IndexVT, DL,
5549 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005550 } else {
5551 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5552 // cannot currently represent the register constraints on the input
5553 // table registers.
5554 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005555 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5556 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00005557 Shuffle = DAG.getNode(
5558 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005559 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5560 V2Cst, DAG.getBuildVector(IndexVT, DL,
5561 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005562 }
5563 }
5564 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5565}
5566
5567static unsigned getDUPLANEOp(EVT EltType) {
5568 if (EltType == MVT::i8)
5569 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005570 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005571 return AArch64ISD::DUPLANE16;
5572 if (EltType == MVT::i32 || EltType == MVT::f32)
5573 return AArch64ISD::DUPLANE32;
5574 if (EltType == MVT::i64 || EltType == MVT::f64)
5575 return AArch64ISD::DUPLANE64;
5576
5577 llvm_unreachable("Invalid vector element type?");
5578}
5579
5580SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5581 SelectionDAG &DAG) const {
5582 SDLoc dl(Op);
5583 EVT VT = Op.getValueType();
5584
5585 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5586
5587 // Convert shuffles that are directly supported on NEON to target-specific
5588 // DAG nodes, instead of keeping them as shuffles and matching them again
5589 // during code selection. This is more efficient and avoids the possibility
5590 // of inconsistencies between legalization and selection.
5591 ArrayRef<int> ShuffleMask = SVN->getMask();
5592
5593 SDValue V1 = Op.getOperand(0);
5594 SDValue V2 = Op.getOperand(1);
5595
Craig Topperbc56e3b2016-06-30 04:38:51 +00005596 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005597 int Lane = SVN->getSplatIndex();
5598 // If this is undef splat, generate it via "just" vdup, if possible.
5599 if (Lane == -1)
5600 Lane = 0;
5601
5602 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5603 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5604 V1.getOperand(0));
5605 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5606 // constant. If so, we can just reference the lane's definition directly.
5607 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5608 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5609 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5610
5611 // Otherwise, duplicate from the lane of the input vector.
5612 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5613
5614 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5615 // to make a vector of the same size as this SHUFFLE. We can ignore the
5616 // extract entirely, and canonicalise the concat using WidenVector.
5617 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5618 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5619 V1 = V1.getOperand(0);
5620 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5621 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5622 Lane -= Idx * VT.getVectorNumElements() / 2;
5623 V1 = WidenVector(V1.getOperand(Idx), DAG);
5624 } else if (VT.getSizeInBits() == 64)
5625 V1 = WidenVector(V1, DAG);
5626
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005627 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005628 }
5629
5630 if (isREVMask(ShuffleMask, VT, 64))
5631 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5632 if (isREVMask(ShuffleMask, VT, 32))
5633 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5634 if (isREVMask(ShuffleMask, VT, 16))
5635 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5636
5637 bool ReverseEXT = false;
5638 unsigned Imm;
5639 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5640 if (ReverseEXT)
5641 std::swap(V1, V2);
5642 Imm *= getExtFactor(V1);
5643 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005644 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00005645 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005646 Imm *= getExtFactor(V1);
5647 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005648 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005649 }
5650
5651 unsigned WhichResult;
5652 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5653 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5654 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5655 }
5656 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5657 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5658 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5659 }
5660 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5661 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5662 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5663 }
5664
5665 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5666 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5667 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5668 }
5669 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5670 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5671 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5672 }
5673 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5674 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5675 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5676 }
5677
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005678 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005679 return Concat;
5680
5681 bool DstIsLeft;
5682 int Anomaly;
5683 int NumInputElements = V1.getValueType().getVectorNumElements();
5684 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5685 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005686 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005687
5688 SDValue SrcVec = V1;
5689 int SrcLane = ShuffleMask[Anomaly];
5690 if (SrcLane >= NumInputElements) {
5691 SrcVec = V2;
5692 SrcLane -= VT.getVectorNumElements();
5693 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005694 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005695
5696 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005697
5698 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005699 ScalarVT = MVT::i32;
5700
5701 return DAG.getNode(
5702 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5703 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5704 DstLaneV);
5705 }
5706
5707 // If the shuffle is not directly supported and it has 4 elements, use
5708 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5709 unsigned NumElts = VT.getVectorNumElements();
5710 if (NumElts == 4) {
5711 unsigned PFIndexes[4];
5712 for (unsigned i = 0; i != 4; ++i) {
5713 if (ShuffleMask[i] < 0)
5714 PFIndexes[i] = 8;
5715 else
5716 PFIndexes[i] = ShuffleMask[i];
5717 }
5718
5719 // Compute the index in the perfect shuffle table.
5720 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5721 PFIndexes[2] * 9 + PFIndexes[3];
5722 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5723 unsigned Cost = (PFEntry >> 30);
5724
5725 if (Cost <= 4)
5726 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5727 }
5728
5729 return GenerateTBL(Op, ShuffleMask, DAG);
5730}
5731
5732static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5733 APInt &UndefBits) {
5734 EVT VT = BVN->getValueType(0);
5735 APInt SplatBits, SplatUndef;
5736 unsigned SplatBitSize;
5737 bool HasAnyUndefs;
5738 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5739 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5740
5741 for (unsigned i = 0; i < NumSplats; ++i) {
5742 CnstBits <<= SplatBitSize;
5743 UndefBits <<= SplatBitSize;
5744 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5745 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5746 }
5747
5748 return true;
5749 }
5750
5751 return false;
5752}
5753
5754SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5755 SelectionDAG &DAG) const {
5756 BuildVectorSDNode *BVN =
5757 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5758 SDValue LHS = Op.getOperand(0);
5759 SDLoc dl(Op);
5760 EVT VT = Op.getValueType();
5761
5762 if (!BVN)
5763 return Op;
5764
5765 APInt CnstBits(VT.getSizeInBits(), 0);
5766 APInt UndefBits(VT.getSizeInBits(), 0);
5767 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5768 // We only have BIC vector immediate instruction, which is and-not.
5769 CnstBits = ~CnstBits;
5770
5771 // We make use of a little bit of goto ickiness in order to avoid having to
5772 // duplicate the immediate matching logic for the undef toggled case.
5773 bool SecondTry = false;
5774 AttemptModImm:
5775
5776 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5777 CnstBits = CnstBits.zextOrTrunc(64);
5778 uint64_t CnstVal = CnstBits.getZExtValue();
5779
5780 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5781 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5782 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5783 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005784 DAG.getConstant(CnstVal, dl, MVT::i32),
5785 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005786 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005787 }
5788
5789 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5790 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5791 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5792 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005793 DAG.getConstant(CnstVal, dl, MVT::i32),
5794 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005795 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005796 }
5797
5798 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5799 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5800 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5801 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005802 DAG.getConstant(CnstVal, dl, MVT::i32),
5803 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005804 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005805 }
5806
5807 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5808 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5809 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5810 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005811 DAG.getConstant(CnstVal, dl, MVT::i32),
5812 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005813 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005814 }
5815
5816 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5817 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5818 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5819 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005820 DAG.getConstant(CnstVal, dl, MVT::i32),
5821 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005822 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005823 }
5824
5825 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5826 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5827 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5828 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005829 DAG.getConstant(CnstVal, dl, MVT::i32),
5830 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005831 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005832 }
5833 }
5834
5835 if (SecondTry)
5836 goto FailedModImm;
5837 SecondTry = true;
5838 CnstBits = ~UndefBits;
5839 goto AttemptModImm;
5840 }
5841
5842// We can always fall back to a non-immediate AND.
5843FailedModImm:
5844 return Op;
5845}
5846
5847// Specialized code to quickly find if PotentialBVec is a BuildVector that
5848// consists of only the same constant int value, returned in reference arg
5849// ConstVal
5850static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5851 uint64_t &ConstVal) {
5852 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5853 if (!Bvec)
5854 return false;
5855 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5856 if (!FirstElt)
5857 return false;
5858 EVT VT = Bvec->getValueType(0);
5859 unsigned NumElts = VT.getVectorNumElements();
5860 for (unsigned i = 1; i < NumElts; ++i)
5861 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5862 return false;
5863 ConstVal = FirstElt->getZExtValue();
5864 return true;
5865}
5866
5867static unsigned getIntrinsicID(const SDNode *N) {
5868 unsigned Opcode = N->getOpcode();
5869 switch (Opcode) {
5870 default:
5871 return Intrinsic::not_intrinsic;
5872 case ISD::INTRINSIC_WO_CHAIN: {
5873 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5874 if (IID < Intrinsic::num_intrinsics)
5875 return IID;
5876 return Intrinsic::not_intrinsic;
5877 }
5878 }
5879}
5880
5881// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5882// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5883// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5884// Also, logical shift right -> sri, with the same structure.
5885static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5886 EVT VT = N->getValueType(0);
5887
5888 if (!VT.isVector())
5889 return SDValue();
5890
5891 SDLoc DL(N);
5892
5893 // Is the first op an AND?
5894 const SDValue And = N->getOperand(0);
5895 if (And.getOpcode() != ISD::AND)
5896 return SDValue();
5897
5898 // Is the second op an shl or lshr?
5899 SDValue Shift = N->getOperand(1);
5900 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5901 // or AArch64ISD::VLSHR vector, #shift
5902 unsigned ShiftOpc = Shift.getOpcode();
5903 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5904 return SDValue();
5905 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5906
5907 // Is the shift amount constant?
5908 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5909 if (!C2node)
5910 return SDValue();
5911
5912 // Is the and mask vector all constant?
5913 uint64_t C1;
5914 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5915 return SDValue();
5916
5917 // Is C1 == ~C2, taking into account how much one can shift elements of a
5918 // particular size?
5919 uint64_t C2 = C2node->getZExtValue();
5920 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5921 if (C2 > ElemSizeInBits)
5922 return SDValue();
5923 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5924 if ((C1 & ElemMask) != (~C2 & ElemMask))
5925 return SDValue();
5926
5927 SDValue X = And.getOperand(0);
5928 SDValue Y = Shift.getOperand(0);
5929
5930 unsigned Intrin =
5931 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5932 SDValue ResultSLI =
5933 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005934 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5935 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005936
5937 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5938 DEBUG(N->dump(&DAG));
5939 DEBUG(dbgs() << "into: \n");
5940 DEBUG(ResultSLI->dump(&DAG));
5941
5942 ++NumShiftInserts;
5943 return ResultSLI;
5944}
5945
5946SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5947 SelectionDAG &DAG) const {
5948 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5949 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005950 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005951 return Res;
5952 }
5953
5954 BuildVectorSDNode *BVN =
5955 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5956 SDValue LHS = Op.getOperand(1);
5957 SDLoc dl(Op);
5958 EVT VT = Op.getValueType();
5959
5960 // OR commutes, so try swapping the operands.
5961 if (!BVN) {
5962 LHS = Op.getOperand(0);
5963 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5964 }
5965 if (!BVN)
5966 return Op;
5967
5968 APInt CnstBits(VT.getSizeInBits(), 0);
5969 APInt UndefBits(VT.getSizeInBits(), 0);
5970 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5971 // We make use of a little bit of goto ickiness in order to avoid having to
5972 // duplicate the immediate matching logic for the undef toggled case.
5973 bool SecondTry = false;
5974 AttemptModImm:
5975
5976 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5977 CnstBits = CnstBits.zextOrTrunc(64);
5978 uint64_t CnstVal = CnstBits.getZExtValue();
5979
5980 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5981 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5982 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5983 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005984 DAG.getConstant(CnstVal, dl, MVT::i32),
5985 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005986 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005987 }
5988
5989 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5990 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5991 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5992 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005993 DAG.getConstant(CnstVal, dl, MVT::i32),
5994 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005995 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005996 }
5997
5998 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5999 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6000 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6001 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006002 DAG.getConstant(CnstVal, dl, MVT::i32),
6003 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006004 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006005 }
6006
6007 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6008 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6009 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6010 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006011 DAG.getConstant(CnstVal, dl, MVT::i32),
6012 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006013 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006014 }
6015
6016 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6017 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6018 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6019 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006020 DAG.getConstant(CnstVal, dl, MVT::i32),
6021 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006022 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006023 }
6024
6025 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6026 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6027 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6028 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006029 DAG.getConstant(CnstVal, dl, MVT::i32),
6030 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006031 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006032 }
6033 }
6034
6035 if (SecondTry)
6036 goto FailedModImm;
6037 SecondTry = true;
6038 CnstBits = UndefBits;
6039 goto AttemptModImm;
6040 }
6041
6042// We can always fall back to a non-immediate OR.
6043FailedModImm:
6044 return Op;
6045}
6046
Kevin Qin4473c192014-07-07 02:45:40 +00006047// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6048// be truncated to fit element width.
6049static SDValue NormalizeBuildVector(SDValue Op,
6050 SelectionDAG &DAG) {
6051 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006052 SDLoc dl(Op);
6053 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006054 EVT EltTy= VT.getVectorElementType();
6055
6056 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6057 return Op;
6058
6059 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006060 for (SDValue Lane : Op->ops()) {
6061 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006062 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006063 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006064 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006065 }
6066 Ops.push_back(Lane);
6067 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006068 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006069}
6070
6071SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6072 SelectionDAG &DAG) const {
6073 SDLoc dl(Op);
6074 EVT VT = Op.getValueType();
6075 Op = NormalizeBuildVector(Op, DAG);
6076 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006077
6078 APInt CnstBits(VT.getSizeInBits(), 0);
6079 APInt UndefBits(VT.getSizeInBits(), 0);
6080 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6081 // We make use of a little bit of goto ickiness in order to avoid having to
6082 // duplicate the immediate matching logic for the undef toggled case.
6083 bool SecondTry = false;
6084 AttemptModImm:
6085
6086 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6087 CnstBits = CnstBits.zextOrTrunc(64);
6088 uint64_t CnstVal = CnstBits.getZExtValue();
6089
6090 // Certain magic vector constants (used to express things like NOT
6091 // and NEG) are passed through unmodified. This allows codegen patterns
6092 // for these operations to match. Special-purpose patterns will lower
6093 // these immediates to MOVIs if it proves necessary.
6094 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6095 return Op;
6096
6097 // The many faces of MOVI...
6098 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6099 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6100 if (VT.getSizeInBits() == 128) {
6101 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006102 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006103 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006104 }
6105
6106 // Support the V64 version via subregister insertion.
6107 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006108 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006109 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006110 }
6111
6112 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6113 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6114 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6115 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006116 DAG.getConstant(CnstVal, dl, MVT::i32),
6117 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006118 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006119 }
6120
6121 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6122 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6123 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6124 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006125 DAG.getConstant(CnstVal, dl, MVT::i32),
6126 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006127 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006128 }
6129
6130 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6131 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6132 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6133 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006134 DAG.getConstant(CnstVal, dl, MVT::i32),
6135 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006136 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006137 }
6138
6139 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6140 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6141 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6142 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006143 DAG.getConstant(CnstVal, dl, MVT::i32),
6144 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006145 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006146 }
6147
6148 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6149 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6150 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6151 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006152 DAG.getConstant(CnstVal, dl, MVT::i32),
6153 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006154 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006155 }
6156
6157 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6158 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6159 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6160 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006161 DAG.getConstant(CnstVal, dl, MVT::i32),
6162 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006163 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006164 }
6165
6166 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6167 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6168 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6169 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006170 DAG.getConstant(CnstVal, dl, MVT::i32),
6171 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006172 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006173 }
6174
6175 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6176 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6177 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6178 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006179 DAG.getConstant(CnstVal, dl, MVT::i32),
6180 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006181 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006182 }
6183
6184 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6185 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6186 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6187 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006188 DAG.getConstant(CnstVal, 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 // The few faces of FMOV...
6193 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6194 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6195 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6196 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006197 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006198 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006199 }
6200
6201 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6202 VT.getSizeInBits() == 128) {
6203 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6204 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006205 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006206 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006207 }
6208
6209 // The many faces of MVNI...
6210 CnstVal = ~CnstVal;
6211 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6212 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6213 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6214 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006215 DAG.getConstant(CnstVal, dl, MVT::i32),
6216 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006217 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006218 }
6219
6220 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6221 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6222 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6223 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006224 DAG.getConstant(CnstVal, dl, MVT::i32),
6225 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006226 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006227 }
6228
6229 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6230 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6231 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6232 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006233 DAG.getConstant(CnstVal, dl, MVT::i32),
6234 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006235 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006236 }
6237
6238 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6239 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6240 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6241 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006242 DAG.getConstant(CnstVal, dl, MVT::i32),
6243 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006244 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006245 }
6246
6247 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6248 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6249 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6250 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006251 DAG.getConstant(CnstVal, dl, MVT::i32),
6252 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006253 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006254 }
6255
6256 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6257 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6258 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6259 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006260 DAG.getConstant(CnstVal, dl, MVT::i32),
6261 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006262 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006263 }
6264
6265 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6266 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6267 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6268 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006269 DAG.getConstant(CnstVal, dl, MVT::i32),
6270 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006271 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006272 }
6273
6274 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6275 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6276 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6277 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006278 DAG.getConstant(CnstVal, dl, MVT::i32),
6279 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006280 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006281 }
6282 }
6283
6284 if (SecondTry)
6285 goto FailedModImm;
6286 SecondTry = true;
6287 CnstBits = UndefBits;
6288 goto AttemptModImm;
6289 }
6290FailedModImm:
6291
6292 // Scan through the operands to find some interesting properties we can
6293 // exploit:
6294 // 1) If only one value is used, we can use a DUP, or
6295 // 2) if only the low element is not undef, we can just insert that, or
6296 // 3) if only one constant value is used (w/ some non-constant lanes),
6297 // we can splat the constant value into the whole vector then fill
6298 // in the non-constant lanes.
6299 // 4) FIXME: If different constant values are used, but we can intelligently
6300 // select the values we'll be overwriting for the non-constant
6301 // lanes such that we can directly materialize the vector
6302 // some other way (MOVI, e.g.), we can be sneaky.
6303 unsigned NumElts = VT.getVectorNumElements();
6304 bool isOnlyLowElement = true;
6305 bool usesOnlyOneValue = true;
6306 bool usesOnlyOneConstantValue = true;
6307 bool isConstant = true;
6308 unsigned NumConstantLanes = 0;
6309 SDValue Value;
6310 SDValue ConstantValue;
6311 for (unsigned i = 0; i < NumElts; ++i) {
6312 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006313 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006314 continue;
6315 if (i > 0)
6316 isOnlyLowElement = false;
6317 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6318 isConstant = false;
6319
6320 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6321 ++NumConstantLanes;
6322 if (!ConstantValue.getNode())
6323 ConstantValue = V;
6324 else if (ConstantValue != V)
6325 usesOnlyOneConstantValue = false;
6326 }
6327
6328 if (!Value.getNode())
6329 Value = V;
6330 else if (V != Value)
6331 usesOnlyOneValue = false;
6332 }
6333
6334 if (!Value.getNode())
6335 return DAG.getUNDEF(VT);
6336
6337 if (isOnlyLowElement)
6338 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6339
6340 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6341 // i32 and try again.
6342 if (usesOnlyOneValue) {
6343 if (!isConstant) {
6344 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6345 Value.getValueType() != VT)
6346 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6347
6348 // This is actually a DUPLANExx operation, which keeps everything vectory.
6349
6350 // DUPLANE works on 128-bit vectors, widen it if necessary.
6351 SDValue Lane = Value.getOperand(1);
6352 Value = Value.getOperand(0);
6353 if (Value.getValueType().getSizeInBits() == 64)
6354 Value = WidenVector(Value, DAG);
6355
6356 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6357 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6358 }
6359
6360 if (VT.getVectorElementType().isFloatingPoint()) {
6361 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006362 EVT EltTy = VT.getVectorElementType();
6363 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6364 "Unsupported floating-point vector type");
6365 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006366 for (unsigned i = 0; i < NumElts; ++i)
6367 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6368 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006369 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Tim Northover3b0846e2014-05-24 12:50:23 +00006370 Val = LowerBUILD_VECTOR(Val, DAG);
6371 if (Val.getNode())
6372 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6373 }
6374 }
6375
6376 // If there was only one constant value used and for more than one lane,
6377 // start by splatting that value, then replace the non-constant lanes. This
6378 // is better than the default, which will perform a separate initialization
6379 // for each lane.
6380 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6381 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6382 // Now insert the non-constant lanes.
6383 for (unsigned i = 0; i < NumElts; ++i) {
6384 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006385 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006386 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6387 // Note that type legalization likely mucked about with the VT of the
6388 // source operand, so we may have to convert it here before inserting.
6389 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6390 }
6391 }
6392 return Val;
6393 }
6394
6395 // If all elements are constants and the case above didn't get hit, fall back
6396 // to the default expansion, which will generate a load from the constant
6397 // pool.
6398 if (isConstant)
6399 return SDValue();
6400
6401 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6402 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006403 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006404 return shuffle;
6405 }
6406
6407 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6408 // know the default expansion would otherwise fall back on something even
6409 // worse. For a vector with one or two non-undef values, that's
6410 // scalar_to_vector for the elements followed by a shuffle (provided the
6411 // shuffle is valid for the target) and materialization element by element
6412 // on the stack followed by a load for everything else.
6413 if (!isConstant && !usesOnlyOneValue) {
6414 SDValue Vec = DAG.getUNDEF(VT);
6415 SDValue Op0 = Op.getOperand(0);
6416 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6417 unsigned i = 0;
6418 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6419 // a) Avoid a RMW dependency on the full vector register, and
6420 // b) Allow the register coalescer to fold away the copy if the
6421 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006422 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6423 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
Sanjay Patel75068522016-03-14 18:09:43 +00006424 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
Matthias Braun0acbd082015-08-31 18:25:15 +00006425 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006426 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6427 MachineSDNode *N =
6428 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006429 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006430 Vec = SDValue(N, 0);
6431 ++i;
6432 }
6433 for (; i < NumElts; ++i) {
6434 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006435 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006436 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006437 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006438 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6439 }
6440 return Vec;
6441 }
6442
6443 // Just use the default expansion. We failed to find a better alternative.
6444 return SDValue();
6445}
6446
6447SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6448 SelectionDAG &DAG) const {
6449 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6450
Tim Northovere4b8e132014-07-15 10:00:26 +00006451 // Check for non-constant or out of range lane.
6452 EVT VT = Op.getOperand(0).getValueType();
6453 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6454 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006455 return SDValue();
6456
Tim Northover3b0846e2014-05-24 12:50:23 +00006457
6458 // Insertion/extraction are legal for V128 types.
6459 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006460 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6461 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006462 return Op;
6463
6464 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006465 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006466 return SDValue();
6467
6468 // For V64 types, we perform insertion by expanding the value
6469 // to a V128 type and perform the insertion on that.
6470 SDLoc DL(Op);
6471 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6472 EVT WideTy = WideVec.getValueType();
6473
6474 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6475 Op.getOperand(1), Op.getOperand(2));
6476 // Re-narrow the resultant vector.
6477 return NarrowVector(Node, DAG);
6478}
6479
6480SDValue
6481AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6482 SelectionDAG &DAG) const {
6483 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6484
Tim Northovere4b8e132014-07-15 10:00:26 +00006485 // Check for non-constant or out of range lane.
6486 EVT VT = Op.getOperand(0).getValueType();
6487 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6488 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006489 return SDValue();
6490
Tim Northover3b0846e2014-05-24 12:50:23 +00006491
6492 // Insertion/extraction are legal for V128 types.
6493 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006494 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6495 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006496 return Op;
6497
6498 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006499 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006500 return SDValue();
6501
6502 // For V64 types, we perform extraction by expanding the value
6503 // to a V128 type and perform the extraction on that.
6504 SDLoc DL(Op);
6505 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6506 EVT WideTy = WideVec.getValueType();
6507
6508 EVT ExtrTy = WideTy.getVectorElementType();
6509 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6510 ExtrTy = MVT::i32;
6511
6512 // For extractions, we just return the result directly.
6513 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6514 Op.getOperand(1));
6515}
6516
6517SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6518 SelectionDAG &DAG) const {
6519 EVT VT = Op.getOperand(0).getValueType();
6520 SDLoc dl(Op);
6521 // Just in case...
6522 if (!VT.isVector())
6523 return SDValue();
6524
6525 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6526 if (!Cst)
6527 return SDValue();
6528 unsigned Val = Cst->getZExtValue();
6529
6530 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006531
6532 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6533 if (Val == 0)
6534 return Op;
6535
Tim Northover3b0846e2014-05-24 12:50:23 +00006536 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6537 // that directly.
6538 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6539 return Op;
6540
6541 return SDValue();
6542}
6543
6544bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6545 EVT VT) const {
6546 if (VT.getVectorNumElements() == 4 &&
6547 (VT.is128BitVector() || VT.is64BitVector())) {
6548 unsigned PFIndexes[4];
6549 for (unsigned i = 0; i != 4; ++i) {
6550 if (M[i] < 0)
6551 PFIndexes[i] = 8;
6552 else
6553 PFIndexes[i] = M[i];
6554 }
6555
6556 // Compute the index in the perfect shuffle table.
6557 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6558 PFIndexes[2] * 9 + PFIndexes[3];
6559 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6560 unsigned Cost = (PFEntry >> 30);
6561
6562 if (Cost <= 4)
6563 return true;
6564 }
6565
6566 bool DummyBool;
6567 int DummyInt;
6568 unsigned DummyUnsigned;
6569
6570 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6571 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6572 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6573 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6574 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6575 isZIPMask(M, VT, DummyUnsigned) ||
6576 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6577 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6578 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6579 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6580 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6581}
6582
6583/// getVShiftImm - Check if this is a valid build_vector for the immediate
6584/// operand of a vector shift operation, where all the elements of the
6585/// build_vector must have the same constant integer value.
6586static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6587 // Ignore bit_converts.
6588 while (Op.getOpcode() == ISD::BITCAST)
6589 Op = Op.getOperand(0);
6590 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6591 APInt SplatBits, SplatUndef;
6592 unsigned SplatBitSize;
6593 bool HasAnyUndefs;
6594 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6595 HasAnyUndefs, ElementBits) ||
6596 SplatBitSize > ElementBits)
6597 return false;
6598 Cnt = SplatBits.getSExtValue();
6599 return true;
6600}
6601
6602/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6603/// operand of a vector shift left operation. That value must be in the range:
6604/// 0 <= Value < ElementBits for a left shift; or
6605/// 0 <= Value <= ElementBits for a long left shift.
6606static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6607 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006608 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006609 if (!getVShiftImm(Op, ElementBits, Cnt))
6610 return false;
6611 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6612}
6613
6614/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006615/// operand of a vector shift right operation. The value must be in the range:
6616/// 1 <= Value <= ElementBits for a right shift; or
6617static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006618 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006619 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006620 if (!getVShiftImm(Op, ElementBits, Cnt))
6621 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006622 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6623}
6624
6625SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6626 SelectionDAG &DAG) const {
6627 EVT VT = Op.getValueType();
6628 SDLoc DL(Op);
6629 int64_t Cnt;
6630
6631 if (!Op.getOperand(1).getValueType().isVector())
6632 return Op;
6633 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6634
6635 switch (Op.getOpcode()) {
6636 default:
6637 llvm_unreachable("unexpected shift opcode");
6638
6639 case ISD::SHL:
6640 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006641 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6642 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006643 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006644 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6645 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006646 Op.getOperand(0), Op.getOperand(1));
6647 case ISD::SRA:
6648 case ISD::SRL:
6649 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006650 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006651 unsigned Opc =
6652 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006653 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6654 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006655 }
6656
6657 // Right shift register. Note, there is not a shift right register
6658 // instruction, but the shift left register instruction takes a signed
6659 // value, where negative numbers specify a right shift.
6660 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6661 : Intrinsic::aarch64_neon_ushl;
6662 // negate the shift amount
6663 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6664 SDValue NegShiftLeft =
6665 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006666 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6667 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006668 return NegShiftLeft;
6669 }
6670
6671 return SDValue();
6672}
6673
6674static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6675 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006676 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006677 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006678 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6679 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006680
6681 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6682 APInt CnstBits(VT.getSizeInBits(), 0);
6683 APInt UndefBits(VT.getSizeInBits(), 0);
6684 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6685 bool IsZero = IsCnst && (CnstBits == 0);
6686
6687 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6688 switch (CC) {
6689 default:
6690 return SDValue();
6691 case AArch64CC::NE: {
6692 SDValue Fcmeq;
6693 if (IsZero)
6694 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6695 else
6696 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6697 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6698 }
6699 case AArch64CC::EQ:
6700 if (IsZero)
6701 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6702 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6703 case AArch64CC::GE:
6704 if (IsZero)
6705 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6706 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6707 case AArch64CC::GT:
6708 if (IsZero)
6709 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6710 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6711 case AArch64CC::LS:
6712 if (IsZero)
6713 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6714 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6715 case AArch64CC::LT:
6716 if (!NoNans)
6717 return SDValue();
6718 // If we ignore NaNs then we can use to the MI implementation.
6719 // Fallthrough.
6720 case AArch64CC::MI:
6721 if (IsZero)
6722 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6723 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6724 }
6725 }
6726
6727 switch (CC) {
6728 default:
6729 return SDValue();
6730 case AArch64CC::NE: {
6731 SDValue Cmeq;
6732 if (IsZero)
6733 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6734 else
6735 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6736 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6737 }
6738 case AArch64CC::EQ:
6739 if (IsZero)
6740 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6741 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6742 case AArch64CC::GE:
6743 if (IsZero)
6744 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6745 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6746 case AArch64CC::GT:
6747 if (IsZero)
6748 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6749 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6750 case AArch64CC::LE:
6751 if (IsZero)
6752 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6753 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6754 case AArch64CC::LS:
6755 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6756 case AArch64CC::LO:
6757 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6758 case AArch64CC::LT:
6759 if (IsZero)
6760 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6761 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6762 case AArch64CC::HI:
6763 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6764 case AArch64CC::HS:
6765 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6766 }
6767}
6768
6769SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6770 SelectionDAG &DAG) const {
6771 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6772 SDValue LHS = Op.getOperand(0);
6773 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006774 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006775 SDLoc dl(Op);
6776
6777 if (LHS.getValueType().getVectorElementType().isInteger()) {
6778 assert(LHS.getValueType() == RHS.getValueType());
6779 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006780 SDValue Cmp =
6781 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6782 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006783 }
6784
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006785 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6786 return SDValue();
6787
Tim Northover3b0846e2014-05-24 12:50:23 +00006788 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6789 LHS.getValueType().getVectorElementType() == MVT::f64);
6790
6791 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6792 // clean. Some of them require two branches to implement.
6793 AArch64CC::CondCode CC1, CC2;
6794 bool ShouldInvert;
6795 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6796
6797 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6798 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006799 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006800 if (!Cmp.getNode())
6801 return SDValue();
6802
6803 if (CC2 != AArch64CC::AL) {
6804 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006805 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006806 if (!Cmp2.getNode())
6807 return SDValue();
6808
Tim Northover45aa89c2015-02-08 00:50:47 +00006809 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006810 }
6811
Tim Northover45aa89c2015-02-08 00:50:47 +00006812 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6813
Tim Northover3b0846e2014-05-24 12:50:23 +00006814 if (ShouldInvert)
6815 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6816
6817 return Cmp;
6818}
6819
6820/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6821/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6822/// specified in the intrinsic calls.
6823bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6824 const CallInst &I,
6825 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006826 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006827 switch (Intrinsic) {
6828 case Intrinsic::aarch64_neon_ld2:
6829 case Intrinsic::aarch64_neon_ld3:
6830 case Intrinsic::aarch64_neon_ld4:
6831 case Intrinsic::aarch64_neon_ld1x2:
6832 case Intrinsic::aarch64_neon_ld1x3:
6833 case Intrinsic::aarch64_neon_ld1x4:
6834 case Intrinsic::aarch64_neon_ld2lane:
6835 case Intrinsic::aarch64_neon_ld3lane:
6836 case Intrinsic::aarch64_neon_ld4lane:
6837 case Intrinsic::aarch64_neon_ld2r:
6838 case Intrinsic::aarch64_neon_ld3r:
6839 case Intrinsic::aarch64_neon_ld4r: {
6840 Info.opc = ISD::INTRINSIC_W_CHAIN;
6841 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006842 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006843 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6844 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6845 Info.offset = 0;
6846 Info.align = 0;
6847 Info.vol = false; // volatile loads with NEON intrinsics not supported
6848 Info.readMem = true;
6849 Info.writeMem = false;
6850 return true;
6851 }
6852 case Intrinsic::aarch64_neon_st2:
6853 case Intrinsic::aarch64_neon_st3:
6854 case Intrinsic::aarch64_neon_st4:
6855 case Intrinsic::aarch64_neon_st1x2:
6856 case Intrinsic::aarch64_neon_st1x3:
6857 case Intrinsic::aarch64_neon_st1x4:
6858 case Intrinsic::aarch64_neon_st2lane:
6859 case Intrinsic::aarch64_neon_st3lane:
6860 case Intrinsic::aarch64_neon_st4lane: {
6861 Info.opc = ISD::INTRINSIC_VOID;
6862 // Conservatively set memVT to the entire set of vectors stored.
6863 unsigned NumElts = 0;
6864 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6865 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6866 if (!ArgTy->isVectorTy())
6867 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006868 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006869 }
6870 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6871 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6872 Info.offset = 0;
6873 Info.align = 0;
6874 Info.vol = false; // volatile stores with NEON intrinsics not supported
6875 Info.readMem = false;
6876 Info.writeMem = true;
6877 return true;
6878 }
6879 case Intrinsic::aarch64_ldaxr:
6880 case Intrinsic::aarch64_ldxr: {
6881 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6882 Info.opc = ISD::INTRINSIC_W_CHAIN;
6883 Info.memVT = MVT::getVT(PtrTy->getElementType());
6884 Info.ptrVal = I.getArgOperand(0);
6885 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006886 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006887 Info.vol = true;
6888 Info.readMem = true;
6889 Info.writeMem = false;
6890 return true;
6891 }
6892 case Intrinsic::aarch64_stlxr:
6893 case Intrinsic::aarch64_stxr: {
6894 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6895 Info.opc = ISD::INTRINSIC_W_CHAIN;
6896 Info.memVT = MVT::getVT(PtrTy->getElementType());
6897 Info.ptrVal = I.getArgOperand(1);
6898 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006899 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006900 Info.vol = true;
6901 Info.readMem = false;
6902 Info.writeMem = true;
6903 return true;
6904 }
6905 case Intrinsic::aarch64_ldaxp:
6906 case Intrinsic::aarch64_ldxp: {
6907 Info.opc = ISD::INTRINSIC_W_CHAIN;
6908 Info.memVT = MVT::i128;
6909 Info.ptrVal = I.getArgOperand(0);
6910 Info.offset = 0;
6911 Info.align = 16;
6912 Info.vol = true;
6913 Info.readMem = true;
6914 Info.writeMem = false;
6915 return true;
6916 }
6917 case Intrinsic::aarch64_stlxp:
6918 case Intrinsic::aarch64_stxp: {
6919 Info.opc = ISD::INTRINSIC_W_CHAIN;
6920 Info.memVT = MVT::i128;
6921 Info.ptrVal = I.getArgOperand(2);
6922 Info.offset = 0;
6923 Info.align = 16;
6924 Info.vol = true;
6925 Info.readMem = false;
6926 Info.writeMem = true;
6927 return true;
6928 }
6929 default:
6930 break;
6931 }
6932
6933 return false;
6934}
6935
6936// Truncations from 64-bit GPR to 32-bit GPR is free.
6937bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6938 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6939 return false;
6940 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6941 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006942 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006943}
6944bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006945 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006946 return false;
6947 unsigned NumBits1 = VT1.getSizeInBits();
6948 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006949 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006950}
6951
Chad Rosier54390052015-02-23 19:15:16 +00006952/// Check if it is profitable to hoist instruction in then/else to if.
6953/// Not profitable if I and it's user can form a FMA instruction
6954/// because we prefer FMSUB/FMADD.
6955bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6956 if (I->getOpcode() != Instruction::FMul)
6957 return true;
6958
6959 if (I->getNumUses() != 1)
6960 return true;
6961
6962 Instruction *User = I->user_back();
6963
6964 if (User &&
6965 !(User->getOpcode() == Instruction::FSub ||
6966 User->getOpcode() == Instruction::FAdd))
6967 return true;
6968
6969 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006970 const DataLayout &DL = I->getModule()->getDataLayout();
6971 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006972
Eric Christopher114fa1c2016-02-29 22:50:49 +00006973 return !(isFMAFasterThanFMulAndFAdd(VT) &&
6974 isOperationLegalOrCustom(ISD::FMA, VT) &&
6975 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
6976 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00006977}
6978
Tim Northover3b0846e2014-05-24 12:50:23 +00006979// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6980// 64-bit GPR.
6981bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6982 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6983 return false;
6984 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6985 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006986 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006987}
6988bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006989 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006990 return false;
6991 unsigned NumBits1 = VT1.getSizeInBits();
6992 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006993 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006994}
6995
6996bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6997 EVT VT1 = Val.getValueType();
6998 if (isZExtFree(VT1, VT2)) {
6999 return true;
7000 }
7001
7002 if (Val.getOpcode() != ISD::LOAD)
7003 return false;
7004
7005 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007006 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7007 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7008 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007009}
7010
Quentin Colombet6843ac42015-03-31 20:52:32 +00007011bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7012 if (isa<FPExtInst>(Ext))
7013 return false;
7014
7015 // Vector types are next free.
7016 if (Ext->getType()->isVectorTy())
7017 return false;
7018
7019 for (const Use &U : Ext->uses()) {
7020 // The extension is free if we can fold it with a left shift in an
7021 // addressing mode or an arithmetic operation: add, sub, and cmp.
7022
7023 // Is there a shift?
7024 const Instruction *Instr = cast<Instruction>(U.getUser());
7025
7026 // Is this a constant shift?
7027 switch (Instr->getOpcode()) {
7028 case Instruction::Shl:
7029 if (!isa<ConstantInt>(Instr->getOperand(1)))
7030 return false;
7031 break;
7032 case Instruction::GetElementPtr: {
7033 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007034 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007035 std::advance(GTI, U.getOperandNo());
7036 Type *IdxTy = *GTI;
7037 // This extension will end up with a shift because of the scaling factor.
7038 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7039 // Get the shift amount based on the scaling factor:
7040 // log2(sizeof(IdxTy)) - log2(8).
7041 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007042 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007043 // Is the constant foldable in the shift of the addressing mode?
7044 // I.e., shift amount is between 1 and 4 inclusive.
7045 if (ShiftAmt == 0 || ShiftAmt > 4)
7046 return false;
7047 break;
7048 }
7049 case Instruction::Trunc:
7050 // Check if this is a noop.
7051 // trunc(sext ty1 to ty2) to ty1.
7052 if (Instr->getType() == Ext->getOperand(0)->getType())
7053 continue;
7054 // FALL THROUGH.
7055 default:
7056 return false;
7057 }
7058
7059 // At this point we can use the bfm family, so this extension is free
7060 // for that use.
7061 }
7062 return true;
7063}
7064
Tim Northover3b0846e2014-05-24 12:50:23 +00007065bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7066 unsigned &RequiredAligment) const {
7067 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7068 return false;
7069 // Cyclone supports unaligned accesses.
7070 RequiredAligment = 0;
7071 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7072 return NumBits == 32 || NumBits == 64;
7073}
7074
7075bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7076 unsigned &RequiredAligment) const {
7077 if (!LoadedType.isSimple() ||
7078 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7079 return false;
7080 // Cyclone supports unaligned accesses.
7081 RequiredAligment = 0;
7082 unsigned NumBits = LoadedType.getSizeInBits();
7083 return NumBits == 32 || NumBits == 64;
7084}
7085
Hao Liu7ec8ee32015-06-26 02:32:07 +00007086/// \brief Lower an interleaved load into a ldN intrinsic.
7087///
7088/// E.g. Lower an interleaved load (Factor = 2):
7089/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7090/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7091/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7092///
7093/// Into:
7094/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7095/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7096/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7097bool AArch64TargetLowering::lowerInterleavedLoad(
7098 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7099 ArrayRef<unsigned> Indices, unsigned Factor) const {
7100 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7101 "Invalid interleave factor");
7102 assert(!Shuffles.empty() && "Empty shufflevector input");
7103 assert(Shuffles.size() == Indices.size() &&
7104 "Unmatched number of shufflevectors and indices");
7105
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007106 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007107
7108 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007109 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007110
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007111 // Skip if we do not have NEON and skip illegal vector types.
7112 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007113 return false;
7114
7115 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7116 // load integer vectors first and then convert to pointer vectors.
7117 Type *EltTy = VecTy->getVectorElementType();
7118 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007119 VecTy =
7120 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007121
7122 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7123 Type *Tys[2] = {VecTy, PtrTy};
7124 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7125 Intrinsic::aarch64_neon_ld3,
7126 Intrinsic::aarch64_neon_ld4};
7127 Function *LdNFunc =
7128 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7129
7130 IRBuilder<> Builder(LI);
7131 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7132
7133 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7134
7135 // Replace uses of each shufflevector with the corresponding vector loaded
7136 // by ldN.
7137 for (unsigned i = 0; i < Shuffles.size(); i++) {
7138 ShuffleVectorInst *SVI = Shuffles[i];
7139 unsigned Index = Indices[i];
7140
7141 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7142
7143 // Convert the integer vector to pointer vector if the element is pointer.
7144 if (EltTy->isPointerTy())
7145 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7146
7147 SVI->replaceAllUsesWith(SubVec);
7148 }
7149
7150 return true;
7151}
7152
7153/// \brief Get a mask consisting of sequential integers starting from \p Start.
7154///
7155/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7156static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7157 unsigned NumElts) {
7158 SmallVector<Constant *, 16> Mask;
7159 for (unsigned i = 0; i < NumElts; i++)
7160 Mask.push_back(Builder.getInt32(Start + i));
7161
7162 return ConstantVector::get(Mask);
7163}
7164
7165/// \brief Lower an interleaved store into a stN intrinsic.
7166///
7167/// E.g. Lower an interleaved store (Factor = 3):
7168/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7169/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7170/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7171///
7172/// Into:
7173/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7174/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7175/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7176/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7177///
7178/// Note that the new shufflevectors will be removed and we'll only generate one
7179/// st3 instruction in CodeGen.
7180bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7181 ShuffleVectorInst *SVI,
7182 unsigned Factor) const {
7183 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7184 "Invalid interleave factor");
7185
7186 VectorType *VecTy = SVI->getType();
7187 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7188 "Invalid interleaved store");
7189
7190 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7191 Type *EltTy = VecTy->getVectorElementType();
7192 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7193
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007194 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007195 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007196
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007197 // Skip if we do not have NEON and skip illegal vector types.
7198 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007199 return false;
7200
7201 Value *Op0 = SVI->getOperand(0);
7202 Value *Op1 = SVI->getOperand(1);
7203 IRBuilder<> Builder(SI);
7204
7205 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7206 // vectors to integer vectors.
7207 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007208 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007209 unsigned NumOpElts =
7210 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7211
7212 // Convert to the corresponding integer vector.
7213 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7214 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7215 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7216
7217 SubVecTy = VectorType::get(IntTy, NumSubElts);
7218 }
7219
7220 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7221 Type *Tys[2] = {SubVecTy, PtrTy};
7222 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7223 Intrinsic::aarch64_neon_st3,
7224 Intrinsic::aarch64_neon_st4};
7225 Function *StNFunc =
7226 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7227
7228 SmallVector<Value *, 5> Ops;
7229
7230 // Split the shufflevector operands into sub vectors for the new stN call.
7231 for (unsigned i = 0; i < Factor; i++)
7232 Ops.push_back(Builder.CreateShuffleVector(
7233 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7234
7235 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7236 Builder.CreateCall(StNFunc, Ops);
7237 return true;
7238}
7239
Tim Northover3b0846e2014-05-24 12:50:23 +00007240static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7241 unsigned AlignCheck) {
7242 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7243 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7244}
7245
7246EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7247 unsigned SrcAlign, bool IsMemset,
7248 bool ZeroMemset,
7249 bool MemcpyStrSrc,
7250 MachineFunction &MF) const {
7251 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7252 // instruction to materialize the v2i64 zero and one store (with restrictive
7253 // addressing mode). Just do two i64 store of zero-registers.
7254 bool Fast;
7255 const Function *F = MF.getFunction();
7256 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007257 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007258 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007259 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007260 return MVT::f128;
7261
Lang Hames90333852015-04-09 03:40:33 +00007262 if (Size >= 8 &&
7263 (memOpAlign(SrcAlign, DstAlign, 8) ||
7264 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7265 return MVT::i64;
7266
7267 if (Size >= 4 &&
7268 (memOpAlign(SrcAlign, DstAlign, 4) ||
7269 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007270 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007271
7272 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007273}
7274
7275// 12-bit optionally shifted immediates are legal for adds.
7276bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berry486f49c2016-06-07 16:48:43 +00007277 // Avoid UB for INT64_MIN.
7278 if (Immed == std::numeric_limits<int64_t>::min())
7279 return false;
7280 // Same encoding for add/sub, just flip the sign.
7281 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007282 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007283}
7284
7285// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7286// immediates is the same as for an add or a sub.
7287bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007288 return isLegalAddImmediate(Immed);
7289}
7290
7291/// isLegalAddressingMode - Return true if the addressing mode represented
7292/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007293bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7294 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007295 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007296 // AArch64 has five basic addressing modes:
7297 // reg
7298 // reg + 9-bit signed offset
7299 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7300 // reg1 + reg2
7301 // reg + SIZE_IN_BYTES * reg
7302
7303 // No global is ever allowed as a base.
7304 if (AM.BaseGV)
7305 return false;
7306
7307 // No reg+reg+imm addressing.
7308 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7309 return false;
7310
7311 // check reg + imm case:
7312 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7313 uint64_t NumBytes = 0;
7314 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007315 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007316 NumBytes = NumBits / 8;
7317 if (!isPowerOf2_64(NumBits))
7318 NumBytes = 0;
7319 }
7320
7321 if (!AM.Scale) {
7322 int64_t Offset = AM.BaseOffs;
7323
7324 // 9-bit signed offset
7325 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7326 return true;
7327
7328 // 12-bit unsigned offset
7329 unsigned shift = Log2_64(NumBytes);
7330 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7331 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7332 (Offset >> shift) << shift == Offset)
7333 return true;
7334 return false;
7335 }
7336
7337 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7338
Eric Christopher114fa1c2016-02-29 22:50:49 +00007339 return !AM.Scale || AM.Scale == 1 ||
7340 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007341}
7342
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007343int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7344 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007345 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007346 // Scaling factors are not free at all.
7347 // Operands | Rt Latency
7348 // -------------------------------------------
7349 // Rt, [Xn, Xm] | 4
7350 // -------------------------------------------
7351 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7352 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007353 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007354 // Scale represents reg2 * scale, thus account for 1 if
7355 // it is not equal to 0 or 1.
7356 return AM.Scale != 0 && AM.Scale != 1;
7357 return -1;
7358}
7359
7360bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7361 VT = VT.getScalarType();
7362
7363 if (!VT.isSimple())
7364 return false;
7365
7366 switch (VT.getSimpleVT().SimpleTy) {
7367 case MVT::f32:
7368 case MVT::f64:
7369 return true;
7370 default:
7371 break;
7372 }
7373
7374 return false;
7375}
7376
7377const MCPhysReg *
7378AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7379 // LR is a callee-save register, but we must treat it as clobbered by any call
7380 // site. Hence we include LR in the scratch registers, which are in turn added
7381 // as implicit-defs for stackmaps and patchpoints.
7382 static const MCPhysReg ScratchRegs[] = {
7383 AArch64::X16, AArch64::X17, AArch64::LR, 0
7384 };
7385 return ScratchRegs;
7386}
7387
7388bool
7389AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7390 EVT VT = N->getValueType(0);
7391 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7392 // it with shift to let it be lowered to UBFX.
7393 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7394 isa<ConstantSDNode>(N->getOperand(1))) {
7395 uint64_t TruncMask = N->getConstantOperandVal(1);
7396 if (isMask_64(TruncMask) &&
7397 N->getOperand(0).getOpcode() == ISD::SRL &&
7398 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7399 return false;
7400 }
7401 return true;
7402}
7403
7404bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7405 Type *Ty) const {
7406 assert(Ty->isIntegerTy());
7407
7408 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7409 if (BitSize == 0)
7410 return false;
7411
7412 int64_t Val = Imm.getSExtValue();
7413 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7414 return true;
7415
7416 if ((int64_t)Val < 0)
7417 Val = ~Val;
7418 if (BitSize == 32)
7419 Val &= (1LL << 32) - 1;
7420
7421 unsigned LZ = countLeadingZeros((uint64_t)Val);
7422 unsigned Shift = (63 - LZ) / 16;
7423 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007424 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007425}
7426
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007427/// Turn vector tests of the signbit in the form of:
7428/// xor (sra X, elt_size(X)-1), -1
7429/// into:
7430/// cmge X, X, #0
7431static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7432 const AArch64Subtarget *Subtarget) {
7433 EVT VT = N->getValueType(0);
7434 if (!Subtarget->hasNEON() || !VT.isVector())
7435 return SDValue();
7436
7437 // There must be a shift right algebraic before the xor, and the xor must be a
7438 // 'not' operation.
7439 SDValue Shift = N->getOperand(0);
7440 SDValue Ones = N->getOperand(1);
7441 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7442 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7443 return SDValue();
7444
7445 // The shift should be smearing the sign bit across each vector element.
7446 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7447 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7448 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7449 return SDValue();
7450
7451 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7452}
7453
Tim Northover3b0846e2014-05-24 12:50:23 +00007454// Generate SUBS and CSEL for integer abs.
7455static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7456 EVT VT = N->getValueType(0);
7457
7458 SDValue N0 = N->getOperand(0);
7459 SDValue N1 = N->getOperand(1);
7460 SDLoc DL(N);
7461
7462 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7463 // and change it to SUB and CSEL.
7464 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7465 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7466 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7467 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7468 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007469 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007470 N0.getOperand(0));
7471 // Generate SUBS & CSEL.
7472 SDValue Cmp =
7473 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007474 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007475 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007476 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007477 SDValue(Cmp.getNode(), 1));
7478 }
7479 return SDValue();
7480}
7481
Tim Northover3b0846e2014-05-24 12:50:23 +00007482static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7483 TargetLowering::DAGCombinerInfo &DCI,
7484 const AArch64Subtarget *Subtarget) {
7485 if (DCI.isBeforeLegalizeOps())
7486 return SDValue();
7487
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007488 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7489 return Cmp;
7490
Tim Northover3b0846e2014-05-24 12:50:23 +00007491 return performIntegerAbsCombine(N, DAG);
7492}
7493
Chad Rosier17020f92014-07-23 14:57:52 +00007494SDValue
7495AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7496 SelectionDAG &DAG,
7497 std::vector<SDNode *> *Created) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +00007498 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7499 if (isIntDivCheap(N->getValueType(0), Attr))
7500 return SDValue(N,0); // Lower SDIV as SDIV
7501
Chad Rosier17020f92014-07-23 14:57:52 +00007502 // fold (sdiv X, pow2)
7503 EVT VT = N->getValueType(0);
7504 if ((VT != MVT::i32 && VT != MVT::i64) ||
7505 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7506 return SDValue();
7507
7508 SDLoc DL(N);
7509 SDValue N0 = N->getOperand(0);
7510 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007511 SDValue Zero = DAG.getConstant(0, DL, VT);
7512 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007513
7514 // Add (N0 < 0) ? Pow2 - 1 : 0;
7515 SDValue CCVal;
7516 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7517 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7518 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7519
7520 if (Created) {
7521 Created->push_back(Cmp.getNode());
7522 Created->push_back(Add.getNode());
7523 Created->push_back(CSel.getNode());
7524 }
7525
7526 // Divide by pow2.
7527 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007528 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007529
7530 // If we're dividing by a positive value, we're done. Otherwise, we must
7531 // negate the result.
7532 if (Divisor.isNonNegative())
7533 return SRA;
7534
7535 if (Created)
7536 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007537 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007538}
7539
Tim Northover3b0846e2014-05-24 12:50:23 +00007540static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7541 TargetLowering::DAGCombinerInfo &DCI,
7542 const AArch64Subtarget *Subtarget) {
7543 if (DCI.isBeforeLegalizeOps())
7544 return SDValue();
7545
7546 // Multiplication of a power of two plus/minus one can be done more
7547 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7548 // future CPUs have a cheaper MADD instruction, this may need to be
7549 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7550 // 64-bit is 5 cycles, so this is always a win.
7551 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00007552 const APInt &Value = C->getAPIntValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00007553 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007554 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007555 if (Value.isNonNegative()) {
7556 // (mul x, 2^N + 1) => (add (shl x, N), x)
7557 APInt VM1 = Value - 1;
7558 if (VM1.isPowerOf2()) {
7559 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007560 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7561 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7562 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007563 N->getOperand(0));
7564 }
7565 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7566 APInt VP1 = Value + 1;
7567 if (VP1.isPowerOf2()) {
7568 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007569 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7570 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7571 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007572 N->getOperand(0));
7573 }
7574 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007575 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7576 APInt VNP1 = -Value + 1;
7577 if (VNP1.isPowerOf2()) {
7578 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007579 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7580 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7581 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007582 ShiftedVal);
7583 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007584 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7585 APInt VNM1 = -Value - 1;
7586 if (VNM1.isPowerOf2()) {
7587 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007588 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7589 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007590 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007591 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7592 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007593 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007594 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007595 }
7596 return SDValue();
7597}
7598
Jim Grosbachf7502c42014-07-18 00:40:52 +00007599static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7600 SelectionDAG &DAG) {
7601 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7602 // optimize away operation when it's from a constant.
7603 //
7604 // The general transformation is:
7605 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7606 // AND(VECTOR_CMP(x,y), constant2)
7607 // constant2 = UNARYOP(constant)
7608
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007609 // Early exit if this isn't a vector operation, the operand of the
7610 // unary operation isn't a bitwise AND, or if the sizes of the operations
7611 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007612 EVT VT = N->getValueType(0);
7613 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007614 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7615 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007616 return SDValue();
7617
Jim Grosbach724e4382014-07-23 20:41:43 +00007618 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007619 // make the transformation for non-constant splats as well, but it's unclear
7620 // that would be a benefit as it would not eliminate any operations, just
7621 // perform one more step in scalar code before moving to the vector unit.
7622 if (BuildVectorSDNode *BV =
7623 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007624 // Bail out if the vector isn't a constant.
7625 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007626 return SDValue();
7627
7628 // Everything checks out. Build up the new and improved node.
7629 SDLoc DL(N);
7630 EVT IntVT = BV->getValueType(0);
7631 // Create a new constant of the appropriate type for the transformed
7632 // DAG.
7633 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7634 // The AND node needs bitcasts to/from an integer vector type around it.
7635 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7636 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7637 N->getOperand(0)->getOperand(0), MaskConst);
7638 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7639 return Res;
7640 }
7641
7642 return SDValue();
7643}
7644
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007645static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7646 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007647 // First try to optimize away the conversion when it's conditionally from
7648 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007649 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007650 return Res;
7651
Tim Northover3b0846e2014-05-24 12:50:23 +00007652 EVT VT = N->getValueType(0);
7653 if (VT != MVT::f32 && VT != MVT::f64)
7654 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007655
Tim Northover3b0846e2014-05-24 12:50:23 +00007656 // Only optimize when the source and destination types have the same width.
7657 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7658 return SDValue();
7659
7660 // If the result of an integer load is only used by an integer-to-float
7661 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007662 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007663 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007664 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007665 // Do not change the width of a volatile load.
7666 !cast<LoadSDNode>(N0)->isVolatile()) {
7667 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7668 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00007669 LN0->getPointerInfo(), LN0->getAlignment(),
7670 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00007671
7672 // Make sure successors of the original load stay after it by updating them
7673 // to use the new Chain.
7674 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7675
7676 unsigned Opcode =
7677 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7678 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7679 }
7680
7681 return SDValue();
7682}
7683
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007684/// Fold a floating-point multiply by power of two into floating-point to
7685/// fixed-point conversion.
7686static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7687 const AArch64Subtarget *Subtarget) {
7688 if (!Subtarget->hasNEON())
7689 return SDValue();
7690
7691 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00007692 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7693 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007694 return SDValue();
7695
7696 SDValue ConstVec = Op->getOperand(1);
7697 if (!isa<BuildVectorSDNode>(ConstVec))
7698 return SDValue();
7699
7700 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7701 uint32_t FloatBits = FloatTy.getSizeInBits();
7702 if (FloatBits != 32 && FloatBits != 64)
7703 return SDValue();
7704
7705 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7706 uint32_t IntBits = IntTy.getSizeInBits();
7707 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7708 return SDValue();
7709
7710 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7711 if (IntBits > FloatBits)
7712 return SDValue();
7713
7714 BitVector UndefElements;
7715 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7716 int32_t Bits = IntBits == 64 ? 64 : 32;
7717 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7718 if (C == -1 || C == 0 || C > Bits)
7719 return SDValue();
7720
7721 MVT ResTy;
7722 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7723 switch (NumLanes) {
7724 default:
7725 return SDValue();
7726 case 2:
7727 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7728 break;
7729 case 4:
7730 ResTy = MVT::v4i32;
7731 break;
7732 }
7733
7734 SDLoc DL(N);
7735 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7736 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7737 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7738 SDValue FixConv =
7739 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7740 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7741 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7742 // We can handle smaller integers by generating an extra trunc.
7743 if (IntBits < FloatBits)
7744 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7745
7746 return FixConv;
7747}
7748
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007749/// Fold a floating-point divide by power of two into fixed-point to
7750/// floating-point conversion.
7751static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7752 const AArch64Subtarget *Subtarget) {
7753 if (!Subtarget->hasNEON())
7754 return SDValue();
7755
7756 SDValue Op = N->getOperand(0);
7757 unsigned Opc = Op->getOpcode();
7758 if (!Op.getValueType().isVector() ||
7759 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7760 return SDValue();
7761
7762 SDValue ConstVec = N->getOperand(1);
7763 if (!isa<BuildVectorSDNode>(ConstVec))
7764 return SDValue();
7765
7766 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7767 int32_t IntBits = IntTy.getSizeInBits();
7768 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7769 return SDValue();
7770
7771 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7772 int32_t FloatBits = FloatTy.getSizeInBits();
7773 if (FloatBits != 32 && FloatBits != 64)
7774 return SDValue();
7775
7776 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7777 if (IntBits > FloatBits)
7778 return SDValue();
7779
7780 BitVector UndefElements;
7781 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7782 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7783 if (C == -1 || C == 0 || C > FloatBits)
7784 return SDValue();
7785
7786 MVT ResTy;
7787 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7788 switch (NumLanes) {
7789 default:
7790 return SDValue();
7791 case 2:
7792 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7793 break;
7794 case 4:
7795 ResTy = MVT::v4i32;
7796 break;
7797 }
7798
7799 SDLoc DL(N);
7800 SDValue ConvInput = Op.getOperand(0);
7801 bool IsSigned = Opc == ISD::SINT_TO_FP;
7802 if (IntBits < FloatBits)
7803 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7804 ResTy, ConvInput);
7805
7806 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7807 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7808 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7809 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7810 DAG.getConstant(C, DL, MVT::i32));
7811}
7812
Tim Northover3b0846e2014-05-24 12:50:23 +00007813/// An EXTR instruction is made up of two shifts, ORed together. This helper
7814/// searches for and classifies those shifts.
7815static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7816 bool &FromHi) {
7817 if (N.getOpcode() == ISD::SHL)
7818 FromHi = false;
7819 else if (N.getOpcode() == ISD::SRL)
7820 FromHi = true;
7821 else
7822 return false;
7823
7824 if (!isa<ConstantSDNode>(N.getOperand(1)))
7825 return false;
7826
7827 ShiftAmount = N->getConstantOperandVal(1);
7828 Src = N->getOperand(0);
7829 return true;
7830}
7831
7832/// EXTR instruction extracts a contiguous chunk of bits from two existing
7833/// registers viewed as a high/low pair. This function looks for the pattern:
7834/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7835/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7836/// independent.
7837static SDValue tryCombineToEXTR(SDNode *N,
7838 TargetLowering::DAGCombinerInfo &DCI) {
7839 SelectionDAG &DAG = DCI.DAG;
7840 SDLoc DL(N);
7841 EVT VT = N->getValueType(0);
7842
7843 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7844
7845 if (VT != MVT::i32 && VT != MVT::i64)
7846 return SDValue();
7847
7848 SDValue LHS;
7849 uint32_t ShiftLHS = 0;
7850 bool LHSFromHi = 0;
7851 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7852 return SDValue();
7853
7854 SDValue RHS;
7855 uint32_t ShiftRHS = 0;
7856 bool RHSFromHi = 0;
7857 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7858 return SDValue();
7859
7860 // If they're both trying to come from the high part of the register, they're
7861 // not really an EXTR.
7862 if (LHSFromHi == RHSFromHi)
7863 return SDValue();
7864
7865 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7866 return SDValue();
7867
7868 if (LHSFromHi) {
7869 std::swap(LHS, RHS);
7870 std::swap(ShiftLHS, ShiftRHS);
7871 }
7872
7873 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007874 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007875}
7876
7877static SDValue tryCombineToBSL(SDNode *N,
7878 TargetLowering::DAGCombinerInfo &DCI) {
7879 EVT VT = N->getValueType(0);
7880 SelectionDAG &DAG = DCI.DAG;
7881 SDLoc DL(N);
7882
7883 if (!VT.isVector())
7884 return SDValue();
7885
7886 SDValue N0 = N->getOperand(0);
7887 if (N0.getOpcode() != ISD::AND)
7888 return SDValue();
7889
7890 SDValue N1 = N->getOperand(1);
7891 if (N1.getOpcode() != ISD::AND)
7892 return SDValue();
7893
7894 // We only have to look for constant vectors here since the general, variable
7895 // case can be handled in TableGen.
7896 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7897 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7898 for (int i = 1; i >= 0; --i)
7899 for (int j = 1; j >= 0; --j) {
7900 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7901 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7902 if (!BVN0 || !BVN1)
7903 continue;
7904
7905 bool FoundMatch = true;
7906 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7907 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7908 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7909 if (!CN0 || !CN1 ||
7910 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7911 FoundMatch = false;
7912 break;
7913 }
7914 }
7915
7916 if (FoundMatch)
7917 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7918 N0->getOperand(1 - i), N1->getOperand(1 - j));
7919 }
7920
7921 return SDValue();
7922}
7923
7924static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7925 const AArch64Subtarget *Subtarget) {
7926 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00007927 SelectionDAG &DAG = DCI.DAG;
7928 EVT VT = N->getValueType(0);
7929
7930 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7931 return SDValue();
7932
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007933 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007934 return Res;
7935
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007936 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007937 return Res;
7938
7939 return SDValue();
7940}
7941
Chad Rosier14aa2ad2016-05-26 19:41:33 +00007942static SDValue performSRLCombine(SDNode *N,
7943 TargetLowering::DAGCombinerInfo &DCI) {
7944 SelectionDAG &DAG = DCI.DAG;
7945 EVT VT = N->getValueType(0);
7946 if (VT != MVT::i32 && VT != MVT::i64)
7947 return SDValue();
7948
7949 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
7950 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
7951 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
7952 SDValue N0 = N->getOperand(0);
7953 if (N0.getOpcode() == ISD::BSWAP) {
7954 SDLoc DL(N);
7955 SDValue N1 = N->getOperand(1);
7956 SDValue N00 = N0.getOperand(0);
7957 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
7958 uint64_t ShiftAmt = C->getZExtValue();
7959 if (VT == MVT::i32 && ShiftAmt == 16 &&
7960 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
7961 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7962 if (VT == MVT::i64 && ShiftAmt == 32 &&
7963 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
7964 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7965 }
7966 }
7967 return SDValue();
7968}
7969
Tim Northover3b0846e2014-05-24 12:50:23 +00007970static SDValue performBitcastCombine(SDNode *N,
7971 TargetLowering::DAGCombinerInfo &DCI,
7972 SelectionDAG &DAG) {
7973 // Wait 'til after everything is legalized to try this. That way we have
7974 // legal vector types and such.
7975 if (DCI.isBeforeLegalizeOps())
7976 return SDValue();
7977
7978 // Remove extraneous bitcasts around an extract_subvector.
7979 // For example,
7980 // (v4i16 (bitconvert
7981 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7982 // becomes
7983 // (extract_subvector ((v8i16 ...), (i64 4)))
7984
7985 // Only interested in 64-bit vectors as the ultimate result.
7986 EVT VT = N->getValueType(0);
7987 if (!VT.isVector())
7988 return SDValue();
7989 if (VT.getSimpleVT().getSizeInBits() != 64)
7990 return SDValue();
7991 // Is the operand an extract_subvector starting at the beginning or halfway
7992 // point of the vector? A low half may also come through as an
7993 // EXTRACT_SUBREG, so look for that, too.
7994 SDValue Op0 = N->getOperand(0);
7995 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7996 !(Op0->isMachineOpcode() &&
7997 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7998 return SDValue();
7999 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8000 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8001 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8002 return SDValue();
8003 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8004 if (idx != AArch64::dsub)
8005 return SDValue();
8006 // The dsub reference is equivalent to a lane zero subvector reference.
8007 idx = 0;
8008 }
8009 // Look through the bitcast of the input to the extract.
8010 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8011 return SDValue();
8012 SDValue Source = Op0->getOperand(0)->getOperand(0);
8013 // If the source type has twice the number of elements as our destination
8014 // type, we know this is an extract of the high or low half of the vector.
8015 EVT SVT = Source->getValueType(0);
8016 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8017 return SDValue();
8018
8019 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8020
8021 // Create the simplified form to just extract the low or high half of the
8022 // vector directly rather than bothering with the bitcasts.
8023 SDLoc dl(N);
8024 unsigned NumElements = VT.getVectorNumElements();
8025 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008026 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008027 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8028 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008029 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008030 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8031 Source, SubReg),
8032 0);
8033 }
8034}
8035
8036static SDValue performConcatVectorsCombine(SDNode *N,
8037 TargetLowering::DAGCombinerInfo &DCI,
8038 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008039 SDLoc dl(N);
8040 EVT VT = N->getValueType(0);
8041 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8042
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008043 // Optimize concat_vectors of truncated vectors, where the intermediate
8044 // type is illegal, to avoid said illegality, e.g.,
8045 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8046 // (v2i16 (truncate (v2i64)))))
8047 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008048 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8049 // (v4i32 (bitcast (v2i64))),
8050 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008051 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8052 // on both input and result type, so we might generate worse code.
8053 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8054 if (N->getNumOperands() == 2 &&
8055 N0->getOpcode() == ISD::TRUNCATE &&
8056 N1->getOpcode() == ISD::TRUNCATE) {
8057 SDValue N00 = N0->getOperand(0);
8058 SDValue N10 = N1->getOperand(0);
8059 EVT N00VT = N00.getValueType();
8060
8061 if (N00VT == N10.getValueType() &&
8062 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8063 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008064 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8065 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8066 for (size_t i = 0; i < Mask.size(); ++i)
8067 Mask[i] = i * 2;
8068 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8069 DAG.getVectorShuffle(
8070 MidVT, dl,
8071 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8072 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008073 }
8074 }
8075
Tim Northover3b0846e2014-05-24 12:50:23 +00008076 // Wait 'til after everything is legalized to try this. That way we have
8077 // legal vector types and such.
8078 if (DCI.isBeforeLegalizeOps())
8079 return SDValue();
8080
Tim Northover3b0846e2014-05-24 12:50:23 +00008081 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8082 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8083 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008084 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008085 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008086 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008087 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008088 }
8089
8090 // Canonicalise concat_vectors so that the right-hand vector has as few
8091 // bit-casts as possible before its real operation. The primary matching
8092 // destination for these operations will be the narrowing "2" instructions,
8093 // which depend on the operation being performed on this right-hand vector.
8094 // For example,
8095 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8096 // becomes
8097 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8098
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008099 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008100 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008101 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008102 MVT RHSTy = RHS.getValueType().getSimpleVT();
8103 // If the RHS is not a vector, this is not the pattern we're looking for.
8104 if (!RHSTy.isVector())
8105 return SDValue();
8106
8107 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8108
8109 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8110 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008111 return DAG.getNode(ISD::BITCAST, dl, VT,
8112 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8113 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8114 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008115}
8116
8117static SDValue tryCombineFixedPointConvert(SDNode *N,
8118 TargetLowering::DAGCombinerInfo &DCI,
8119 SelectionDAG &DAG) {
8120 // Wait 'til after everything is legalized to try this. That way we have
8121 // legal vector types and such.
8122 if (DCI.isBeforeLegalizeOps())
8123 return SDValue();
8124 // Transform a scalar conversion of a value from a lane extract into a
8125 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8126 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8127 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8128 //
8129 // The second form interacts better with instruction selection and the
8130 // register allocator to avoid cross-class register copies that aren't
8131 // coalescable due to a lane reference.
8132
8133 // Check the operand and see if it originates from a lane extract.
8134 SDValue Op1 = N->getOperand(1);
8135 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8136 // Yep, no additional predication needed. Perform the transform.
8137 SDValue IID = N->getOperand(0);
8138 SDValue Shift = N->getOperand(2);
8139 SDValue Vec = Op1.getOperand(0);
8140 SDValue Lane = Op1.getOperand(1);
8141 EVT ResTy = N->getValueType(0);
8142 EVT VecResTy;
8143 SDLoc DL(N);
8144
8145 // The vector width should be 128 bits by the time we get here, even
8146 // if it started as 64 bits (the extract_vector handling will have
8147 // done so).
8148 assert(Vec.getValueType().getSizeInBits() == 128 &&
8149 "unexpected vector size on extract_vector_elt!");
8150 if (Vec.getValueType() == MVT::v4i32)
8151 VecResTy = MVT::v4f32;
8152 else if (Vec.getValueType() == MVT::v2i64)
8153 VecResTy = MVT::v2f64;
8154 else
Craig Topper2a30d782014-06-18 05:05:13 +00008155 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008156
8157 SDValue Convert =
8158 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8159 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8160 }
8161 return SDValue();
8162}
8163
8164// AArch64 high-vector "long" operations are formed by performing the non-high
8165// version on an extract_subvector of each operand which gets the high half:
8166//
8167// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8168//
8169// However, there are cases which don't have an extract_high explicitly, but
8170// have another operation that can be made compatible with one for free. For
8171// example:
8172//
8173// (dupv64 scalar) --> (extract_high (dup128 scalar))
8174//
8175// This routine does the actual conversion of such DUPs, once outer routines
8176// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008177// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8178// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008179static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008180 switch (N.getOpcode()) {
8181 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008182 case AArch64ISD::DUPLANE8:
8183 case AArch64ISD::DUPLANE16:
8184 case AArch64ISD::DUPLANE32:
8185 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008186 case AArch64ISD::MOVI:
8187 case AArch64ISD::MOVIshift:
8188 case AArch64ISD::MOVIedit:
8189 case AArch64ISD::MOVImsl:
8190 case AArch64ISD::MVNIshift:
8191 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008192 break;
8193 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008194 // FMOV could be supported, but isn't very useful, as it would only occur
8195 // if you passed a bitcast' floating point immediate to an eligible long
8196 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008197 return SDValue();
8198 }
8199
8200 MVT NarrowTy = N.getSimpleValueType();
8201 if (!NarrowTy.is64BitVector())
8202 return SDValue();
8203
8204 MVT ElementTy = NarrowTy.getVectorElementType();
8205 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008206 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008207
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008208 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008209 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8210 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008211 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008212}
8213
8214static bool isEssentiallyExtractSubvector(SDValue N) {
8215 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8216 return true;
8217
8218 return N.getOpcode() == ISD::BITCAST &&
8219 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8220}
8221
8222/// \brief Helper structure to keep track of ISD::SET_CC operands.
8223struct GenericSetCCInfo {
8224 const SDValue *Opnd0;
8225 const SDValue *Opnd1;
8226 ISD::CondCode CC;
8227};
8228
8229/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8230struct AArch64SetCCInfo {
8231 const SDValue *Cmp;
8232 AArch64CC::CondCode CC;
8233};
8234
8235/// \brief Helper structure to keep track of SetCC information.
8236union SetCCInfo {
8237 GenericSetCCInfo Generic;
8238 AArch64SetCCInfo AArch64;
8239};
8240
8241/// \brief Helper structure to be able to read SetCC information. If set to
8242/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8243/// GenericSetCCInfo.
8244struct SetCCInfoAndKind {
8245 SetCCInfo Info;
8246 bool IsAArch64;
8247};
8248
8249/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8250/// an
8251/// AArch64 lowered one.
8252/// \p SetCCInfo is filled accordingly.
8253/// \post SetCCInfo is meanginfull only when this function returns true.
8254/// \return True when Op is a kind of SET_CC operation.
8255static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8256 // If this is a setcc, this is straight forward.
8257 if (Op.getOpcode() == ISD::SETCC) {
8258 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8259 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8260 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8261 SetCCInfo.IsAArch64 = false;
8262 return true;
8263 }
8264 // Otherwise, check if this is a matching csel instruction.
8265 // In other words:
8266 // - csel 1, 0, cc
8267 // - csel 0, 1, !cc
8268 if (Op.getOpcode() != AArch64ISD::CSEL)
8269 return false;
8270 // Set the information about the operands.
8271 // TODO: we want the operands of the Cmp not the csel
8272 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8273 SetCCInfo.IsAArch64 = true;
8274 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8275 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8276
8277 // Check that the operands matches the constraints:
8278 // (1) Both operands must be constants.
8279 // (2) One must be 1 and the other must be 0.
8280 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8281 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8282
8283 // Check (1).
8284 if (!TValue || !FValue)
8285 return false;
8286
8287 // Check (2).
8288 if (!TValue->isOne()) {
8289 // Update the comparison when we are interested in !cc.
8290 std::swap(TValue, FValue);
8291 SetCCInfo.Info.AArch64.CC =
8292 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8293 }
8294 return TValue->isOne() && FValue->isNullValue();
8295}
8296
8297// Returns true if Op is setcc or zext of setcc.
8298static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8299 if (isSetCC(Op, Info))
8300 return true;
8301 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8302 isSetCC(Op->getOperand(0), Info));
8303}
8304
8305// The folding we want to perform is:
8306// (add x, [zext] (setcc cc ...) )
8307// -->
8308// (csel x, (add x, 1), !cc ...)
8309//
8310// The latter will get matched to a CSINC instruction.
8311static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8312 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8313 SDValue LHS = Op->getOperand(0);
8314 SDValue RHS = Op->getOperand(1);
8315 SetCCInfoAndKind InfoAndKind;
8316
8317 // If neither operand is a SET_CC, give up.
8318 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8319 std::swap(LHS, RHS);
8320 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8321 return SDValue();
8322 }
8323
8324 // FIXME: This could be generatized to work for FP comparisons.
8325 EVT CmpVT = InfoAndKind.IsAArch64
8326 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8327 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8328 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8329 return SDValue();
8330
8331 SDValue CCVal;
8332 SDValue Cmp;
8333 SDLoc dl(Op);
8334 if (InfoAndKind.IsAArch64) {
8335 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008336 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8337 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008338 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8339 } else
8340 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8341 *InfoAndKind.Info.Generic.Opnd1,
8342 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8343 CCVal, DAG, dl);
8344
8345 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008346 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008347 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8348}
8349
8350// The basic add/sub long vector instructions have variants with "2" on the end
8351// which act on the high-half of their inputs. They are normally matched by
8352// patterns like:
8353//
8354// (add (zeroext (extract_high LHS)),
8355// (zeroext (extract_high RHS)))
8356// -> uaddl2 vD, vN, vM
8357//
8358// However, if one of the extracts is something like a duplicate, this
8359// instruction can still be used profitably. This function puts the DAG into a
8360// more appropriate form for those patterns to trigger.
8361static SDValue performAddSubLongCombine(SDNode *N,
8362 TargetLowering::DAGCombinerInfo &DCI,
8363 SelectionDAG &DAG) {
8364 if (DCI.isBeforeLegalizeOps())
8365 return SDValue();
8366
8367 MVT VT = N->getSimpleValueType(0);
8368 if (!VT.is128BitVector()) {
8369 if (N->getOpcode() == ISD::ADD)
8370 return performSetccAddFolding(N, DAG);
8371 return SDValue();
8372 }
8373
8374 // Make sure both branches are extended in the same way.
8375 SDValue LHS = N->getOperand(0);
8376 SDValue RHS = N->getOperand(1);
8377 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8378 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8379 LHS.getOpcode() != RHS.getOpcode())
8380 return SDValue();
8381
8382 unsigned ExtType = LHS.getOpcode();
8383
8384 // It's not worth doing if at least one of the inputs isn't already an
8385 // extract, but we don't know which it'll be so we have to try both.
8386 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8387 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8388 if (!RHS.getNode())
8389 return SDValue();
8390
8391 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8392 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8393 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8394 if (!LHS.getNode())
8395 return SDValue();
8396
8397 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8398 }
8399
8400 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8401}
8402
8403// Massage DAGs which we can use the high-half "long" operations on into
8404// something isel will recognize better. E.g.
8405//
8406// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8407// (aarch64_neon_umull (extract_high (v2i64 vec)))
8408// (extract_high (v2i64 (dup128 scalar)))))
8409//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008410static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008411 TargetLowering::DAGCombinerInfo &DCI,
8412 SelectionDAG &DAG) {
8413 if (DCI.isBeforeLegalizeOps())
8414 return SDValue();
8415
Hal Finkelcd8664c2015-12-11 23:11:52 +00008416 SDValue LHS = N->getOperand(1);
8417 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008418 assert(LHS.getValueType().is64BitVector() &&
8419 RHS.getValueType().is64BitVector() &&
8420 "unexpected shape for long operation");
8421
8422 // Either node could be a DUP, but it's not worth doing both of them (you'd
8423 // just as well use the non-high version) so look for a corresponding extract
8424 // operation on the other "wing".
8425 if (isEssentiallyExtractSubvector(LHS)) {
8426 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8427 if (!RHS.getNode())
8428 return SDValue();
8429 } else if (isEssentiallyExtractSubvector(RHS)) {
8430 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8431 if (!LHS.getNode())
8432 return SDValue();
8433 }
8434
Hal Finkelcd8664c2015-12-11 23:11:52 +00008435 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8436 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008437}
8438
8439static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8440 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8441 unsigned ElemBits = ElemTy.getSizeInBits();
8442
8443 int64_t ShiftAmount;
8444 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8445 APInt SplatValue, SplatUndef;
8446 unsigned SplatBitSize;
8447 bool HasAnyUndefs;
8448 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8449 HasAnyUndefs, ElemBits) ||
8450 SplatBitSize != ElemBits)
8451 return SDValue();
8452
8453 ShiftAmount = SplatValue.getSExtValue();
8454 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8455 ShiftAmount = CVN->getSExtValue();
8456 } else
8457 return SDValue();
8458
8459 unsigned Opcode;
8460 bool IsRightShift;
8461 switch (IID) {
8462 default:
8463 llvm_unreachable("Unknown shift intrinsic");
8464 case Intrinsic::aarch64_neon_sqshl:
8465 Opcode = AArch64ISD::SQSHL_I;
8466 IsRightShift = false;
8467 break;
8468 case Intrinsic::aarch64_neon_uqshl:
8469 Opcode = AArch64ISD::UQSHL_I;
8470 IsRightShift = false;
8471 break;
8472 case Intrinsic::aarch64_neon_srshl:
8473 Opcode = AArch64ISD::SRSHR_I;
8474 IsRightShift = true;
8475 break;
8476 case Intrinsic::aarch64_neon_urshl:
8477 Opcode = AArch64ISD::URSHR_I;
8478 IsRightShift = true;
8479 break;
8480 case Intrinsic::aarch64_neon_sqshlu:
8481 Opcode = AArch64ISD::SQSHLU_I;
8482 IsRightShift = false;
8483 break;
8484 }
8485
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008486 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8487 SDLoc dl(N);
8488 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8489 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8490 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8491 SDLoc dl(N);
8492 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8493 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8494 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008495
8496 return SDValue();
8497}
8498
8499// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8500// the intrinsics must be legal and take an i32, this means there's almost
8501// certainly going to be a zext in the DAG which we can eliminate.
8502static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8503 SDValue AndN = N->getOperand(2);
8504 if (AndN.getOpcode() != ISD::AND)
8505 return SDValue();
8506
8507 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8508 if (!CMask || CMask->getZExtValue() != Mask)
8509 return SDValue();
8510
8511 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8512 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8513}
8514
Ahmed Bougachafab58922015-03-10 20:45:38 +00008515static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8516 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008517 SDLoc dl(N);
8518 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8519 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008520 N->getOperand(1).getSimpleValueType(),
8521 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008522 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008523}
8524
Tim Northover3b0846e2014-05-24 12:50:23 +00008525static SDValue performIntrinsicCombine(SDNode *N,
8526 TargetLowering::DAGCombinerInfo &DCI,
8527 const AArch64Subtarget *Subtarget) {
8528 SelectionDAG &DAG = DCI.DAG;
8529 unsigned IID = getIntrinsicID(N);
8530 switch (IID) {
8531 default:
8532 break;
8533 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8534 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8535 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008536 case Intrinsic::aarch64_neon_saddv:
8537 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8538 case Intrinsic::aarch64_neon_uaddv:
8539 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8540 case Intrinsic::aarch64_neon_sminv:
8541 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8542 case Intrinsic::aarch64_neon_uminv:
8543 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8544 case Intrinsic::aarch64_neon_smaxv:
8545 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8546 case Intrinsic::aarch64_neon_umaxv:
8547 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008548 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008549 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008550 N->getOperand(1), N->getOperand(2));
8551 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008552 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008553 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008554 case Intrinsic::aarch64_neon_fmaxnm:
8555 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8556 N->getOperand(1), N->getOperand(2));
8557 case Intrinsic::aarch64_neon_fminnm:
8558 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8559 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008560 case Intrinsic::aarch64_neon_smull:
8561 case Intrinsic::aarch64_neon_umull:
8562 case Intrinsic::aarch64_neon_pmull:
8563 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008564 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008565 case Intrinsic::aarch64_neon_sqshl:
8566 case Intrinsic::aarch64_neon_uqshl:
8567 case Intrinsic::aarch64_neon_sqshlu:
8568 case Intrinsic::aarch64_neon_srshl:
8569 case Intrinsic::aarch64_neon_urshl:
8570 return tryCombineShiftImm(IID, N, DAG);
8571 case Intrinsic::aarch64_crc32b:
8572 case Intrinsic::aarch64_crc32cb:
8573 return tryCombineCRC32(0xff, N, DAG);
8574 case Intrinsic::aarch64_crc32h:
8575 case Intrinsic::aarch64_crc32ch:
8576 return tryCombineCRC32(0xffff, N, DAG);
8577 }
8578 return SDValue();
8579}
8580
8581static SDValue performExtendCombine(SDNode *N,
8582 TargetLowering::DAGCombinerInfo &DCI,
8583 SelectionDAG &DAG) {
8584 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8585 // we can convert that DUP into another extract_high (of a bigger DUP), which
8586 // helps the backend to decide that an sabdl2 would be useful, saving a real
8587 // extract_high operation.
8588 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008589 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008590 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008591 unsigned IID = getIntrinsicID(ABDNode);
8592 if (IID == Intrinsic::aarch64_neon_sabd ||
8593 IID == Intrinsic::aarch64_neon_uabd) {
8594 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8595 if (!NewABD.getNode())
8596 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008597
Hal Finkelcd8664c2015-12-11 23:11:52 +00008598 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8599 NewABD);
8600 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008601 }
8602
8603 // This is effectively a custom type legalization for AArch64.
8604 //
8605 // Type legalization will split an extend of a small, legal, type to a larger
8606 // illegal type by first splitting the destination type, often creating
8607 // illegal source types, which then get legalized in isel-confusing ways,
8608 // leading to really terrible codegen. E.g.,
8609 // %result = v8i32 sext v8i8 %value
8610 // becomes
8611 // %losrc = extract_subreg %value, ...
8612 // %hisrc = extract_subreg %value, ...
8613 // %lo = v4i32 sext v4i8 %losrc
8614 // %hi = v4i32 sext v4i8 %hisrc
8615 // Things go rapidly downhill from there.
8616 //
8617 // For AArch64, the [sz]ext vector instructions can only go up one element
8618 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8619 // take two instructions.
8620 //
8621 // This implies that the most efficient way to do the extend from v8i8
8622 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8623 // the normal splitting to happen for the v8i16->v8i32.
8624
8625 // This is pre-legalization to catch some cases where the default
8626 // type legalization will create ill-tempered code.
8627 if (!DCI.isBeforeLegalizeOps())
8628 return SDValue();
8629
8630 // We're only interested in cleaning things up for non-legal vector types
8631 // here. If both the source and destination are legal, things will just
8632 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008633 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008634 EVT ResVT = N->getValueType(0);
8635 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8636 return SDValue();
8637 // If the vector type isn't a simple VT, it's beyond the scope of what
8638 // we're worried about here. Let legalization do its thing and hope for
8639 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008640 SDValue Src = N->getOperand(0);
8641 EVT SrcVT = Src->getValueType(0);
8642 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008643 return SDValue();
8644
Tim Northover3b0846e2014-05-24 12:50:23 +00008645 // If the source VT is a 64-bit vector, we can play games and get the
8646 // better results we want.
8647 if (SrcVT.getSizeInBits() != 64)
8648 return SDValue();
8649
8650 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8651 unsigned ElementCount = SrcVT.getVectorNumElements();
8652 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8653 SDLoc DL(N);
8654 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8655
8656 // Now split the rest of the operation into two halves, each with a 64
8657 // bit source.
8658 EVT LoVT, HiVT;
8659 SDValue Lo, Hi;
8660 unsigned NumElements = ResVT.getVectorNumElements();
8661 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8662 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8663 ResVT.getVectorElementType(), NumElements / 2);
8664
8665 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8666 LoVT.getVectorNumElements());
8667 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008668 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008669 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008670 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008671 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8672 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8673
8674 // Now combine the parts back together so we still have a single result
8675 // like the combiner expects.
8676 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8677}
8678
8679/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8680/// value. The load store optimizer pass will merge them to store pair stores.
8681/// This has better performance than a splat of the scalar followed by a split
8682/// vector store. Even if the stores are not merged it is four stores vs a dup,
8683/// followed by an ext.b and two stores.
8684static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8685 SDValue StVal = St->getValue();
8686 EVT VT = StVal.getValueType();
8687
8688 // Don't replace floating point stores, they possibly won't be transformed to
8689 // stp because of the store pair suppress pass.
8690 if (VT.isFloatingPoint())
8691 return SDValue();
8692
8693 // Check for insert vector elements.
8694 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8695 return SDValue();
8696
8697 // We can express a splat as store pair(s) for 2 or 4 elements.
8698 unsigned NumVecElts = VT.getVectorNumElements();
8699 if (NumVecElts != 4 && NumVecElts != 2)
8700 return SDValue();
8701 SDValue SplatVal = StVal.getOperand(1);
8702 unsigned RemainInsertElts = NumVecElts - 1;
8703
8704 // Check that this is a splat.
8705 while (--RemainInsertElts) {
8706 SDValue NextInsertElt = StVal.getOperand(0);
8707 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8708 return SDValue();
8709 if (NextInsertElt.getOperand(1) != SplatVal)
8710 return SDValue();
8711 StVal = NextInsertElt;
8712 }
8713 unsigned OrigAlignment = St->getAlignment();
8714 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8715 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8716
8717 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008718 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008719 // Most of the time the three stores should be replaced by store pair
8720 // instructions (stp).
8721 SDLoc DL(St);
8722 SDValue BasePtr = St->getBasePtr();
8723 SDValue NewST1 =
8724 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00008725 St->getAlignment(), St->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008726
8727 unsigned Offset = EltOffset;
8728 while (--NumVecElts) {
8729 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008730 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008731 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00008732 St->getPointerInfo(), Alignment,
8733 St->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008734 Offset += EltOffset;
8735 }
8736 return NewST1;
8737}
8738
Tim Northover339c83e2015-11-10 00:44:23 +00008739static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8740 SelectionDAG &DAG,
8741 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008742 if (!DCI.isBeforeLegalize())
8743 return SDValue();
8744
8745 StoreSDNode *S = cast<StoreSDNode>(N);
8746 if (S->isVolatile())
8747 return SDValue();
8748
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008749 // FIXME: The logic for deciding if an unaligned store should be split should
8750 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8751 // a call to that function here.
8752
Matthias Braun651cff42016-06-02 18:03:53 +00008753 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00008754 return SDValue();
8755
Sanjay Patel924879a2015-08-04 15:49:57 +00008756 // Don't split at -Oz.
8757 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008758 return SDValue();
8759
8760 SDValue StVal = S->getValue();
8761 EVT VT = StVal.getValueType();
8762
8763 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8764 // those up regresses performance on micro-benchmarks and olden/bh.
8765 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8766 return SDValue();
8767
8768 // Split unaligned 16B stores. They are terrible for performance.
8769 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8770 // extensions can use this to mark that it does not want splitting to happen
8771 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8772 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8773 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8774 S->getAlignment() <= 2)
8775 return SDValue();
8776
8777 // If we get a splat of a scalar convert this vector store to a store of
8778 // scalars. They will be merged into store pairs thereby removing two
8779 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008780 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008781 return ReplacedSplat;
8782
8783 SDLoc DL(S);
8784 unsigned NumElts = VT.getVectorNumElements() / 2;
8785 // Split VT into two.
8786 EVT HalfVT =
8787 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8788 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008789 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008790 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008791 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008792 SDValue BasePtr = S->getBasePtr();
8793 SDValue NewST1 =
8794 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00008795 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008796 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008797 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008798 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00008799 S->getPointerInfo(), S->getAlignment(),
8800 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008801}
8802
8803/// Target-specific DAG combine function for post-increment LD1 (lane) and
8804/// post-increment LD1R.
8805static SDValue performPostLD1Combine(SDNode *N,
8806 TargetLowering::DAGCombinerInfo &DCI,
8807 bool IsLaneOp) {
8808 if (DCI.isBeforeLegalizeOps())
8809 return SDValue();
8810
8811 SelectionDAG &DAG = DCI.DAG;
8812 EVT VT = N->getValueType(0);
8813
8814 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8815 SDNode *LD = N->getOperand(LoadIdx).getNode();
8816 // If it is not LOAD, can not do such combine.
8817 if (LD->getOpcode() != ISD::LOAD)
8818 return SDValue();
8819
8820 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8821 EVT MemVT = LoadSDN->getMemoryVT();
8822 // Check if memory operand is the same type as the vector element.
8823 if (MemVT != VT.getVectorElementType())
8824 return SDValue();
8825
8826 // Check if there are other uses. If so, do not combine as it will introduce
8827 // an extra load.
8828 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8829 ++UI) {
8830 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8831 continue;
8832 if (*UI != N)
8833 return SDValue();
8834 }
8835
8836 SDValue Addr = LD->getOperand(1);
8837 SDValue Vector = N->getOperand(0);
8838 // Search for a use of the address operand that is an increment.
8839 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8840 Addr.getNode()->use_end(); UI != UE; ++UI) {
8841 SDNode *User = *UI;
8842 if (User->getOpcode() != ISD::ADD
8843 || UI.getUse().getResNo() != Addr.getResNo())
8844 continue;
8845
8846 // Check that the add is independent of the load. Otherwise, folding it
8847 // would create a cycle.
8848 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8849 continue;
8850 // Also check that add is not used in the vector operand. This would also
8851 // create a cycle.
8852 if (User->isPredecessorOf(Vector.getNode()))
8853 continue;
8854
8855 // If the increment is a constant, it must match the memory ref size.
8856 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8857 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8858 uint32_t IncVal = CInc->getZExtValue();
8859 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8860 if (IncVal != NumBytes)
8861 continue;
8862 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8863 }
8864
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008865 // Finally, check that the vector doesn't depend on the load.
8866 // Again, this would create a cycle.
8867 // The load depending on the vector is fine, as that's the case for the
8868 // LD1*post we'll eventually generate anyway.
8869 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8870 continue;
8871
Tim Northover3b0846e2014-05-24 12:50:23 +00008872 SmallVector<SDValue, 8> Ops;
8873 Ops.push_back(LD->getOperand(0)); // Chain
8874 if (IsLaneOp) {
8875 Ops.push_back(Vector); // The vector to be inserted
8876 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8877 }
8878 Ops.push_back(Addr);
8879 Ops.push_back(Inc);
8880
8881 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008882 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008883 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8884 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8885 MemVT,
8886 LoadSDN->getMemOperand());
8887
8888 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00008889 SDValue NewResults[] = {
8890 SDValue(LD, 0), // The result of load
8891 SDValue(UpdN.getNode(), 2) // Chain
8892 };
Tim Northover3b0846e2014-05-24 12:50:23 +00008893 DCI.CombineTo(LD, NewResults);
8894 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8895 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8896
8897 break;
8898 }
8899 return SDValue();
8900}
8901
Tim Northover339c83e2015-11-10 00:44:23 +00008902/// Simplify \Addr given that the top byte of it is ignored by HW during
8903/// address translation.
8904static bool performTBISimplification(SDValue Addr,
8905 TargetLowering::DAGCombinerInfo &DCI,
8906 SelectionDAG &DAG) {
8907 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8908 APInt KnownZero, KnownOne;
8909 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8910 DCI.isBeforeLegalizeOps());
8911 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8912 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8913 DCI.CommitTargetLoweringOpt(TLO);
8914 return true;
8915 }
8916 return false;
8917}
8918
8919static SDValue performSTORECombine(SDNode *N,
8920 TargetLowering::DAGCombinerInfo &DCI,
8921 SelectionDAG &DAG,
8922 const AArch64Subtarget *Subtarget) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008923 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00008924 return Split;
8925
8926 if (Subtarget->supportsAddressTopByteIgnored() &&
8927 performTBISimplification(N->getOperand(2), DCI, DAG))
8928 return SDValue(N, 0);
8929
8930 return SDValue();
8931}
8932
8933 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008934/// LoopVectorizer for the across vector reduction. It consists of
8935/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8936/// are reduced, where s is an induction variable from 0 to
8937/// log2(NumVectorElements).
8938static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8939 unsigned Op,
8940 SelectionDAG &DAG) {
8941 EVT VTy = OpV->getOperand(0).getValueType();
8942 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008943 return SDValue();
8944
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008945 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008946 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8947 if (NumVecElts != 4)
8948 return SDValue();
8949 } else {
8950 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8951 return SDValue();
8952 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008953
8954 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008955 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008956 // Iterate over each step of the across vector reduction.
8957 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008958 SDValue CurOp = PreOp.getOperand(0);
8959 SDValue Shuffle = PreOp.getOperand(1);
8960 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008961 // Try to swap the 1st and 2nd operand as add and min/max instructions
8962 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008963 CurOp = PreOp.getOperand(1);
8964 Shuffle = PreOp.getOperand(0);
8965 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8966 return SDValue();
8967 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008968
8969 // Check if the input vector is fed by the operator we want to handle,
8970 // except the last step; the very first input vector is not necessarily
8971 // the same operator we are handling.
8972 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8973 return SDValue();
8974
Chad Rosier6c36eff2015-09-03 18:13:57 +00008975 // Check if it forms one step of the across vector reduction.
8976 // E.g.,
8977 // %cur = add %1, %0
8978 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8979 // %pre = add %cur, %shuffle
8980 if (Shuffle.getOperand(0) != CurOp)
8981 return SDValue();
8982
8983 int NumMaskElts = 1 << CurStep;
8984 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8985 // Check mask values in each step.
8986 // We expect the shuffle mask in each step follows a specific pattern
8987 // denoted here by the <M, U> form, where M is a sequence of integers
8988 // starting from NumMaskElts, increasing by 1, and the number integers
8989 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8990 // of undef in U should be NumVecElts - NumMaskElts.
8991 // E.g., for <8 x i16>, mask values in each step should be :
8992 // step 0 : <1,u,u,u,u,u,u,u>
8993 // step 1 : <2,3,u,u,u,u,u,u>
8994 // step 2 : <4,5,6,7,u,u,u,u>
8995 for (int i = 0; i < NumVecElts; ++i)
8996 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8997 (i >= NumMaskElts && !(Mask[i] < 0)))
8998 return SDValue();
8999
9000 PreOp = CurOp;
9001 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009002 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009003 bool IsIntrinsic = false;
9004
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009005 switch (Op) {
9006 default:
9007 llvm_unreachable("Unexpected operator for across vector reduction");
9008 case ISD::ADD:
9009 Opcode = AArch64ISD::UADDV;
9010 break;
9011 case ISD::SMAX:
9012 Opcode = AArch64ISD::SMAXV;
9013 break;
9014 case ISD::UMAX:
9015 Opcode = AArch64ISD::UMAXV;
9016 break;
9017 case ISD::SMIN:
9018 Opcode = AArch64ISD::SMINV;
9019 break;
9020 case ISD::UMIN:
9021 Opcode = AArch64ISD::UMINV;
9022 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009023 case ISD::FMAXNUM:
9024 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9025 IsIntrinsic = true;
9026 break;
9027 case ISD::FMINNUM:
9028 Opcode = Intrinsic::aarch64_neon_fminnmv;
9029 IsIntrinsic = true;
9030 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009031 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009032 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00009033
9034 return IsIntrinsic
9035 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9036 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9037 : DAG.getNode(
9038 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9039 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9040 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009041}
9042
9043/// Target-specific DAG combine for the across vector min/max reductions.
9044/// This function specifically handles the final clean-up step of the vector
9045/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9046/// pattern, which narrows down and finds the final min/max value from all
9047/// elements of the vector.
9048/// For example, for a <16 x i8> vector :
9049/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9050/// %smax0 = smax %arr, svn0
9051/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9052/// %smax1 = smax %smax0, %svn1
9053/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9054/// %smax2 = smax %smax1, svn2
9055/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9056/// %sc = setcc %smax2, %svn3, gt
9057/// %n0 = extract_vector_elt %sc, #0
9058/// %n1 = extract_vector_elt %smax2, #0
9059/// %n2 = extract_vector_elt $smax2, #1
9060/// %result = select %n0, %n1, n2
9061/// becomes :
9062/// %1 = smaxv %0
9063/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009064static SDValue
9065performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9066 const AArch64Subtarget *Subtarget) {
9067 if (!Subtarget->hasNEON())
9068 return SDValue();
9069
9070 SDValue N0 = N->getOperand(0);
9071 SDValue IfTrue = N->getOperand(1);
9072 SDValue IfFalse = N->getOperand(2);
9073
9074 // Check if the SELECT merges up the final result of the min/max
9075 // from a vector.
9076 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9077 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9078 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9079 return SDValue();
9080
9081 // Expect N0 is fed by SETCC.
9082 SDValue SetCC = N0.getOperand(0);
9083 EVT SetCCVT = SetCC.getValueType();
9084 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9085 SetCCVT.getVectorElementType() != MVT::i1)
9086 return SDValue();
9087
9088 SDValue VectorOp = SetCC.getOperand(0);
9089 unsigned Op = VectorOp->getOpcode();
9090 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009091 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9092 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009093 return SDValue();
9094
9095 EVT VTy = VectorOp.getValueType();
9096 if (!VTy.isVector())
9097 return SDValue();
9098
Jun Bum Lim0aace132015-10-09 14:11:25 +00009099 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009100 return SDValue();
9101
Jun Bum Lim0aace132015-10-09 14:11:25 +00009102 EVT EltTy = VTy.getVectorElementType();
9103 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9104 if (EltTy != MVT::f32)
9105 return SDValue();
9106 } else {
9107 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9108 return SDValue();
9109 }
9110
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009111 // Check if extracting from the same vector.
9112 // For example,
9113 // %sc = setcc %vector, %svn1, gt
9114 // %n0 = extract_vector_elt %sc, #0
9115 // %n1 = extract_vector_elt %vector, #0
9116 // %n2 = extract_vector_elt $vector, #1
9117 if (!(VectorOp == IfTrue->getOperand(0) &&
9118 VectorOp == IfFalse->getOperand(0)))
9119 return SDValue();
9120
9121 // Check if the condition code is matched with the operator type.
9122 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9123 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9124 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9125 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009126 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9127 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9128 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9129 CC != ISD::SETGE) ||
9130 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9131 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9132 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009133 return SDValue();
9134
9135 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009136 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009137 return SDValue();
9138
9139 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009140 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009141 return SDValue();
9142
9143 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009144 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009145 return SDValue();
9146
9147 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9148}
9149
9150/// Target-specific DAG combine for the across vector add reduction.
9151/// This function specifically handles the final clean-up step of the vector
9152/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9153/// pattern, which adds all elements of a vector together.
9154/// For example, for a <4 x i32> vector :
9155/// %1 = vector_shuffle %0, <2,3,u,u>
9156/// %2 = add %0, %1
9157/// %3 = vector_shuffle %2, <1,u,u,u>
9158/// %4 = add %2, %3
9159/// %result = extract_vector_elt %4, 0
9160/// becomes :
9161/// %0 = uaddv %0
9162/// %result = extract_vector_elt %0, 0
9163static SDValue
9164performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9165 const AArch64Subtarget *Subtarget) {
9166 if (!Subtarget->hasNEON())
9167 return SDValue();
9168 SDValue N0 = N->getOperand(0);
9169 SDValue N1 = N->getOperand(1);
9170
9171 // Check if the input vector is fed by the ADD.
9172 if (N0->getOpcode() != ISD::ADD)
9173 return SDValue();
9174
9175 // The vector extract idx must constant zero because we only expect the final
9176 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009177 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009178 return SDValue();
9179
9180 EVT VTy = N0.getValueType();
9181 if (!VTy.isVector())
9182 return SDValue();
9183
9184 EVT EltTy = VTy.getVectorElementType();
9185 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9186 return SDValue();
9187
Jun Bum Lim0aace132015-10-09 14:11:25 +00009188 if (VTy.getSizeInBits() < 64)
9189 return SDValue();
9190
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009191 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009192}
9193
Tim Northover3b0846e2014-05-24 12:50:23 +00009194/// Target-specific DAG combine function for NEON load/store intrinsics
9195/// to merge base address updates.
9196static SDValue performNEONPostLDSTCombine(SDNode *N,
9197 TargetLowering::DAGCombinerInfo &DCI,
9198 SelectionDAG &DAG) {
9199 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9200 return SDValue();
9201
9202 unsigned AddrOpIdx = N->getNumOperands() - 1;
9203 SDValue Addr = N->getOperand(AddrOpIdx);
9204
9205 // Search for a use of the address operand that is an increment.
9206 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9207 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9208 SDNode *User = *UI;
9209 if (User->getOpcode() != ISD::ADD ||
9210 UI.getUse().getResNo() != Addr.getResNo())
9211 continue;
9212
9213 // Check that the add is independent of the load/store. Otherwise, folding
9214 // it would create a cycle.
9215 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9216 continue;
9217
9218 // Find the new opcode for the updating load/store.
9219 bool IsStore = false;
9220 bool IsLaneOp = false;
9221 bool IsDupOp = false;
9222 unsigned NewOpc = 0;
9223 unsigned NumVecs = 0;
9224 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9225 switch (IntNo) {
9226 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9227 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9228 NumVecs = 2; break;
9229 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9230 NumVecs = 3; break;
9231 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9232 NumVecs = 4; break;
9233 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9234 NumVecs = 2; IsStore = true; break;
9235 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9236 NumVecs = 3; IsStore = true; break;
9237 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9238 NumVecs = 4; IsStore = true; break;
9239 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9240 NumVecs = 2; break;
9241 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9242 NumVecs = 3; break;
9243 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9244 NumVecs = 4; break;
9245 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9246 NumVecs = 2; IsStore = true; break;
9247 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9248 NumVecs = 3; IsStore = true; break;
9249 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9250 NumVecs = 4; IsStore = true; break;
9251 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9252 NumVecs = 2; IsDupOp = true; break;
9253 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9254 NumVecs = 3; IsDupOp = true; break;
9255 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9256 NumVecs = 4; IsDupOp = true; break;
9257 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9258 NumVecs = 2; IsLaneOp = true; break;
9259 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9260 NumVecs = 3; IsLaneOp = true; break;
9261 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9262 NumVecs = 4; IsLaneOp = true; break;
9263 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9264 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9265 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9266 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9267 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9268 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9269 }
9270
9271 EVT VecTy;
9272 if (IsStore)
9273 VecTy = N->getOperand(2).getValueType();
9274 else
9275 VecTy = N->getValueType(0);
9276
9277 // If the increment is a constant, it must match the memory ref size.
9278 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9279 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9280 uint32_t IncVal = CInc->getZExtValue();
9281 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9282 if (IsLaneOp || IsDupOp)
9283 NumBytes /= VecTy.getVectorNumElements();
9284 if (IncVal != NumBytes)
9285 continue;
9286 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9287 }
9288 SmallVector<SDValue, 8> Ops;
9289 Ops.push_back(N->getOperand(0)); // Incoming chain
9290 // Load lane and store have vector list as input.
9291 if (IsLaneOp || IsStore)
9292 for (unsigned i = 2; i < AddrOpIdx; ++i)
9293 Ops.push_back(N->getOperand(i));
9294 Ops.push_back(Addr); // Base register
9295 Ops.push_back(Inc);
9296
9297 // Return Types.
9298 EVT Tys[6];
9299 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9300 unsigned n;
9301 for (n = 0; n < NumResultVecs; ++n)
9302 Tys[n] = VecTy;
9303 Tys[n++] = MVT::i64; // Type of write back register
9304 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009305 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009306
9307 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9308 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9309 MemInt->getMemoryVT(),
9310 MemInt->getMemOperand());
9311
9312 // Update the uses.
9313 std::vector<SDValue> NewResults;
9314 for (unsigned i = 0; i < NumResultVecs; ++i) {
9315 NewResults.push_back(SDValue(UpdN.getNode(), i));
9316 }
9317 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9318 DCI.CombineTo(N, NewResults);
9319 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9320
9321 break;
9322 }
9323 return SDValue();
9324}
9325
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009326// Checks to see if the value is the prescribed width and returns information
9327// about its extension mode.
9328static
9329bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9330 ExtType = ISD::NON_EXTLOAD;
9331 switch(V.getNode()->getOpcode()) {
9332 default:
9333 return false;
9334 case ISD::LOAD: {
9335 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9336 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9337 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9338 ExtType = LoadNode->getExtensionType();
9339 return true;
9340 }
9341 return false;
9342 }
9343 case ISD::AssertSext: {
9344 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9345 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9346 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9347 ExtType = ISD::SEXTLOAD;
9348 return true;
9349 }
9350 return false;
9351 }
9352 case ISD::AssertZext: {
9353 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9354 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9355 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9356 ExtType = ISD::ZEXTLOAD;
9357 return true;
9358 }
9359 return false;
9360 }
9361 case ISD::Constant:
9362 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009363 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9364 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009365 }
9366 }
9367
9368 return true;
9369}
9370
9371// This function does a whole lot of voodoo to determine if the tests are
9372// equivalent without and with a mask. Essentially what happens is that given a
9373// DAG resembling:
9374//
9375// +-------------+ +-------------+ +-------------+ +-------------+
9376// | Input | | AddConstant | | CompConstant| | CC |
9377// +-------------+ +-------------+ +-------------+ +-------------+
9378// | | | |
9379// V V | +----------+
9380// +-------------+ +----+ | |
9381// | ADD | |0xff| | |
9382// +-------------+ +----+ | |
9383// | | | |
9384// V V | |
9385// +-------------+ | |
9386// | AND | | |
9387// +-------------+ | |
9388// | | |
9389// +-----+ | |
9390// | | |
9391// V V V
9392// +-------------+
9393// | CMP |
9394// +-------------+
9395//
9396// The AND node may be safely removed for some combinations of inputs. In
9397// particular we need to take into account the extension type of the Input,
9398// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9399// width of the input (this can work for any width inputs, the above graph is
9400// specific to 8 bits.
9401//
9402// The specific equations were worked out by generating output tables for each
9403// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9404// problem was simplified by working with 4 bit inputs, which means we only
9405// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9406// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9407// patterns present in both extensions (0,7). For every distinct set of
9408// AddConstant and CompConstants bit patterns we can consider the masked and
9409// unmasked versions to be equivalent if the result of this function is true for
9410// all 16 distinct bit patterns of for the current extension type of Input (w0).
9411//
9412// sub w8, w0, w1
9413// and w10, w8, #0x0f
9414// cmp w8, w2
9415// cset w9, AArch64CC
9416// cmp w10, w2
9417// cset w11, AArch64CC
9418// cmp w9, w11
9419// cset w0, eq
9420// ret
9421//
9422// Since the above function shows when the outputs are equivalent it defines
9423// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9424// would be expensive to run during compiles. The equations below were written
9425// in a test harness that confirmed they gave equivalent outputs to the above
9426// for all inputs function, so they can be used determine if the removal is
9427// legal instead.
9428//
9429// isEquivalentMaskless() is the code for testing if the AND can be removed
9430// factored out of the DAG recognition as the DAG can take several forms.
9431
David Majnemere61e4bf2016-06-21 05:10:24 +00009432static bool isEquivalentMaskless(unsigned CC, unsigned width,
9433 ISD::LoadExtType ExtType, int AddConstant,
9434 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009435 // By being careful about our equations and only writing the in term
9436 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9437 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009438 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009439
9440 // For the purposes of these comparisons sign extending the type is
9441 // equivalent to zero extending the add and displacing it by half the integer
9442 // width. Provided we are careful and make sure our equations are valid over
9443 // the whole range we can just adjust the input and avoid writing equations
9444 // for sign extended inputs.
9445 if (ExtType == ISD::SEXTLOAD)
9446 AddConstant -= (1 << (width-1));
9447
9448 switch(CC) {
9449 case AArch64CC::LE:
9450 case AArch64CC::GT: {
9451 if ((AddConstant == 0) ||
9452 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9453 (AddConstant >= 0 && CompConstant < 0) ||
9454 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9455 return true;
9456 } break;
9457 case AArch64CC::LT:
9458 case AArch64CC::GE: {
9459 if ((AddConstant == 0) ||
9460 (AddConstant >= 0 && CompConstant <= 0) ||
9461 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9462 return true;
9463 } break;
9464 case AArch64CC::HI:
9465 case AArch64CC::LS: {
9466 if ((AddConstant >= 0 && CompConstant < 0) ||
9467 (AddConstant <= 0 && CompConstant >= -1 &&
9468 CompConstant < AddConstant + MaxUInt))
9469 return true;
9470 } break;
9471 case AArch64CC::PL:
9472 case AArch64CC::MI: {
9473 if ((AddConstant == 0) ||
9474 (AddConstant > 0 && CompConstant <= 0) ||
9475 (AddConstant < 0 && CompConstant <= AddConstant))
9476 return true;
9477 } break;
9478 case AArch64CC::LO:
9479 case AArch64CC::HS: {
9480 if ((AddConstant >= 0 && CompConstant <= 0) ||
9481 (AddConstant <= 0 && CompConstant >= 0 &&
9482 CompConstant <= AddConstant + MaxUInt))
9483 return true;
9484 } break;
9485 case AArch64CC::EQ:
9486 case AArch64CC::NE: {
9487 if ((AddConstant > 0 && CompConstant < 0) ||
9488 (AddConstant < 0 && CompConstant >= 0 &&
9489 CompConstant < AddConstant + MaxUInt) ||
9490 (AddConstant >= 0 && CompConstant >= 0 &&
9491 CompConstant >= AddConstant) ||
9492 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9493
9494 return true;
9495 } break;
9496 case AArch64CC::VS:
9497 case AArch64CC::VC:
9498 case AArch64CC::AL:
9499 case AArch64CC::NV:
9500 return true;
9501 case AArch64CC::Invalid:
9502 break;
9503 }
9504
9505 return false;
9506}
9507
9508static
9509SDValue performCONDCombine(SDNode *N,
9510 TargetLowering::DAGCombinerInfo &DCI,
9511 SelectionDAG &DAG, unsigned CCIndex,
9512 unsigned CmpIndex) {
9513 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9514 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9515 unsigned CondOpcode = SubsNode->getOpcode();
9516
9517 if (CondOpcode != AArch64ISD::SUBS)
9518 return SDValue();
9519
9520 // There is a SUBS feeding this condition. Is it fed by a mask we can
9521 // use?
9522
9523 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9524 unsigned MaskBits = 0;
9525
9526 if (AndNode->getOpcode() != ISD::AND)
9527 return SDValue();
9528
9529 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9530 uint32_t CNV = CN->getZExtValue();
9531 if (CNV == 255)
9532 MaskBits = 8;
9533 else if (CNV == 65535)
9534 MaskBits = 16;
9535 }
9536
9537 if (!MaskBits)
9538 return SDValue();
9539
9540 SDValue AddValue = AndNode->getOperand(0);
9541
9542 if (AddValue.getOpcode() != ISD::ADD)
9543 return SDValue();
9544
9545 // The basic dag structure is correct, grab the inputs and validate them.
9546
9547 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9548 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9549 SDValue SubsInputValue = SubsNode->getOperand(1);
9550
9551 // The mask is present and the provenance of all the values is a smaller type,
9552 // lets see if the mask is superfluous.
9553
9554 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9555 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9556 return SDValue();
9557
9558 ISD::LoadExtType ExtType;
9559
9560 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9561 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9562 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9563 return SDValue();
9564
9565 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9566 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9567 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9568 return SDValue();
9569
9570 // The AND is not necessary, remove it.
9571
9572 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9573 SubsNode->getValueType(1));
9574 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9575
9576 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9577 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9578
9579 return SDValue(N, 0);
9580}
9581
Tim Northover3b0846e2014-05-24 12:50:23 +00009582// Optimize compare with zero and branch.
9583static SDValue performBRCONDCombine(SDNode *N,
9584 TargetLowering::DAGCombinerInfo &DCI,
9585 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009586 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009587 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009588 SDValue Chain = N->getOperand(0);
9589 SDValue Dest = N->getOperand(1);
9590 SDValue CCVal = N->getOperand(2);
9591 SDValue Cmp = N->getOperand(3);
9592
9593 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9594 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9595 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9596 return SDValue();
9597
9598 unsigned CmpOpc = Cmp.getOpcode();
9599 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9600 return SDValue();
9601
9602 // Only attempt folding if there is only one use of the flag and no use of the
9603 // value.
9604 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9605 return SDValue();
9606
9607 SDValue LHS = Cmp.getOperand(0);
9608 SDValue RHS = Cmp.getOperand(1);
9609
9610 assert(LHS.getValueType() == RHS.getValueType() &&
9611 "Expected the value type to be the same for both operands!");
9612 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9613 return SDValue();
9614
Artyom Skrobov314ee042015-11-25 19:41:11 +00009615 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009616 std::swap(LHS, RHS);
9617
Artyom Skrobov314ee042015-11-25 19:41:11 +00009618 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009619 return SDValue();
9620
9621 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9622 LHS.getOpcode() == ISD::SRL)
9623 return SDValue();
9624
9625 // Fold the compare into the branch instruction.
9626 SDValue BR;
9627 if (CC == AArch64CC::EQ)
9628 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9629 else
9630 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9631
9632 // Do not add new nodes to DAG combiner worklist.
9633 DCI.CombineTo(N, BR, false);
9634
9635 return SDValue();
9636}
9637
Geoff Berry9e934b02016-01-04 18:55:47 +00009638// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9639// as well as whether the test should be inverted. This code is required to
9640// catch these cases (as opposed to standard dag combines) because
9641// AArch64ISD::TBZ is matched during legalization.
9642static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9643 SelectionDAG &DAG) {
9644
9645 if (!Op->hasOneUse())
9646 return Op;
9647
9648 // We don't handle undef/constant-fold cases below, as they should have
9649 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9650 // etc.)
9651
9652 // (tbz (trunc x), b) -> (tbz x, b)
9653 // This case is just here to enable more of the below cases to be caught.
9654 if (Op->getOpcode() == ISD::TRUNCATE &&
9655 Bit < Op->getValueType(0).getSizeInBits()) {
9656 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9657 }
9658
9659 if (Op->getNumOperands() != 2)
9660 return Op;
9661
9662 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9663 if (!C)
9664 return Op;
9665
9666 switch (Op->getOpcode()) {
9667 default:
9668 return Op;
9669
9670 // (tbz (and x, m), b) -> (tbz x, b)
9671 case ISD::AND:
9672 if ((C->getZExtValue() >> Bit) & 1)
9673 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9674 return Op;
9675
9676 // (tbz (shl x, c), b) -> (tbz x, b-c)
9677 case ISD::SHL:
9678 if (C->getZExtValue() <= Bit &&
9679 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9680 Bit = Bit - C->getZExtValue();
9681 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9682 }
9683 return Op;
9684
9685 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9686 case ISD::SRA:
9687 Bit = Bit + C->getZExtValue();
9688 if (Bit >= Op->getValueType(0).getSizeInBits())
9689 Bit = Op->getValueType(0).getSizeInBits() - 1;
9690 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9691
9692 // (tbz (srl x, c), b) -> (tbz x, b+c)
9693 case ISD::SRL:
9694 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9695 Bit = Bit + C->getZExtValue();
9696 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9697 }
9698 return Op;
9699
9700 // (tbz (xor x, -1), b) -> (tbnz x, b)
9701 case ISD::XOR:
9702 if ((C->getZExtValue() >> Bit) & 1)
9703 Invert = !Invert;
9704 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9705 }
9706}
9707
9708// Optimize test single bit zero/non-zero and branch.
9709static SDValue performTBZCombine(SDNode *N,
9710 TargetLowering::DAGCombinerInfo &DCI,
9711 SelectionDAG &DAG) {
9712 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9713 bool Invert = false;
9714 SDValue TestSrc = N->getOperand(1);
9715 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9716
9717 if (TestSrc == NewTestSrc)
9718 return SDValue();
9719
9720 unsigned NewOpc = N->getOpcode();
9721 if (Invert) {
9722 if (NewOpc == AArch64ISD::TBZ)
9723 NewOpc = AArch64ISD::TBNZ;
9724 else {
9725 assert(NewOpc == AArch64ISD::TBNZ);
9726 NewOpc = AArch64ISD::TBZ;
9727 }
9728 }
9729
9730 SDLoc DL(N);
9731 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9732 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9733}
9734
Tim Northover3b0846e2014-05-24 12:50:23 +00009735// vselect (v1i1 setcc) ->
9736// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9737// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9738// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9739// such VSELECT.
9740static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9741 SDValue N0 = N->getOperand(0);
9742 EVT CCVT = N0.getValueType();
9743
9744 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9745 CCVT.getVectorElementType() != MVT::i1)
9746 return SDValue();
9747
9748 EVT ResVT = N->getValueType(0);
9749 EVT CmpVT = N0.getOperand(0).getValueType();
9750 // Only combine when the result type is of the same size as the compared
9751 // operands.
9752 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9753 return SDValue();
9754
9755 SDValue IfTrue = N->getOperand(1);
9756 SDValue IfFalse = N->getOperand(2);
9757 SDValue SetCC =
9758 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9759 N0.getOperand(0), N0.getOperand(1),
9760 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9761 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9762 IfTrue, IfFalse);
9763}
9764
9765/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9766/// the compare-mask instructions rather than going via NZCV, even if LHS and
9767/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9768/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009769static SDValue performSelectCombine(SDNode *N,
9770 TargetLowering::DAGCombinerInfo &DCI) {
9771 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009772 SDValue N0 = N->getOperand(0);
9773 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009774
Ahmed Bougachac004c602015-04-27 21:43:12 +00009775 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009776 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009777
Ahmed Bougachac004c602015-04-27 21:43:12 +00009778 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9779 // scalar SetCCResultType. We also don't expect vectors, because we assume
9780 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9781 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9782 "Scalar-SETCC feeding SELECT has unexpected result type!");
9783
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009784 // If NumMaskElts == 0, the comparison is larger than select result. The
9785 // largest real NEON comparison is 64-bits per lane, which means the result is
9786 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009787 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009788
9789 // Don't try to do this optimization when the setcc itself has i1 operands.
9790 // There are no legal vectors of i1, so this would be pointless.
9791 if (SrcVT == MVT::i1)
9792 return SDValue();
9793
Tim Northover3c0915e2014-08-29 15:34:58 +00009794 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009795 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009796 return SDValue();
9797
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009798 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009799 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9800
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009801 // Also bail out if the vector CCVT isn't the same size as ResVT.
9802 // This can happen if the SETCC operand size doesn't divide the ResVT size
9803 // (e.g., f64 vs v3f32).
9804 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9805 return SDValue();
9806
Ahmed Bougachac004c602015-04-27 21:43:12 +00009807 // Make sure we didn't create illegal types, if we're not supposed to.
9808 assert(DCI.isBeforeLegalize() ||
9809 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9810
Tim Northover3b0846e2014-05-24 12:50:23 +00009811 // First perform a vector comparison, where lane 0 is the one we're interested
9812 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009813 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009814 SDValue LHS =
9815 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9816 SDValue RHS =
9817 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9818 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9819
9820 // Now duplicate the comparison mask we want across all other lanes.
9821 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +00009822 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009823 Mask = DAG.getNode(ISD::BITCAST, DL,
9824 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009825
9826 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9827}
9828
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009829/// Get rid of unnecessary NVCASTs (that don't change the type).
9830static SDValue performNVCASTCombine(SDNode *N) {
9831 if (N->getValueType(0) == N->getOperand(0).getValueType())
9832 return N->getOperand(0);
9833
9834 return SDValue();
9835}
9836
Tim Northover3b0846e2014-05-24 12:50:23 +00009837SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9838 DAGCombinerInfo &DCI) const {
9839 SelectionDAG &DAG = DCI.DAG;
9840 switch (N->getOpcode()) {
9841 default:
9842 break;
9843 case ISD::ADD:
9844 case ISD::SUB:
9845 return performAddSubLongCombine(N, DCI, DAG);
9846 case ISD::XOR:
9847 return performXorCombine(N, DAG, DCI, Subtarget);
9848 case ISD::MUL:
9849 return performMulCombine(N, DAG, DCI, Subtarget);
9850 case ISD::SINT_TO_FP:
9851 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009852 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009853 case ISD::FP_TO_SINT:
9854 case ISD::FP_TO_UINT:
9855 return performFpToIntCombine(N, DAG, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009856 case ISD::FDIV:
9857 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009858 case ISD::OR:
9859 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009860 case ISD::SRL:
9861 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +00009862 case ISD::INTRINSIC_WO_CHAIN:
9863 return performIntrinsicCombine(N, DCI, Subtarget);
9864 case ISD::ANY_EXTEND:
9865 case ISD::ZERO_EXTEND:
9866 case ISD::SIGN_EXTEND:
9867 return performExtendCombine(N, DCI, DAG);
9868 case ISD::BITCAST:
9869 return performBitcastCombine(N, DCI, DAG);
9870 case ISD::CONCAT_VECTORS:
9871 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009872 case ISD::SELECT: {
9873 SDValue RV = performSelectCombine(N, DCI);
9874 if (!RV.getNode())
9875 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9876 return RV;
9877 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009878 case ISD::VSELECT:
9879 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009880 case ISD::LOAD:
9881 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9882 return SDValue(N, 0);
9883 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009884 case ISD::STORE:
9885 return performSTORECombine(N, DCI, DAG, Subtarget);
9886 case AArch64ISD::BRCOND:
9887 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009888 case AArch64ISD::TBNZ:
9889 case AArch64ISD::TBZ:
9890 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009891 case AArch64ISD::CSEL:
9892 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009893 case AArch64ISD::DUP:
9894 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009895 case AArch64ISD::NVCAST:
9896 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009897 case ISD::INSERT_VECTOR_ELT:
9898 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009899 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009900 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009901 case ISD::INTRINSIC_VOID:
9902 case ISD::INTRINSIC_W_CHAIN:
9903 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9904 case Intrinsic::aarch64_neon_ld2:
9905 case Intrinsic::aarch64_neon_ld3:
9906 case Intrinsic::aarch64_neon_ld4:
9907 case Intrinsic::aarch64_neon_ld1x2:
9908 case Intrinsic::aarch64_neon_ld1x3:
9909 case Intrinsic::aarch64_neon_ld1x4:
9910 case Intrinsic::aarch64_neon_ld2lane:
9911 case Intrinsic::aarch64_neon_ld3lane:
9912 case Intrinsic::aarch64_neon_ld4lane:
9913 case Intrinsic::aarch64_neon_ld2r:
9914 case Intrinsic::aarch64_neon_ld3r:
9915 case Intrinsic::aarch64_neon_ld4r:
9916 case Intrinsic::aarch64_neon_st2:
9917 case Intrinsic::aarch64_neon_st3:
9918 case Intrinsic::aarch64_neon_st4:
9919 case Intrinsic::aarch64_neon_st1x2:
9920 case Intrinsic::aarch64_neon_st1x3:
9921 case Intrinsic::aarch64_neon_st1x4:
9922 case Intrinsic::aarch64_neon_st2lane:
9923 case Intrinsic::aarch64_neon_st3lane:
9924 case Intrinsic::aarch64_neon_st4lane:
9925 return performNEONPostLDSTCombine(N, DCI, DAG);
9926 default:
9927 break;
9928 }
9929 }
9930 return SDValue();
9931}
9932
9933// Check if the return value is used as only a return value, as otherwise
9934// we can't perform a tail-call. In particular, we need to check for
9935// target ISD nodes that are returns and any other "odd" constructs
9936// that the generic analysis code won't necessarily catch.
9937bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9938 SDValue &Chain) const {
9939 if (N->getNumValues() != 1)
9940 return false;
9941 if (!N->hasNUsesOfValue(1, 0))
9942 return false;
9943
9944 SDValue TCChain = Chain;
9945 SDNode *Copy = *N->use_begin();
9946 if (Copy->getOpcode() == ISD::CopyToReg) {
9947 // If the copy has a glue operand, we conservatively assume it isn't safe to
9948 // perform a tail call.
9949 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9950 MVT::Glue)
9951 return false;
9952 TCChain = Copy->getOperand(0);
9953 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9954 return false;
9955
9956 bool HasRet = false;
9957 for (SDNode *Node : Copy->uses()) {
9958 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9959 return false;
9960 HasRet = true;
9961 }
9962
9963 if (!HasRet)
9964 return false;
9965
9966 Chain = TCChain;
9967 return true;
9968}
9969
9970// Return whether the an instruction can potentially be optimized to a tail
9971// call. This will cause the optimizers to attempt to move, or duplicate,
9972// return instructions to help enable tail call optimizations for this
9973// instruction.
9974bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009975 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00009976}
9977
9978bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9979 SDValue &Offset,
9980 ISD::MemIndexedMode &AM,
9981 bool &IsInc,
9982 SelectionDAG &DAG) const {
9983 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9984 return false;
9985
9986 Base = Op->getOperand(0);
9987 // All of the indexed addressing mode instructions take a signed
9988 // 9 bit immediate offset.
9989 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9990 int64_t RHSC = (int64_t)RHS->getZExtValue();
9991 if (RHSC >= 256 || RHSC <= -256)
9992 return false;
9993 IsInc = (Op->getOpcode() == ISD::ADD);
9994 Offset = Op->getOperand(1);
9995 return true;
9996 }
9997 return false;
9998}
9999
10000bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10001 SDValue &Offset,
10002 ISD::MemIndexedMode &AM,
10003 SelectionDAG &DAG) const {
10004 EVT VT;
10005 SDValue Ptr;
10006 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10007 VT = LD->getMemoryVT();
10008 Ptr = LD->getBasePtr();
10009 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10010 VT = ST->getMemoryVT();
10011 Ptr = ST->getBasePtr();
10012 } else
10013 return false;
10014
10015 bool IsInc;
10016 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10017 return false;
10018 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10019 return true;
10020}
10021
10022bool AArch64TargetLowering::getPostIndexedAddressParts(
10023 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10024 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10025 EVT VT;
10026 SDValue Ptr;
10027 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10028 VT = LD->getMemoryVT();
10029 Ptr = LD->getBasePtr();
10030 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10031 VT = ST->getMemoryVT();
10032 Ptr = ST->getBasePtr();
10033 } else
10034 return false;
10035
10036 bool IsInc;
10037 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10038 return false;
10039 // Post-indexing updates the base, so it's not a valid transform
10040 // if that's not the same as the load's pointer.
10041 if (Ptr != Base)
10042 return false;
10043 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10044 return true;
10045}
10046
Tim Northoverf8bfe212014-07-18 13:07:05 +000010047static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10048 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010049 SDLoc DL(N);
10050 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010051
10052 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10053 return;
10054
Tim Northoverf8bfe212014-07-18 13:07:05 +000010055 Op = SDValue(
10056 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10057 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010058 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010059 0);
10060 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10061 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10062}
10063
Charlie Turner434d4592015-10-16 15:38:25 +000010064static void ReplaceReductionResults(SDNode *N,
10065 SmallVectorImpl<SDValue> &Results,
10066 SelectionDAG &DAG, unsigned InterOp,
10067 unsigned AcrossOp) {
10068 EVT LoVT, HiVT;
10069 SDValue Lo, Hi;
10070 SDLoc dl(N);
10071 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10072 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10073 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10074 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10075 Results.push_back(SplitVal);
10076}
10077
Tim Northovercdf15292016-04-14 17:03:29 +000010078static void ReplaceCMP_SWAP_128Results(SDNode *N,
10079 SmallVectorImpl<SDValue> & Results,
10080 SelectionDAG &DAG) {
10081 assert(N->getValueType(0) == MVT::i128 &&
10082 "AtomicCmpSwap on types less than 128 should be legal");
10083 SDValue Ops[] = {N->getOperand(1),
10084 N->getOperand(2)->getOperand(0),
10085 N->getOperand(2)->getOperand(1),
10086 N->getOperand(3)->getOperand(0),
10087 N->getOperand(3)->getOperand(1),
10088 N->getOperand(0)};
10089 SDNode *CmpSwap = DAG.getMachineNode(
10090 AArch64::CMP_SWAP_128, SDLoc(N),
10091 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10092
10093 MachineFunction &MF = DAG.getMachineFunction();
10094 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10095 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10096 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10097
10098 Results.push_back(SDValue(CmpSwap, 0));
10099 Results.push_back(SDValue(CmpSwap, 1));
10100 Results.push_back(SDValue(CmpSwap, 3));
10101}
10102
Tim Northover3b0846e2014-05-24 12:50:23 +000010103void AArch64TargetLowering::ReplaceNodeResults(
10104 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10105 switch (N->getOpcode()) {
10106 default:
10107 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010108 case ISD::BITCAST:
10109 ReplaceBITCASTResults(N, Results, DAG);
10110 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010111 case AArch64ISD::SADDV:
10112 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10113 return;
10114 case AArch64ISD::UADDV:
10115 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10116 return;
10117 case AArch64ISD::SMINV:
10118 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10119 return;
10120 case AArch64ISD::UMINV:
10121 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10122 return;
10123 case AArch64ISD::SMAXV:
10124 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10125 return;
10126 case AArch64ISD::UMAXV:
10127 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10128 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010129 case ISD::FP_TO_UINT:
10130 case ISD::FP_TO_SINT:
10131 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10132 // Let normal code take care of it by not adding anything to Results.
10133 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010134 case ISD::ATOMIC_CMP_SWAP:
10135 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10136 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010137 }
10138}
10139
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010140bool AArch64TargetLowering::useLoadStackGuardNode() const {
Tim Shene885d5e2016-04-19 19:40:37 +000010141 if (!Subtarget->isTargetAndroid())
10142 return true;
10143 return TargetLowering::useLoadStackGuardNode();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010144}
10145
Sanjay Patel1dd15592015-07-28 23:05:48 +000010146unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010147 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10148 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010149 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010150}
10151
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010152TargetLoweringBase::LegalizeTypeAction
10153AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10154 MVT SVT = VT.getSimpleVT();
10155 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10156 // v4i16, v2i32 instead of to promote.
10157 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10158 || SVT == MVT::v1f32)
10159 return TypeWidenVector;
10160
10161 return TargetLoweringBase::getPreferredVectorAction(VT);
10162}
10163
Robin Morisseted3d48f2014-09-03 21:29:59 +000010164// Loads and stores less than 128-bits are already atomic; ones above that
10165// are doomed anyway, so defer to the default libcall and blame the OS when
10166// things go wrong.
10167bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10168 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10169 return Size == 128;
10170}
10171
10172// Loads and stores less than 128-bits are already atomic; ones above that
10173// are doomed anyway, so defer to the default libcall and blame the OS when
10174// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010175TargetLowering::AtomicExpansionKind
10176AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010177 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010178 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010179}
10180
10181// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010182TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010183AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010184 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010185 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010186}
10187
Ahmed Bougacha52468672015-09-11 17:08:28 +000010188bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10189 AtomicCmpXchgInst *AI) const {
Tim Northovercdf15292016-04-14 17:03:29 +000010190 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10191 // implement cmpxchg without spilling. If the address being exchanged is also
10192 // on the stack and close enough to the spill slot, this can lead to a
10193 // situation where the monitor always gets cleared and the atomic operation
10194 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10195 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010196}
10197
Tim Northover3b0846e2014-05-24 12:50:23 +000010198Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10199 AtomicOrdering Ord) const {
10200 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10201 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010202 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010203
10204 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10205 // intrinsic must return {i64, i64} and we have to recombine them into a
10206 // single i128 here.
10207 if (ValTy->getPrimitiveSizeInBits() == 128) {
10208 Intrinsic::ID Int =
10209 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10210 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10211
10212 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10213 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10214
10215 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10216 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10217 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10218 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10219 return Builder.CreateOr(
10220 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10221 }
10222
10223 Type *Tys[] = { Addr->getType() };
10224 Intrinsic::ID Int =
10225 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10226 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10227
10228 return Builder.CreateTruncOrBitCast(
10229 Builder.CreateCall(Ldxr, Addr),
10230 cast<PointerType>(Addr->getType())->getElementType());
10231}
10232
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010233void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10234 IRBuilder<> &Builder) const {
10235 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10236 Builder.CreateCall(
10237 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10238}
10239
Tim Northover3b0846e2014-05-24 12:50:23 +000010240Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10241 Value *Val, Value *Addr,
10242 AtomicOrdering Ord) const {
10243 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010244 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010245
10246 // Since the intrinsics must have legal type, the i128 intrinsics take two
10247 // parameters: "i64, i64". We must marshal Val into the appropriate form
10248 // before the call.
10249 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10250 Intrinsic::ID Int =
10251 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10252 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10253 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10254
10255 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10256 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10257 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010258 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010259 }
10260
10261 Intrinsic::ID Int =
10262 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10263 Type *Tys[] = { Addr->getType() };
10264 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10265
David Blaikieff6409d2015-05-18 22:13:54 +000010266 return Builder.CreateCall(Stxr,
10267 {Builder.CreateZExtOrBitCast(
10268 Val, Stxr->getFunctionType()->getParamType(0)),
10269 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010270}
Tim Northover3c55cca2014-11-27 21:02:42 +000010271
10272bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10273 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10274 return Ty->isArrayTy();
10275}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010276
10277bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10278 EVT) const {
10279 return false;
10280}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010281
Tim Shen00127562016-04-08 21:26:31 +000010282Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010283 if (!Subtarget->isTargetAndroid())
Tim Shen00127562016-04-08 21:26:31 +000010284 return TargetLowering::getIRStackGuard(IRB);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010285
10286 // Android provides a fixed TLS slot for the stack cookie. See the definition
10287 // of TLS_SLOT_STACK_GUARD in
10288 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10289 const unsigned TlsOffset = 0x28;
10290 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10291 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010292 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010293 return IRB.CreatePointerCast(
10294 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10295 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10296}
10297
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010298Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10299 if (!Subtarget->isTargetAndroid())
10300 return TargetLowering::getSafeStackPointerLocation(IRB);
10301
10302 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10303 // definition of TLS_SLOT_SAFESTACK in
10304 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10305 const unsigned TlsOffset = 0x48;
10306 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10307 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010308 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010309 return IRB.CreatePointerCast(
10310 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10311 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10312}
Manman Rencbe4f942015-12-16 21:04:19 +000010313
10314void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10315 // Update IsSplitCSR in AArch64unctionInfo.
10316 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10317 AFI->setIsSplitCSR(true);
10318}
10319
10320void AArch64TargetLowering::insertCopiesSplitCSR(
10321 MachineBasicBlock *Entry,
10322 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10323 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10324 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10325 if (!IStart)
10326 return;
10327
10328 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10329 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010330 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010331 for (const MCPhysReg *I = IStart; *I; ++I) {
10332 const TargetRegisterClass *RC = nullptr;
10333 if (AArch64::GPR64RegClass.contains(*I))
10334 RC = &AArch64::GPR64RegClass;
10335 else if (AArch64::FPR64RegClass.contains(*I))
10336 RC = &AArch64::FPR64RegClass;
10337 else
10338 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10339
10340 unsigned NewVR = MRI->createVirtualRegister(RC);
10341 // Create copy from CSR to a virtual register.
10342 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10343 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10344 // nounwind. If we want to generalize this later, we may need to emit
10345 // CFI pseudo-instructions.
10346 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10347 Attribute::NoUnwind) &&
10348 "Function should be nounwind in insertCopiesSplitCSR!");
10349 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010350 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010351 .addReg(*I);
10352
Manman Ren4632e8e2016-01-15 20:13:28 +000010353 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010354 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010355 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10356 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010357 .addReg(NewVR);
10358 }
10359}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010360
10361bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10362 // Integer division on AArch64 is expensive. However, when aggressively
10363 // optimizing for code size, we prefer to use a div instruction, as it is
10364 // usually smaller than the alternative sequence.
10365 // The exception to this is vector division. Since AArch64 doesn't have vector
10366 // integer division, leaving the division as-is is a loss even in terms of
10367 // size, because it will have to be scalarized, while the alternative code
10368 // sequence can be performed in vector form.
10369 bool OptSize =
10370 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10371 return OptSize && !VT.isVector();
10372}