blob: 6ed9e6fe5aa5419d9d2635a208f4817422ff0198 [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:
Justin Bognerb03fd122016-08-17 05:10:15 +00001182 Invert = true;
1183 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001184 case ISD::SETO:
1185 CondCode = AArch64CC::MI;
1186 CondCode2 = AArch64CC::GE;
1187 break;
1188 case ISD::SETUEQ:
1189 case ISD::SETULT:
1190 case ISD::SETULE:
1191 case ISD::SETUGT:
1192 case ISD::SETUGE:
1193 // All of the compare-mask comparisons are ordered, but we can switch
1194 // between the two by a double inversion. E.g. ULE == !OGT.
1195 Invert = true;
1196 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1197 break;
1198 }
1199}
1200
1201static bool isLegalArithImmed(uint64_t C) {
1202 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1203 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1204}
1205
1206static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001207 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001208 EVT VT = LHS.getValueType();
1209
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001210 if (VT.isFloatingPoint()) {
1211 assert(VT != MVT::f128);
1212 if (VT == MVT::f16) {
1213 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1214 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001215 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001216 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001217 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001218 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001219
1220 // The CMP instruction is just an alias for SUBS, and representing it as
1221 // SUBS means that it's possible to get CSE with subtract operations.
1222 // A later phase can perform the optimization of setting the destination
1223 // register to WZR/XZR if it ends up being unused.
1224 unsigned Opcode = AArch64ISD::SUBS;
1225
Artyom Skrobov314ee042015-11-25 19:41:11 +00001226 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001227 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1228 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1229 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1230 // can be set differently by this operation. It comes down to whether
1231 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1232 // everything is fine. If not then the optimization is wrong. Thus general
1233 // comparisons are only valid if op2 != 0.
1234
1235 // So, finally, the only LLVM-native comparisons that don't mention C and V
1236 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1237 // the absence of information about op2.
1238 Opcode = AArch64ISD::ADDS;
1239 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001240 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001241 !isUnsignedIntSetCC(CC)) {
1242 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1243 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1244 // of the signed comparisons.
1245 Opcode = AArch64ISD::ANDS;
1246 RHS = LHS.getOperand(1);
1247 LHS = LHS.getOperand(0);
1248 }
1249
Matthias Braunaf7d7702015-07-16 20:02:37 +00001250 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001251 .getValue(1);
1252}
1253
Matthias Braunaf7d7702015-07-16 20:02:37 +00001254/// \defgroup AArch64CCMP CMP;CCMP matching
1255///
1256/// These functions deal with the formation of CMP;CCMP;... sequences.
1257/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1258/// a comparison. They set the NZCV flags to a predefined value if their
1259/// predicate is false. This allows to express arbitrary conjunctions, for
1260/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1261/// expressed as:
1262/// cmp A
1263/// ccmp B, inv(CB), CA
1264/// check for CB flags
1265///
1266/// In general we can create code for arbitrary "... (and (and A B) C)"
1267/// sequences. We can also implement some "or" expressions, because "(or A B)"
1268/// is equivalent to "not (and (not A) (not B))" and we can implement some
1269/// negation operations:
1270/// We can negate the results of a single comparison by inverting the flags
1271/// used when the predicate fails and inverting the flags tested in the next
1272/// instruction; We can also negate the results of the whole previous
1273/// conditional compare sequence by inverting the flags tested in the next
1274/// instruction. However there is no way to negate the result of a partial
1275/// sequence.
1276///
1277/// Therefore on encountering an "or" expression we can negate the subtree on
1278/// one side and have to be able to push the negate to the leafs of the subtree
1279/// on the other side (see also the comments in code). As complete example:
1280/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1281/// (and (setCC (cmp C)) (setCD (cmp D)))"
1282/// is transformed to
1283/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1284/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1285/// and implemented as:
1286/// cmp C
1287/// ccmp D, inv(CD), CC
1288/// ccmp A, CA, inv(CD)
1289/// ccmp B, CB, inv(CA)
1290/// check for CB flags
1291/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1292/// by conditional compare sequences.
1293/// @{
1294
Geoff Berrye41c2df2015-07-20 22:03:52 +00001295/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001296static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1297 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001298 AArch64CC::CondCode Predicate,
1299 AArch64CC::CondCode OutCC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001300 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001301 unsigned Opcode = 0;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001302 if (LHS.getValueType().isFloatingPoint()) {
1303 assert(LHS.getValueType() != MVT::f128);
1304 if (LHS.getValueType() == MVT::f16) {
1305 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1306 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1307 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001308 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001309 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001310 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001311 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001312 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1313 Opcode = AArch64ISD::CCMN;
1314 RHS = RHS.getOperand(1);
1315 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001316 }
1317 if (Opcode == 0)
1318 Opcode = AArch64ISD::CCMP;
1319
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001320 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1321 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1322 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001323 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1324 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1325}
1326
1327/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1328/// CanPushNegate is set to true if we can push a negate operation through
1329/// the tree in a was that we are left with AND operations and negate operations
1330/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1331/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1332/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001333static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001334 unsigned Depth = 0) {
1335 if (!Val.hasOneUse())
1336 return false;
1337 unsigned Opcode = Val->getOpcode();
1338 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001339 if (Val->getOperand(0).getValueType() == MVT::f128)
1340 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001341 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001342 return true;
1343 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001344 // Protect against exponential runtime and stack overflow.
1345 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001346 return false;
1347 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1348 SDValue O0 = Val->getOperand(0);
1349 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001350 bool CanNegateL;
1351 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001352 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001353 bool CanNegateR;
1354 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001355 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001356
1357 if (Opcode == ISD::OR) {
1358 // For an OR expression we need to be able to negate at least one side or
1359 // we cannot do the transformation at all.
1360 if (!CanNegateL && !CanNegateR)
1361 return false;
1362 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1363 // can negate the x and y subtrees.
1364 CanNegate = CanNegateL && CanNegateR;
1365 } else {
1366 // If the operands are OR expressions then we finally need to negate their
1367 // outputs, we can only do that for the operand with emitted last by
1368 // negating OutCC, not for both operands.
1369 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1370 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1371 if (NeedsNegOutL && NeedsNegOutR)
1372 return false;
1373 // We cannot negate an AND operation (it would become an OR),
1374 CanNegate = false;
1375 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001376 return true;
1377 }
1378 return false;
1379}
1380
1381/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1382/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1383/// Tries to transform the given i1 producing node @p Val to a series compare
1384/// and conditional compare operations. @returns an NZCV flags producing node
1385/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1386/// transformation was not possible.
1387/// On recursive invocations @p PushNegate may be set to true to have negation
1388/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1389/// for the comparisons in the current subtree; @p Depth limits the search
1390/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001391static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1392 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1393 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001394 // We're at a tree leaf, produce a conditional comparison operation.
1395 unsigned Opcode = Val->getOpcode();
1396 if (Opcode == ISD::SETCC) {
1397 SDValue LHS = Val->getOperand(0);
1398 SDValue RHS = Val->getOperand(1);
1399 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1400 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001401 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001402 CC = getSetCCInverse(CC, isInteger);
1403 SDLoc DL(Val);
1404 // Determine OutCC and handle FP special case.
1405 if (isInteger) {
1406 OutCC = changeIntCCToAArch64CC(CC);
1407 } else {
1408 assert(LHS.getValueType().isFloatingPoint());
1409 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001410 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1411 // Some floating point conditions can't be tested with a single condition
1412 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001413 if (ExtraCC != AArch64CC::AL) {
1414 SDValue ExtraCmp;
1415 if (!CCOp.getNode())
1416 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001417 else
1418 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1419 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001420 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001421 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001422 }
1423 }
1424
1425 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001426 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001427 return emitComparison(LHS, RHS, CC, DL, DAG);
1428 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001429 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001430 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001431 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001432 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1433 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001434
1435 // Check if both sides can be transformed.
1436 SDValue LHS = Val->getOperand(0);
1437 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001438
Matthias Braunfdef49b2016-01-23 04:05:22 +00001439 // In case of an OR we need to negate our operands and the result.
1440 // (A v B) <=> not(not(A) ^ not(B))
1441 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001442 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001443 // predicate flags giving us a free negation for one side. The other side
1444 // must be negatable by itself.
1445 if (NegateOpsAndResult) {
1446 // See which side we can negate.
1447 bool CanNegateL;
1448 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1449 assert(isValidL && "Valid conjunction/disjunction tree");
1450 (void)isValidL;
1451
1452#ifndef NDEBUG
1453 bool CanNegateR;
1454 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1455 assert(isValidR && "Valid conjunction/disjunction tree");
1456 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1457#endif
1458
1459 // Order the side which we cannot negate to RHS so we can emit it first.
1460 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001461 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001462 } else {
1463 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001464 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001465 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001466 // Order the side where we need to negate the output flags to RHS so it
1467 // gets emitted first.
1468 if (NeedsNegOutL)
1469 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001470 }
1471
1472 // Emit RHS. If we want to negate the tree we only need to push a negate
1473 // through if we are already in a PushNegate case, otherwise we can negate
1474 // the "flags to test" afterwards.
1475 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001476 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1477 CCOp, Predicate);
1478 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001479 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001480 // Emit LHS. We may need to negate it.
1481 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1482 NegateOpsAndResult, CmpR,
1483 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001484 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001485 // (or absorb the Negate parameter).
1486 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001487 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1488 return CmpL;
1489}
1490
Matthias Braunfdef49b2016-01-23 04:05:22 +00001491/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1492/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1493/// \see emitConjunctionDisjunctionTreeRec().
1494static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1495 AArch64CC::CondCode &OutCC) {
1496 bool CanNegate;
1497 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1498 return SDValue();
1499
1500 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1501 AArch64CC::AL);
1502}
1503
Matthias Braunaf7d7702015-07-16 20:02:37 +00001504/// @}
1505
Tim Northover3b0846e2014-05-24 12:50:23 +00001506static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001507 SDValue &AArch64cc, SelectionDAG &DAG,
1508 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001509 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1510 EVT VT = RHS.getValueType();
1511 uint64_t C = RHSC->getZExtValue();
1512 if (!isLegalArithImmed(C)) {
1513 // Constant does not fit, try adjusting it by one?
1514 switch (CC) {
1515 default:
1516 break;
1517 case ISD::SETLT:
1518 case ISD::SETGE:
1519 if ((VT == MVT::i32 && C != 0x80000000 &&
1520 isLegalArithImmed((uint32_t)(C - 1))) ||
1521 (VT == MVT::i64 && C != 0x80000000ULL &&
1522 isLegalArithImmed(C - 1ULL))) {
1523 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1524 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001525 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001526 }
1527 break;
1528 case ISD::SETULT:
1529 case ISD::SETUGE:
1530 if ((VT == MVT::i32 && C != 0 &&
1531 isLegalArithImmed((uint32_t)(C - 1))) ||
1532 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1533 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1534 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001535 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001536 }
1537 break;
1538 case ISD::SETLE:
1539 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001540 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001541 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001542 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001543 isLegalArithImmed(C + 1ULL))) {
1544 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1545 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001546 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001547 }
1548 break;
1549 case ISD::SETULE:
1550 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001551 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001552 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001553 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001554 isLegalArithImmed(C + 1ULL))) {
1555 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1556 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001557 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001558 }
1559 break;
1560 }
1561 }
1562 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001563 SDValue Cmp;
1564 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001565 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001566 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1567
1568 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1569 // For the i8 operand, the largest immediate is 255, so this can be easily
1570 // encoded in the compare instruction. For the i16 operand, however, the
1571 // largest immediate cannot be encoded in the compare.
1572 // Therefore, use a sign extending load and cmn to avoid materializing the
1573 // -1 constant. For example,
1574 // movz w1, #65535
1575 // ldrh w0, [x0, #0]
1576 // cmp w0, w1
1577 // >
1578 // ldrsh w0, [x0, #0]
1579 // cmn w0, #1
1580 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1581 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001582 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001583 // transformation is profitable.
1584 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1585 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1586 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1587 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1588 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1589 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1590 SDValue SExt =
1591 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1592 DAG.getValueType(MVT::i16));
1593 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1594 RHS.getValueType()),
1595 CC, dl, DAG);
1596 AArch64CC = changeIntCCToAArch64CC(CC);
1597 }
1598 }
1599
1600 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1601 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1602 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1603 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001604 }
1605 }
1606 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001607
1608 if (!Cmp) {
1609 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1610 AArch64CC = changeIntCCToAArch64CC(CC);
1611 }
1612 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001613 return Cmp;
1614}
1615
1616static std::pair<SDValue, SDValue>
1617getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1618 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1619 "Unsupported value type");
1620 SDValue Value, Overflow;
1621 SDLoc DL(Op);
1622 SDValue LHS = Op.getOperand(0);
1623 SDValue RHS = Op.getOperand(1);
1624 unsigned Opc = 0;
1625 switch (Op.getOpcode()) {
1626 default:
1627 llvm_unreachable("Unknown overflow instruction!");
1628 case ISD::SADDO:
1629 Opc = AArch64ISD::ADDS;
1630 CC = AArch64CC::VS;
1631 break;
1632 case ISD::UADDO:
1633 Opc = AArch64ISD::ADDS;
1634 CC = AArch64CC::HS;
1635 break;
1636 case ISD::SSUBO:
1637 Opc = AArch64ISD::SUBS;
1638 CC = AArch64CC::VS;
1639 break;
1640 case ISD::USUBO:
1641 Opc = AArch64ISD::SUBS;
1642 CC = AArch64CC::LO;
1643 break;
1644 // Multiply needs a little bit extra work.
1645 case ISD::SMULO:
1646 case ISD::UMULO: {
1647 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001648 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001649 if (Op.getValueType() == MVT::i32) {
1650 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1651 // For a 32 bit multiply with overflow check we want the instruction
1652 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1653 // need to generate the following pattern:
1654 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1655 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1656 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1657 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1658 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001659 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001660 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1661 // operation. We need to clear out the upper 32 bits, because we used a
1662 // widening multiply that wrote all 64 bits. In the end this should be a
1663 // noop.
1664 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1665 if (IsSigned) {
1666 // The signed overflow check requires more than just a simple check for
1667 // any bit set in the upper 32 bits of the result. These bits could be
1668 // just the sign bits of a negative number. To perform the overflow
1669 // check we have to arithmetic shift right the 32nd bit of the result by
1670 // 31 bits. Then we compare the result to the upper 32 bits.
1671 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001672 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001673 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1674 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001675 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001676 // It is important that LowerBits is last, otherwise the arithmetic
1677 // shift will not be folded into the compare (SUBS).
1678 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1679 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1680 .getValue(1);
1681 } else {
1682 // The overflow check for unsigned multiply is easy. We only need to
1683 // check if any of the upper 32 bits are set. This can be done with a
1684 // CMP (shifted register). For that we need to generate the following
1685 // pattern:
1686 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1687 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001688 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001689 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1690 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001691 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1692 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001693 UpperBits).getValue(1);
1694 }
1695 break;
1696 }
1697 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1698 // For the 64 bit multiply
1699 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1700 if (IsSigned) {
1701 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1702 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001703 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001704 // It is important that LowerBits is last, otherwise the arithmetic
1705 // shift will not be folded into the compare (SUBS).
1706 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1707 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1708 .getValue(1);
1709 } else {
1710 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1711 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1712 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001713 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1714 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001715 UpperBits).getValue(1);
1716 }
1717 break;
1718 }
1719 } // switch (...)
1720
1721 if (Opc) {
1722 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1723
1724 // Emit the AArch64 operation with overflow check.
1725 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1726 Overflow = Value.getValue(1);
1727 }
1728 return std::make_pair(Value, Overflow);
1729}
1730
1731SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1732 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001733 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001734 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001735}
1736
1737static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1738 SDValue Sel = Op.getOperand(0);
1739 SDValue Other = Op.getOperand(1);
1740
1741 // If neither operand is a SELECT_CC, give up.
1742 if (Sel.getOpcode() != ISD::SELECT_CC)
1743 std::swap(Sel, Other);
1744 if (Sel.getOpcode() != ISD::SELECT_CC)
1745 return Op;
1746
1747 // The folding we want to perform is:
1748 // (xor x, (select_cc a, b, cc, 0, -1) )
1749 // -->
1750 // (csel x, (xor x, -1), cc ...)
1751 //
1752 // The latter will get matched to a CSINV instruction.
1753
1754 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1755 SDValue LHS = Sel.getOperand(0);
1756 SDValue RHS = Sel.getOperand(1);
1757 SDValue TVal = Sel.getOperand(2);
1758 SDValue FVal = Sel.getOperand(3);
1759 SDLoc dl(Sel);
1760
1761 // FIXME: This could be generalized to non-integer comparisons.
1762 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1763 return Op;
1764
1765 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1766 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1767
Eric Christopher572e03a2015-06-19 01:53:21 +00001768 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001769 if (!CFVal || !CTVal)
1770 return Op;
1771
1772 // We can commute the SELECT_CC by inverting the condition. This
1773 // might be needed to make this fit into a CSINV pattern.
1774 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1775 std::swap(TVal, FVal);
1776 std::swap(CTVal, CFVal);
1777 CC = ISD::getSetCCInverse(CC, true);
1778 }
1779
1780 // If the constants line up, perform the transform!
1781 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1782 SDValue CCVal;
1783 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1784
1785 FVal = Other;
1786 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001787 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001788
1789 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1790 CCVal, Cmp);
1791 }
1792
1793 return Op;
1794}
1795
1796static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1797 EVT VT = Op.getValueType();
1798
1799 // Let legalize expand this if it isn't a legal type yet.
1800 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1801 return SDValue();
1802
1803 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1804
1805 unsigned Opc;
1806 bool ExtraOp = false;
1807 switch (Op.getOpcode()) {
1808 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001809 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001810 case ISD::ADDC:
1811 Opc = AArch64ISD::ADDS;
1812 break;
1813 case ISD::SUBC:
1814 Opc = AArch64ISD::SUBS;
1815 break;
1816 case ISD::ADDE:
1817 Opc = AArch64ISD::ADCS;
1818 ExtraOp = true;
1819 break;
1820 case ISD::SUBE:
1821 Opc = AArch64ISD::SBCS;
1822 ExtraOp = true;
1823 break;
1824 }
1825
1826 if (!ExtraOp)
1827 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1828 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1829 Op.getOperand(2));
1830}
1831
1832static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1833 // Let legalize expand this if it isn't a legal type yet.
1834 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1835 return SDValue();
1836
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001837 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001838 AArch64CC::CondCode CC;
1839 // The actual operation that sets the overflow or carry flag.
1840 SDValue Value, Overflow;
1841 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1842
1843 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001844 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1845 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001846
1847 // We use an inverted condition, because the conditional select is inverted
1848 // too. This will allow it to be selected to a single instruction:
1849 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001850 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1851 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001852 CCVal, Overflow);
1853
1854 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001855 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001856}
1857
1858// Prefetch operands are:
1859// 1: Address to prefetch
1860// 2: bool isWrite
1861// 3: int locality (0 = no locality ... 3 = extreme locality)
1862// 4: bool isDataCache
1863static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1864 SDLoc DL(Op);
1865 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1866 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001867 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001868
1869 bool IsStream = !Locality;
1870 // When the locality number is set
1871 if (Locality) {
1872 // The front-end should have filtered out the out-of-range values
1873 assert(Locality <= 3 && "Prefetch locality out-of-range");
1874 // The locality degree is the opposite of the cache speed.
1875 // Put the number the other way around.
1876 // The encoding starts at 0 for level 1
1877 Locality = 3 - Locality;
1878 }
1879
1880 // built the mask value encoding the expected behavior.
1881 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001882 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001883 (Locality << 1) | // Cache level bits
1884 (unsigned)IsStream; // Stream bit
1885 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001886 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001887}
1888
1889SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1890 SelectionDAG &DAG) const {
1891 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1892
1893 RTLIB::Libcall LC;
1894 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1895
1896 return LowerF128Call(Op, DAG, LC);
1897}
1898
1899SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1900 SelectionDAG &DAG) const {
1901 if (Op.getOperand(0).getValueType() != MVT::f128) {
1902 // It's legal except when f128 is involved
1903 return Op;
1904 }
1905
1906 RTLIB::Libcall LC;
1907 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1908
1909 // FP_ROUND node has a second operand indicating whether it is known to be
1910 // precise. That doesn't take part in the LibCall so we can't directly use
1911 // LowerF128Call.
1912 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001913 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1914 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001915}
1916
1917static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1918 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1919 // Any additional optimization in this function should be recorded
1920 // in the cost tables.
1921 EVT InVT = Op.getOperand(0).getValueType();
1922 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001923 unsigned NumElts = InVT.getVectorNumElements();
1924
1925 // f16 vectors are promoted to f32 before a conversion.
1926 if (InVT.getVectorElementType() == MVT::f16) {
1927 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1928 SDLoc dl(Op);
1929 return DAG.getNode(
1930 Op.getOpcode(), dl, Op.getValueType(),
1931 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1932 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001933
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001934 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001935 SDLoc dl(Op);
1936 SDValue Cv =
1937 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1938 Op.getOperand(0));
1939 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001940 }
1941
1942 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001943 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001944 MVT ExtVT =
1945 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1946 VT.getVectorNumElements());
1947 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001948 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1949 }
1950
1951 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001952 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001953}
1954
1955SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1956 SelectionDAG &DAG) const {
1957 if (Op.getOperand(0).getValueType().isVector())
1958 return LowerVectorFP_TO_INT(Op, DAG);
1959
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001960 // f16 conversions are promoted to f32.
1961 if (Op.getOperand(0).getValueType() == MVT::f16) {
1962 SDLoc dl(Op);
1963 return DAG.getNode(
1964 Op.getOpcode(), dl, Op.getValueType(),
1965 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1966 }
1967
Tim Northover3b0846e2014-05-24 12:50:23 +00001968 if (Op.getOperand(0).getValueType() != MVT::f128) {
1969 // It's legal except when f128 is involved
1970 return Op;
1971 }
1972
1973 RTLIB::Libcall LC;
1974 if (Op.getOpcode() == ISD::FP_TO_SINT)
1975 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1976 else
1977 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1978
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001979 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001980 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001981}
1982
1983static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1984 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1985 // Any additional optimization in this function should be recorded
1986 // in the cost tables.
1987 EVT VT = Op.getValueType();
1988 SDLoc dl(Op);
1989 SDValue In = Op.getOperand(0);
1990 EVT InVT = In.getValueType();
1991
Tim Northoveref0d7602014-06-15 09:27:06 +00001992 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1993 MVT CastVT =
1994 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1995 InVT.getVectorNumElements());
1996 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001997 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001998 }
1999
Tim Northoveref0d7602014-06-15 09:27:06 +00002000 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2001 unsigned CastOpc =
2002 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2003 EVT CastVT = VT.changeVectorElementTypeToInteger();
2004 In = DAG.getNode(CastOpc, dl, CastVT, In);
2005 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002006 }
2007
Tim Northoveref0d7602014-06-15 09:27:06 +00002008 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002009}
2010
2011SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2012 SelectionDAG &DAG) const {
2013 if (Op.getValueType().isVector())
2014 return LowerVectorINT_TO_FP(Op, DAG);
2015
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002016 // f16 conversions are promoted to f32.
2017 if (Op.getValueType() == MVT::f16) {
2018 SDLoc dl(Op);
2019 return DAG.getNode(
2020 ISD::FP_ROUND, dl, MVT::f16,
2021 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002022 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002023 }
2024
Tim Northover3b0846e2014-05-24 12:50:23 +00002025 // i128 conversions are libcalls.
2026 if (Op.getOperand(0).getValueType() == MVT::i128)
2027 return SDValue();
2028
2029 // Other conversions are legal, unless it's to the completely software-based
2030 // fp128.
2031 if (Op.getValueType() != MVT::f128)
2032 return Op;
2033
2034 RTLIB::Libcall LC;
2035 if (Op.getOpcode() == ISD::SINT_TO_FP)
2036 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2037 else
2038 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2039
2040 return LowerF128Call(Op, DAG, LC);
2041}
2042
2043SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2044 SelectionDAG &DAG) const {
2045 // For iOS, we want to call an alternative entry point: __sincos_stret,
2046 // which returns the values in two S / D registers.
2047 SDLoc dl(Op);
2048 SDValue Arg = Op.getOperand(0);
2049 EVT ArgVT = Arg.getValueType();
2050 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2051
2052 ArgListTy Args;
2053 ArgListEntry Entry;
2054
2055 Entry.Node = Arg;
2056 Entry.Ty = ArgTy;
2057 Entry.isSExt = false;
2058 Entry.isZExt = false;
2059 Args.push_back(Entry);
2060
2061 const char *LibcallName =
2062 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002063 SDValue Callee =
2064 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002065
Reid Kleckner343c3952014-11-20 23:51:47 +00002066 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002067 TargetLowering::CallLoweringInfo CLI(DAG);
2068 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00002069 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002070
2071 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2072 return CallResult.first;
2073}
2074
Tim Northoverf8bfe212014-07-18 13:07:05 +00002075static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2076 if (Op.getValueType() != MVT::f16)
2077 return SDValue();
2078
2079 assert(Op.getOperand(0).getValueType() == MVT::i16);
2080 SDLoc DL(Op);
2081
2082 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2083 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2084 return SDValue(
2085 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002086 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002087 0);
2088}
2089
Chad Rosierd9d0f862014-10-08 02:31:24 +00002090static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2091 if (OrigVT.getSizeInBits() >= 64)
2092 return OrigVT;
2093
2094 assert(OrigVT.isSimple() && "Expecting a simple value type");
2095
2096 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2097 switch (OrigSimpleTy) {
2098 default: llvm_unreachable("Unexpected Vector Type");
2099 case MVT::v2i8:
2100 case MVT::v2i16:
2101 return MVT::v2i32;
2102 case MVT::v4i8:
2103 return MVT::v4i16;
2104 }
2105}
2106
2107static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2108 const EVT &OrigTy,
2109 const EVT &ExtTy,
2110 unsigned ExtOpcode) {
2111 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2112 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2113 // 64-bits we need to insert a new extension so that it will be 64-bits.
2114 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2115 if (OrigTy.getSizeInBits() >= 64)
2116 return N;
2117
2118 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2119 EVT NewVT = getExtensionTo64Bits(OrigTy);
2120
2121 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2122}
2123
2124static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2125 bool isSigned) {
2126 EVT VT = N->getValueType(0);
2127
2128 if (N->getOpcode() != ISD::BUILD_VECTOR)
2129 return false;
2130
Pete Cooper3af9a252015-06-26 18:17:36 +00002131 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2133 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2134 unsigned HalfSize = EltSize / 2;
2135 if (isSigned) {
2136 if (!isIntN(HalfSize, C->getSExtValue()))
2137 return false;
2138 } else {
2139 if (!isUIntN(HalfSize, C->getZExtValue()))
2140 return false;
2141 }
2142 continue;
2143 }
2144 return false;
2145 }
2146
2147 return true;
2148}
2149
2150static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2151 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2152 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2153 N->getOperand(0)->getValueType(0),
2154 N->getValueType(0),
2155 N->getOpcode());
2156
2157 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2158 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002159 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002160 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2161 unsigned NumElts = VT.getVectorNumElements();
2162 MVT TruncVT = MVT::getIntegerVT(EltSize);
2163 SmallVector<SDValue, 8> Ops;
2164 for (unsigned i = 0; i != NumElts; ++i) {
2165 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2166 const APInt &CInt = C->getAPIntValue();
2167 // Element types smaller than 32 bits are not legal, so use i32 elements.
2168 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002169 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002170 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002171 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002172}
2173
2174static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2175 if (N->getOpcode() == ISD::SIGN_EXTEND)
2176 return true;
2177 if (isExtendedBUILD_VECTOR(N, DAG, true))
2178 return true;
2179 return false;
2180}
2181
2182static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2183 if (N->getOpcode() == ISD::ZERO_EXTEND)
2184 return true;
2185 if (isExtendedBUILD_VECTOR(N, DAG, false))
2186 return true;
2187 return false;
2188}
2189
2190static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2191 unsigned Opcode = N->getOpcode();
2192 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2193 SDNode *N0 = N->getOperand(0).getNode();
2194 SDNode *N1 = N->getOperand(1).getNode();
2195 return N0->hasOneUse() && N1->hasOneUse() &&
2196 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2197 }
2198 return false;
2199}
2200
2201static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2202 unsigned Opcode = N->getOpcode();
2203 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2204 SDNode *N0 = N->getOperand(0).getNode();
2205 SDNode *N1 = N->getOperand(1).getNode();
2206 return N0->hasOneUse() && N1->hasOneUse() &&
2207 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2208 }
2209 return false;
2210}
2211
2212static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2213 // Multiplications are only custom-lowered for 128-bit vectors so that
2214 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2215 EVT VT = Op.getValueType();
2216 assert(VT.is128BitVector() && VT.isInteger() &&
2217 "unexpected type for custom-lowering ISD::MUL");
2218 SDNode *N0 = Op.getOperand(0).getNode();
2219 SDNode *N1 = Op.getOperand(1).getNode();
2220 unsigned NewOpc = 0;
2221 bool isMLA = false;
2222 bool isN0SExt = isSignExtended(N0, DAG);
2223 bool isN1SExt = isSignExtended(N1, DAG);
2224 if (isN0SExt && isN1SExt)
2225 NewOpc = AArch64ISD::SMULL;
2226 else {
2227 bool isN0ZExt = isZeroExtended(N0, DAG);
2228 bool isN1ZExt = isZeroExtended(N1, DAG);
2229 if (isN0ZExt && isN1ZExt)
2230 NewOpc = AArch64ISD::UMULL;
2231 else if (isN1SExt || isN1ZExt) {
2232 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2233 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2234 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2235 NewOpc = AArch64ISD::SMULL;
2236 isMLA = true;
2237 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2238 NewOpc = AArch64ISD::UMULL;
2239 isMLA = true;
2240 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2241 std::swap(N0, N1);
2242 NewOpc = AArch64ISD::UMULL;
2243 isMLA = true;
2244 }
2245 }
2246
2247 if (!NewOpc) {
2248 if (VT == MVT::v2i64)
2249 // Fall through to expand this. It is not legal.
2250 return SDValue();
2251 else
2252 // Other vector multiplications are legal.
2253 return Op;
2254 }
2255 }
2256
2257 // Legalize to a S/UMULL instruction
2258 SDLoc DL(Op);
2259 SDValue Op0;
2260 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2261 if (!isMLA) {
2262 Op0 = skipExtensionForVectorMULL(N0, DAG);
2263 assert(Op0.getValueType().is64BitVector() &&
2264 Op1.getValueType().is64BitVector() &&
2265 "unexpected types for extended operands to VMULL");
2266 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2267 }
2268 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2269 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2270 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2271 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2272 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2273 EVT Op1VT = Op1.getValueType();
2274 return DAG.getNode(N0->getOpcode(), DL, VT,
2275 DAG.getNode(NewOpc, DL, VT,
2276 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2277 DAG.getNode(NewOpc, DL, VT,
2278 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2279}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002280
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002281SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2282 SelectionDAG &DAG) const {
2283 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2284 SDLoc dl(Op);
2285 switch (IntNo) {
2286 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002287 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002288 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2289 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2290 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002291 case Intrinsic::aarch64_neon_smax:
2292 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2293 Op.getOperand(1), Op.getOperand(2));
2294 case Intrinsic::aarch64_neon_umax:
2295 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2296 Op.getOperand(1), Op.getOperand(2));
2297 case Intrinsic::aarch64_neon_smin:
2298 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2299 Op.getOperand(1), Op.getOperand(2));
2300 case Intrinsic::aarch64_neon_umin:
2301 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2302 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002303 }
2304}
2305
Tim Northover3b0846e2014-05-24 12:50:23 +00002306SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2307 SelectionDAG &DAG) const {
2308 switch (Op.getOpcode()) {
2309 default:
2310 llvm_unreachable("unimplemented operand");
2311 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002312 case ISD::BITCAST:
2313 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002314 case ISD::GlobalAddress:
2315 return LowerGlobalAddress(Op, DAG);
2316 case ISD::GlobalTLSAddress:
2317 return LowerGlobalTLSAddress(Op, DAG);
2318 case ISD::SETCC:
2319 return LowerSETCC(Op, DAG);
2320 case ISD::BR_CC:
2321 return LowerBR_CC(Op, DAG);
2322 case ISD::SELECT:
2323 return LowerSELECT(Op, DAG);
2324 case ISD::SELECT_CC:
2325 return LowerSELECT_CC(Op, DAG);
2326 case ISD::JumpTable:
2327 return LowerJumpTable(Op, DAG);
2328 case ISD::ConstantPool:
2329 return LowerConstantPool(Op, DAG);
2330 case ISD::BlockAddress:
2331 return LowerBlockAddress(Op, DAG);
2332 case ISD::VASTART:
2333 return LowerVASTART(Op, DAG);
2334 case ISD::VACOPY:
2335 return LowerVACOPY(Op, DAG);
2336 case ISD::VAARG:
2337 return LowerVAARG(Op, DAG);
2338 case ISD::ADDC:
2339 case ISD::ADDE:
2340 case ISD::SUBC:
2341 case ISD::SUBE:
2342 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2343 case ISD::SADDO:
2344 case ISD::UADDO:
2345 case ISD::SSUBO:
2346 case ISD::USUBO:
2347 case ISD::SMULO:
2348 case ISD::UMULO:
2349 return LowerXALUO(Op, DAG);
2350 case ISD::FADD:
2351 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2352 case ISD::FSUB:
2353 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2354 case ISD::FMUL:
2355 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2356 case ISD::FDIV:
2357 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2358 case ISD::FP_ROUND:
2359 return LowerFP_ROUND(Op, DAG);
2360 case ISD::FP_EXTEND:
2361 return LowerFP_EXTEND(Op, DAG);
2362 case ISD::FRAMEADDR:
2363 return LowerFRAMEADDR(Op, DAG);
2364 case ISD::RETURNADDR:
2365 return LowerRETURNADDR(Op, DAG);
2366 case ISD::INSERT_VECTOR_ELT:
2367 return LowerINSERT_VECTOR_ELT(Op, DAG);
2368 case ISD::EXTRACT_VECTOR_ELT:
2369 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2370 case ISD::BUILD_VECTOR:
2371 return LowerBUILD_VECTOR(Op, DAG);
2372 case ISD::VECTOR_SHUFFLE:
2373 return LowerVECTOR_SHUFFLE(Op, DAG);
2374 case ISD::EXTRACT_SUBVECTOR:
2375 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2376 case ISD::SRA:
2377 case ISD::SRL:
2378 case ISD::SHL:
2379 return LowerVectorSRA_SRL_SHL(Op, DAG);
2380 case ISD::SHL_PARTS:
2381 return LowerShiftLeftParts(Op, DAG);
2382 case ISD::SRL_PARTS:
2383 case ISD::SRA_PARTS:
2384 return LowerShiftRightParts(Op, DAG);
2385 case ISD::CTPOP:
2386 return LowerCTPOP(Op, DAG);
2387 case ISD::FCOPYSIGN:
2388 return LowerFCOPYSIGN(Op, DAG);
2389 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002390 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002391 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002392 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002393 case ISD::XOR:
2394 return LowerXOR(Op, DAG);
2395 case ISD::PREFETCH:
2396 return LowerPREFETCH(Op, DAG);
2397 case ISD::SINT_TO_FP:
2398 case ISD::UINT_TO_FP:
2399 return LowerINT_TO_FP(Op, DAG);
2400 case ISD::FP_TO_SINT:
2401 case ISD::FP_TO_UINT:
2402 return LowerFP_TO_INT(Op, DAG);
2403 case ISD::FSINCOS:
2404 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002405 case ISD::MUL:
2406 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002407 case ISD::INTRINSIC_WO_CHAIN:
2408 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002409 }
2410}
2411
Tim Northover3b0846e2014-05-24 12:50:23 +00002412//===----------------------------------------------------------------------===//
2413// Calling Convention Implementation
2414//===----------------------------------------------------------------------===//
2415
2416#include "AArch64GenCallingConv.inc"
2417
Robin Morisset039781e2014-08-29 21:53:01 +00002418/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002419CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2420 bool IsVarArg) const {
2421 switch (CC) {
2422 default:
2423 llvm_unreachable("Unsupported calling convention.");
2424 case CallingConv::WebKit_JS:
2425 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002426 case CallingConv::GHC:
2427 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002428 case CallingConv::C:
2429 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002430 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002431 case CallingConv::CXX_FAST_TLS:
Tim Northover3b0846e2014-05-24 12:50:23 +00002432 if (!Subtarget->isTargetDarwin())
2433 return CC_AArch64_AAPCS;
2434 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2435 }
2436}
2437
Tim Northover406024a2016-08-10 21:44:01 +00002438CCAssignFn *
2439AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2440 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2441 : RetCC_AArch64_AAPCS;
2442}
2443
Tim Northover3b0846e2014-05-24 12:50:23 +00002444SDValue AArch64TargetLowering::LowerFormalArguments(
2445 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002446 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2447 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002448 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002449 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002450
2451 // Assign locations to all of the incoming arguments.
2452 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002453 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2454 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002455
2456 // At this point, Ins[].VT may already be promoted to i32. To correctly
2457 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2458 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2459 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2460 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2461 // LocVT.
2462 unsigned NumArgs = Ins.size();
2463 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2464 unsigned CurArgIdx = 0;
2465 for (unsigned i = 0; i != NumArgs; ++i) {
2466 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002467 if (Ins[i].isOrigArg()) {
2468 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2469 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002470
Andrew Trick05938a52015-02-16 18:10:47 +00002471 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002472 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2473 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002474 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2475 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2476 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2477 ValVT = MVT::i8;
2478 else if (ActualMVT == MVT::i16)
2479 ValVT = MVT::i16;
2480 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002481 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2482 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002483 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002484 assert(!Res && "Call operand has unhandled type");
2485 (void)Res;
2486 }
2487 assert(ArgLocs.size() == Ins.size());
2488 SmallVector<SDValue, 16> ArgValues;
2489 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2490 CCValAssign &VA = ArgLocs[i];
2491
2492 if (Ins[i].Flags.isByVal()) {
2493 // Byval is used for HFAs in the PCS, but the system should work in a
2494 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002495 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002496 int Size = Ins[i].Flags.getByValSize();
2497 unsigned NumRegs = (Size + 7) / 8;
2498
2499 // FIXME: This works on big-endian for composite byvals, which are the common
2500 // case. It should also work for fundamental types too.
2501 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002502 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002503 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002504 InVals.push_back(FrameIdxN);
2505
2506 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002507 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002508
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002509 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002510 // Arguments stored in registers.
2511 EVT RegVT = VA.getLocVT();
2512
2513 SDValue ArgValue;
2514 const TargetRegisterClass *RC;
2515
2516 if (RegVT == MVT::i32)
2517 RC = &AArch64::GPR32RegClass;
2518 else if (RegVT == MVT::i64)
2519 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002520 else if (RegVT == MVT::f16)
2521 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002522 else if (RegVT == MVT::f32)
2523 RC = &AArch64::FPR32RegClass;
2524 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2525 RC = &AArch64::FPR64RegClass;
2526 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2527 RC = &AArch64::FPR128RegClass;
2528 else
2529 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2530
2531 // Transform the arguments in physical registers into virtual ones.
2532 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2533 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2534
2535 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2536 // to 64 bits. Insert an assert[sz]ext to capture this, then
2537 // truncate to the right size.
2538 switch (VA.getLocInfo()) {
2539 default:
2540 llvm_unreachable("Unknown loc info!");
2541 case CCValAssign::Full:
2542 break;
2543 case CCValAssign::BCvt:
2544 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2545 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002546 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002547 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002548 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002549 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2550 // nodes after our lowering.
2551 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002552 break;
2553 }
2554
2555 InVals.push_back(ArgValue);
2556
2557 } else { // VA.isRegLoc()
2558 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2559 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002560 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002561
2562 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002563 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2564 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002565 BEAlign = 8 - ArgSize;
2566
Matthias Braun941a7052016-07-28 18:40:00 +00002567 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002568
2569 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002570 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002571 SDValue ArgValue;
2572
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002573 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002574 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002575 MVT MemVT = VA.getValVT();
2576
Tim Northover47e003c2014-05-26 17:21:53 +00002577 switch (VA.getLocInfo()) {
2578 default:
2579 break;
Tim Northover6890add2014-06-03 13:54:53 +00002580 case CCValAssign::BCvt:
2581 MemVT = VA.getLocVT();
2582 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002583 case CCValAssign::SExt:
2584 ExtType = ISD::SEXTLOAD;
2585 break;
2586 case CCValAssign::ZExt:
2587 ExtType = ISD::ZEXTLOAD;
2588 break;
2589 case CCValAssign::AExt:
2590 ExtType = ISD::EXTLOAD;
2591 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002592 }
2593
Alex Lorenze40c8a22015-08-11 23:09:45 +00002594 ArgValue = DAG.getExtLoad(
2595 ExtType, DL, VA.getLocVT(), Chain, FIN,
2596 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002597 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002598
Tim Northover3b0846e2014-05-24 12:50:23 +00002599 InVals.push_back(ArgValue);
2600 }
2601 }
2602
2603 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002604 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002605 if (isVarArg) {
2606 if (!Subtarget->isTargetDarwin()) {
2607 // The AAPCS variadic function ABI is identical to the non-variadic
2608 // one. As a result there may be more arguments in registers and we should
2609 // save them for future reference.
2610 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2611 }
2612
Tim Northover3b0846e2014-05-24 12:50:23 +00002613 // This will point to the next argument passed via stack.
2614 unsigned StackOffset = CCInfo.getNextStackOffset();
2615 // We currently pass all varargs at 8-byte alignment.
2616 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002617 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002618 }
2619
Tim Northover3b0846e2014-05-24 12:50:23 +00002620 unsigned StackArgSize = CCInfo.getNextStackOffset();
2621 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2622 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2623 // This is a non-standard ABI so by fiat I say we're allowed to make full
2624 // use of the stack area to be popped, which must be aligned to 16 bytes in
2625 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002626 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002627
2628 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2629 // a multiple of 16.
2630 FuncInfo->setArgumentStackToRestore(StackArgSize);
2631
2632 // This realignment carries over to the available bytes below. Our own
2633 // callers will guarantee the space is free by giving an aligned value to
2634 // CALLSEQ_START.
2635 }
2636 // Even if we're not expected to free up the space, it's useful to know how
2637 // much is there while considering tail calls (because we can reuse it).
2638 FuncInfo->setBytesInStackArgArea(StackArgSize);
2639
2640 return Chain;
2641}
2642
2643void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002644 SelectionDAG &DAG,
2645 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002646 SDValue &Chain) const {
2647 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002648 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002649 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002650 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002651
2652 SmallVector<SDValue, 8> MemOps;
2653
2654 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2655 AArch64::X3, AArch64::X4, AArch64::X5,
2656 AArch64::X6, AArch64::X7 };
2657 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002658 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002659
2660 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2661 int GPRIdx = 0;
2662 if (GPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002663 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002664
Mehdi Amini44ede332015-07-09 02:09:04 +00002665 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002666
2667 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2668 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2669 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002670 SDValue Store = DAG.getStore(
2671 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002672 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002673 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002674 FIN =
2675 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002676 }
2677 }
2678 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2679 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2680
2681 if (Subtarget->hasFPARMv8()) {
2682 static const MCPhysReg FPRArgRegs[] = {
2683 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2684 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2685 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002686 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002687
2688 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2689 int FPRIdx = 0;
2690 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002691 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002692
Mehdi Amini44ede332015-07-09 02:09:04 +00002693 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002694
2695 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2696 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2697 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2698
Alex Lorenze40c8a22015-08-11 23:09:45 +00002699 SDValue Store = DAG.getStore(
2700 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002701 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00002702 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002703 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2704 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002705 }
2706 }
2707 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2708 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2709 }
2710
2711 if (!MemOps.empty()) {
2712 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2713 }
2714}
2715
2716/// LowerCallResult - Lower the result values of a call into the
2717/// appropriate copies out of appropriate physical registers.
2718SDValue AArch64TargetLowering::LowerCallResult(
2719 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002720 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2721 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002722 SDValue ThisVal) const {
2723 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2724 ? RetCC_AArch64_WebKit_JS
2725 : RetCC_AArch64_AAPCS;
2726 // Assign locations to each value returned by this call.
2727 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002728 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2729 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002730 CCInfo.AnalyzeCallResult(Ins, RetCC);
2731
2732 // Copy all of the result registers out of their specified physreg.
2733 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2734 CCValAssign VA = RVLocs[i];
2735
2736 // Pass 'this' value directly from the argument to return value, to avoid
2737 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00002738 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002739 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2740 "unexpected return calling convention register assignment");
2741 InVals.push_back(ThisVal);
2742 continue;
2743 }
2744
2745 SDValue Val =
2746 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2747 Chain = Val.getValue(1);
2748 InFlag = Val.getValue(2);
2749
2750 switch (VA.getLocInfo()) {
2751 default:
2752 llvm_unreachable("Unknown loc info!");
2753 case CCValAssign::Full:
2754 break;
2755 case CCValAssign::BCvt:
2756 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2757 break;
2758 }
2759
2760 InVals.push_back(Val);
2761 }
2762
2763 return Chain;
2764}
2765
2766bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2767 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00002768 const SmallVectorImpl<ISD::OutputArg> &Outs,
2769 const SmallVectorImpl<SDValue> &OutVals,
2770 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2771 // For CallingConv::C this function knows whether the ABI needs
2772 // changing. That's not true for other conventions so they will have to opt in
2773 // manually.
2774 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2775 return false;
2776
Matthias Braun8d414362016-03-30 22:46:04 +00002777 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002778 const Function *CallerF = MF.getFunction();
2779 CallingConv::ID CallerCC = CallerF->getCallingConv();
2780 bool CCMatch = CallerCC == CalleeCC;
2781
2782 // Byval parameters hand the function a pointer directly into the stack area
2783 // we want to reuse during a tail call. Working around this *is* possible (see
2784 // X86) but less efficient and uglier in LowerCall.
2785 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2786 e = CallerF->arg_end();
2787 i != e; ++i)
2788 if (i->hasByValAttr())
2789 return false;
2790
2791 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
Eric Christopher114fa1c2016-02-29 22:50:49 +00002792 return IsTailCallConvention(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002793 }
2794
Oliver Stannard12993dd2014-08-18 12:42:15 +00002795 // Externally-defined functions with weak linkage should not be
2796 // tail-called on AArch64 when the OS does not support dynamic
2797 // pre-emption of symbols, as the AAELF spec requires normal calls
2798 // to undefined weak functions to be replaced with a NOP or jump to the
2799 // next instruction. The behaviour of branch instructions in this
2800 // situation (as used for tail calls) is implementation-defined, so we
2801 // cannot rely on the linker replacing the tail call with a return.
2802 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2803 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002804 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002805 if (GV->hasExternalWeakLinkage() &&
2806 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002807 return false;
2808 }
2809
Tim Northover3b0846e2014-05-24 12:50:23 +00002810 // Now we search for cases where we can use a tail call without changing the
2811 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2812 // concept.
2813
2814 // I want anyone implementing a new calling convention to think long and hard
2815 // about this assert.
2816 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2817 "Unexpected variadic calling convention");
2818
Matthias Braun8d414362016-03-30 22:46:04 +00002819 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00002820 if (isVarArg && !Outs.empty()) {
2821 // At least two cases here: if caller is fastcc then we can't have any
2822 // memory arguments (we'd be expected to clean up the stack afterwards). If
2823 // caller is C then we could potentially use its argument area.
2824
2825 // FIXME: for now we take the most conservative of these in both cases:
2826 // disallow all variadic memory operands.
2827 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002828 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002829
2830 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002831 for (const CCValAssign &ArgLoc : ArgLocs)
2832 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002833 return false;
2834 }
2835
Matthias Braun8d414362016-03-30 22:46:04 +00002836 // Check that the call results are passed in the same way.
2837 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2838 CCAssignFnForCall(CalleeCC, isVarArg),
2839 CCAssignFnForCall(CallerCC, isVarArg)))
2840 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00002841 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00002842 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2843 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00002844 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00002845 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2846 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00002847 return false;
2848 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002849
2850 // Nothing more to check if the callee is taking no arguments
2851 if (Outs.empty())
2852 return true;
2853
2854 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002855 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002856
2857 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2858
2859 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2860
Matthias Braun74a0bd32016-04-13 21:43:16 +00002861 // If the stack arguments for this call do not fit into our own save area then
2862 // the call cannot be made tail.
2863 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2864 return false;
2865
Matthias Braun46b0f032016-04-14 01:10:42 +00002866 const MachineRegisterInfo &MRI = MF.getRegInfo();
2867 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2868 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00002869
2870 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00002871}
2872
2873SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2874 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00002875 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00002876 int ClobberedFI) const {
2877 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00002878 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2879 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002880
2881 // Include the original chain at the beginning of the list. When this is
2882 // used by target LowerCall hooks, this helps legalize find the
2883 // CALLSEQ_BEGIN node.
2884 ArgChains.push_back(Chain);
2885
2886 // Add a chain value for each stack argument corresponding
2887 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2888 UE = DAG.getEntryNode().getNode()->use_end();
2889 U != UE; ++U)
2890 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2891 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2892 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002893 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00002894 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00002895 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002896
2897 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2898 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2899 ArgChains.push_back(SDValue(L, 1));
2900 }
2901
2902 // Build a tokenfactor for all the chains.
2903 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2904}
2905
2906bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2907 bool TailCallOpt) const {
2908 return CallCC == CallingConv::Fast && TailCallOpt;
2909}
2910
2911bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002912 return CallCC == CallingConv::Fast ||
2913 CallCC == CallingConv::PreserveMost;
Tim Northover3b0846e2014-05-24 12:50:23 +00002914}
2915
2916/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2917/// and add input and output parameter nodes.
2918SDValue
2919AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2920 SmallVectorImpl<SDValue> &InVals) const {
2921 SelectionDAG &DAG = CLI.DAG;
2922 SDLoc &DL = CLI.DL;
2923 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2924 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2925 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2926 SDValue Chain = CLI.Chain;
2927 SDValue Callee = CLI.Callee;
2928 bool &IsTailCall = CLI.IsTailCall;
2929 CallingConv::ID CallConv = CLI.CallConv;
2930 bool IsVarArg = CLI.IsVarArg;
2931
2932 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002933 bool IsThisReturn = false;
2934
2935 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2936 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2937 bool IsSibCall = false;
2938
2939 if (IsTailCall) {
2940 // Check if it's really possible to do a tail call.
2941 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00002942 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002943 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2944 report_fatal_error("failed to perform tail call elimination on a call "
2945 "site marked musttail");
2946
2947 // A sibling call is one where we're under the usual C ABI and not planning
2948 // to change that but can still do a tail call:
2949 if (!TailCallOpt && IsTailCall)
2950 IsSibCall = true;
2951
2952 if (IsTailCall)
2953 ++NumTailCalls;
2954 }
2955
2956 // Analyze operands of the call, assigning locations to each operand.
2957 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002958 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2959 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002960
2961 if (IsVarArg) {
2962 // Handle fixed and variable vector arguments differently.
2963 // Variable vector arguments always go into memory.
2964 unsigned NumArgs = Outs.size();
2965
2966 for (unsigned i = 0; i != NumArgs; ++i) {
2967 MVT ArgVT = Outs[i].VT;
2968 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2969 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2970 /*IsVarArg=*/ !Outs[i].IsFixed);
2971 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2972 assert(!Res && "Call operand has unhandled type");
2973 (void)Res;
2974 }
2975 } else {
2976 // At this point, Outs[].VT may already be promoted to i32. To correctly
2977 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2978 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2979 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2980 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2981 // LocVT.
2982 unsigned NumArgs = Outs.size();
2983 for (unsigned i = 0; i != NumArgs; ++i) {
2984 MVT ValVT = Outs[i].VT;
2985 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002986 EVT ActualVT = getValueType(DAG.getDataLayout(),
2987 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002988 /*AllowUnknown*/ true);
2989 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2990 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2991 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002992 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002993 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002994 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002995 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002996
2997 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002998 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002999 assert(!Res && "Call operand has unhandled type");
3000 (void)Res;
3001 }
3002 }
3003
3004 // Get a count of how many bytes are to be pushed on the stack.
3005 unsigned NumBytes = CCInfo.getNextStackOffset();
3006
3007 if (IsSibCall) {
3008 // Since we're not changing the ABI to make this a tail call, the memory
3009 // operands are already available in the caller's incoming argument space.
3010 NumBytes = 0;
3011 }
3012
3013 // FPDiff is the byte offset of the call's argument area from the callee's.
3014 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3015 // by this amount for a tail call. In a sibling call it must be 0 because the
3016 // caller will deallocate the entire stack and the callee still expects its
3017 // arguments to begin at SP+0. Completely unused for non-tail calls.
3018 int FPDiff = 0;
3019
3020 if (IsTailCall && !IsSibCall) {
3021 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3022
3023 // Since callee will pop argument stack as a tail call, we must keep the
3024 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003025 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003026
3027 // FPDiff will be negative if this tail call requires more space than we
3028 // would automatically have in our incoming argument space. Positive if we
3029 // can actually shrink the stack.
3030 FPDiff = NumReusableBytes - NumBytes;
3031
3032 // The stack pointer must be 16-byte aligned at all times it's used for a
3033 // memory operation, which in practice means at *all* times and in
3034 // particular across call boundaries. Therefore our own arguments started at
3035 // a 16-byte aligned SP and the delta applied for the tail call should
3036 // satisfy the same constraint.
3037 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3038 }
3039
3040 // Adjust the stack pointer for the new arguments...
3041 // These operations are automatically eliminated by the prolog/epilog pass
3042 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003043 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3044 true),
3045 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003046
Mehdi Amini44ede332015-07-09 02:09:04 +00003047 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3048 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003049
3050 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3051 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003052 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003053
3054 // Walk the register/memloc assignments, inserting copies/loads.
3055 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3056 ++i, ++realArgIdx) {
3057 CCValAssign &VA = ArgLocs[i];
3058 SDValue Arg = OutVals[realArgIdx];
3059 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3060
3061 // Promote the value if needed.
3062 switch (VA.getLocInfo()) {
3063 default:
3064 llvm_unreachable("Unknown loc info!");
3065 case CCValAssign::Full:
3066 break;
3067 case CCValAssign::SExt:
3068 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3069 break;
3070 case CCValAssign::ZExt:
3071 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3072 break;
3073 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003074 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3075 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3076 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3077 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3078 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003079 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3080 break;
3081 case CCValAssign::BCvt:
3082 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3083 break;
3084 case CCValAssign::FPExt:
3085 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3086 break;
3087 }
3088
3089 if (VA.isRegLoc()) {
3090 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3091 assert(VA.getLocVT() == MVT::i64 &&
3092 "unexpected calling convention register assignment");
3093 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3094 "unexpected use of 'returned'");
3095 IsThisReturn = true;
3096 }
3097 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3098 } else {
3099 assert(VA.isMemLoc());
3100
3101 SDValue DstAddr;
3102 MachinePointerInfo DstInfo;
3103
3104 // FIXME: This works on big-endian for composite byvals, which are the
3105 // common case. It should also work for fundamental types too.
3106 uint32_t BEAlign = 0;
3107 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003108 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003109 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003110 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3111 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003112 if (OpSize < 8)
3113 BEAlign = 8 - OpSize;
3114 }
3115 unsigned LocMemOffset = VA.getLocMemOffset();
3116 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003117 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003118 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003119
3120 if (IsTailCall) {
3121 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003122 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003123
Mehdi Amini44ede332015-07-09 02:09:04 +00003124 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003125 DstInfo =
3126 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003127
3128 // Make sure any stack arguments overlapping with where we're storing
3129 // are loaded before this eventual operation. Otherwise they'll be
3130 // clobbered.
3131 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3132 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003133 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003134
Mehdi Amini44ede332015-07-09 02:09:04 +00003135 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003136 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3137 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003138 }
3139
3140 if (Outs[i].Flags.isByVal()) {
3141 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003142 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003143 SDValue Cpy = DAG.getMemcpy(
3144 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003145 /*isVol = */ false, /*AlwaysInline = */ false,
3146 /*isTailCall = */ false,
3147 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003148
3149 MemOpChains.push_back(Cpy);
3150 } else {
3151 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3152 // promoted to a legal register type i32, we should truncate Arg back to
3153 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003154 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3155 VA.getValVT() == MVT::i16)
3156 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003157
Justin Lebar9c375812016-07-15 18:27:10 +00003158 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003159 MemOpChains.push_back(Store);
3160 }
3161 }
3162 }
3163
3164 if (!MemOpChains.empty())
3165 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3166
3167 // Build a sequence of copy-to-reg nodes chained together with token chain
3168 // and flag operands which copy the outgoing args into the appropriate regs.
3169 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003170 for (auto &RegToPass : RegsToPass) {
3171 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3172 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003173 InFlag = Chain.getValue(1);
3174 }
3175
3176 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3177 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3178 // node so that legalize doesn't hack it.
3179 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3180 Subtarget->isTargetMachO()) {
3181 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3182 const GlobalValue *GV = G->getGlobal();
3183 bool InternalLinkage = GV->hasInternalLinkage();
3184 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003185 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003186 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003187 Callee =
3188 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3189 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003190 }
3191 } else if (ExternalSymbolSDNode *S =
3192 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3193 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003194 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3195 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003196 }
3197 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3198 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003199 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003200 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3201 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003202 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003203 }
3204
3205 // We don't usually want to end the call-sequence here because we would tidy
3206 // the frame up *after* the call, however in the ABI-changing tail-call case
3207 // we've carefully laid out the parameters so that when sp is reset they'll be
3208 // in the correct location.
3209 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003210 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3211 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003212 InFlag = Chain.getValue(1);
3213 }
3214
3215 std::vector<SDValue> Ops;
3216 Ops.push_back(Chain);
3217 Ops.push_back(Callee);
3218
3219 if (IsTailCall) {
3220 // Each tail call may have to adjust the stack by a different amount, so
3221 // this information must travel along with the operation for eventual
3222 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003223 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003224 }
3225
3226 // Add argument registers to the end of the list so that they are known live
3227 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003228 for (auto &RegToPass : RegsToPass)
3229 Ops.push_back(DAG.getRegister(RegToPass.first,
3230 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003231
3232 // Add a register mask operand representing the call-preserved registers.
3233 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003234 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003235 if (IsThisReturn) {
3236 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003237 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003238 if (!Mask) {
3239 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003240 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003241 }
3242 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003243 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003244
3245 assert(Mask && "Missing call preserved mask for calling convention");
3246 Ops.push_back(DAG.getRegisterMask(Mask));
3247
3248 if (InFlag.getNode())
3249 Ops.push_back(InFlag);
3250
3251 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3252
3253 // If we're doing a tall call, use a TC_RETURN here rather than an
3254 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003255 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003256 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003257 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003258 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003259
3260 // Returns a chain and a flag for retval copy to use.
3261 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3262 InFlag = Chain.getValue(1);
3263
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003264 uint64_t CalleePopBytes =
3265 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003266
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003267 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3268 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003269 InFlag, DL);
3270 if (!Ins.empty())
3271 InFlag = Chain.getValue(1);
3272
3273 // Handle result values, copying them out of physregs into vregs that we
3274 // return.
3275 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3276 InVals, IsThisReturn,
3277 IsThisReturn ? OutVals[0] : SDValue());
3278}
3279
3280bool AArch64TargetLowering::CanLowerReturn(
3281 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3282 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3283 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3284 ? RetCC_AArch64_WebKit_JS
3285 : RetCC_AArch64_AAPCS;
3286 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003287 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003288 return CCInfo.CheckReturn(Outs, RetCC);
3289}
3290
3291SDValue
3292AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3293 bool isVarArg,
3294 const SmallVectorImpl<ISD::OutputArg> &Outs,
3295 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003296 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003297 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3298 ? RetCC_AArch64_WebKit_JS
3299 : RetCC_AArch64_AAPCS;
3300 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003301 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3302 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003303 CCInfo.AnalyzeReturn(Outs, RetCC);
3304
3305 // Copy the result values into the output registers.
3306 SDValue Flag;
3307 SmallVector<SDValue, 4> RetOps(1, Chain);
3308 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3309 ++i, ++realRVLocIdx) {
3310 CCValAssign &VA = RVLocs[i];
3311 assert(VA.isRegLoc() && "Can only return in registers!");
3312 SDValue Arg = OutVals[realRVLocIdx];
3313
3314 switch (VA.getLocInfo()) {
3315 default:
3316 llvm_unreachable("Unknown loc info!");
3317 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003318 if (Outs[i].ArgVT == MVT::i1) {
3319 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3320 // value. This is strictly redundant on Darwin (which uses "zeroext
3321 // i1"), but will be optimised out before ISel.
3322 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3323 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3324 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003325 break;
3326 case CCValAssign::BCvt:
3327 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3328 break;
3329 }
3330
3331 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3332 Flag = Chain.getValue(1);
3333 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3334 }
Manman Rencbe4f942015-12-16 21:04:19 +00003335 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3336 const MCPhysReg *I =
3337 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3338 if (I) {
3339 for (; *I; ++I) {
3340 if (AArch64::GPR64RegClass.contains(*I))
3341 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3342 else if (AArch64::FPR64RegClass.contains(*I))
3343 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3344 else
3345 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3346 }
3347 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003348
3349 RetOps[0] = Chain; // Update chain.
3350
3351 // Add the flag if we have it.
3352 if (Flag.getNode())
3353 RetOps.push_back(Flag);
3354
3355 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3356}
3357
3358//===----------------------------------------------------------------------===//
3359// Other Lowering Code
3360//===----------------------------------------------------------------------===//
3361
3362SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3363 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003364 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003365 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003366 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3367 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003368 unsigned char OpFlags =
3369 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3370
3371 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3372 "unexpected offset in global node");
3373
3374 // This also catched the large code model case for Darwin.
3375 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3376 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3377 // FIXME: Once remat is capable of dealing with instructions with register
3378 // operands, expand this into two nodes instead of using a wrapper node.
3379 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3380 }
3381
3382 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3383 const unsigned char MO_NC = AArch64II::MO_NC;
3384 return DAG.getNode(
3385 AArch64ISD::WrapperLarge, DL, PtrVT,
3386 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3387 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3388 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3389 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3390 } else {
3391 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3392 // the only correct model on Darwin.
3393 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3394 OpFlags | AArch64II::MO_PAGE);
3395 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3396 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3397
3398 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3399 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3400 }
3401}
3402
3403/// \brief Convert a TLS address reference into the correct sequence of loads
3404/// and calls to compute the variable's address (for Darwin, currently) and
3405/// return an SDValue containing the final node.
3406
3407/// Darwin only has one TLS scheme which must be capable of dealing with the
3408/// fully general situation, in the worst case. This means:
3409/// + "extern __thread" declaration.
3410/// + Defined in a possibly unknown dynamic library.
3411///
3412/// The general system is that each __thread variable has a [3 x i64] descriptor
3413/// which contains information used by the runtime to calculate the address. The
3414/// only part of this the compiler needs to know about is the first xword, which
3415/// contains a function pointer that must be called with the address of the
3416/// entire descriptor in "x0".
3417///
3418/// Since this descriptor may be in a different unit, in general even the
3419/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3420/// is:
3421/// adrp x0, _var@TLVPPAGE
3422/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3423/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3424/// ; the function pointer
3425/// blr x1 ; Uses descriptor address in x0
3426/// ; Address of _var is now in x0.
3427///
3428/// If the address of _var's descriptor *is* known to the linker, then it can
3429/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3430/// a slight efficiency gain.
3431SDValue
3432AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3433 SelectionDAG &DAG) const {
3434 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3435
3436 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003437 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003438 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3439
3440 SDValue TLVPAddr =
3441 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3442 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3443
3444 // The first entry in the descriptor is a function pointer that we must call
3445 // to obtain the address of the variable.
3446 SDValue Chain = DAG.getEntryNode();
3447 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003448 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00003449 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3450 /* Alignment = */ 8, MachineMemOperand::MONonTemporal |
3451 MachineMemOperand::MOInvariant);
Tim Northover3b0846e2014-05-24 12:50:23 +00003452 Chain = FuncTLVGet.getValue(1);
3453
Matthias Braun941a7052016-07-28 18:40:00 +00003454 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3455 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003456
3457 // TLS calls preserve all registers except those that absolutely must be
3458 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3459 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003460 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003461 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003462
3463 // Finally, we can make the call. This is just a degenerate version of a
3464 // normal AArch64 call node: x0 takes the address of the descriptor, and
3465 // returns the address of the variable in this thread.
3466 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3467 Chain =
3468 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3469 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3470 DAG.getRegisterMask(Mask), Chain.getValue(1));
3471 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3472}
3473
3474/// When accessing thread-local variables under either the general-dynamic or
3475/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3476/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003477/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003478///
Kristof Beylsaea84612015-03-04 09:12:08 +00003479/// The sequence is:
3480/// adrp x0, :tlsdesc:var
3481/// ldr x1, [x0, #:tlsdesc_lo12:var]
3482/// add x0, x0, #:tlsdesc_lo12:var
3483/// .tlsdesccall var
3484/// blr x1
3485/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003486///
Kristof Beylsaea84612015-03-04 09:12:08 +00003487/// The above sequence must be produced unscheduled, to enable the linker to
3488/// optimize/relax this sequence.
3489/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3490/// above sequence, and expanded really late in the compilation flow, to ensure
3491/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003492SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3493 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003494 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003495 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003496
Kristof Beylsaea84612015-03-04 09:12:08 +00003497 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003498 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003499
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003500 Chain =
3501 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003502 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003503
3504 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3505}
3506
3507SDValue
3508AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3509 SelectionDAG &DAG) const {
3510 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3511 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3512 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003513 // Different choices can be made for the maximum size of the TLS area for a
3514 // module. For the small address model, the default TLS size is 16MiB and the
3515 // maximum TLS size is 4GiB.
3516 // FIXME: add -mtls-size command line option and make it control the 16MiB
3517 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003518 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3519
3520 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003521
3522 if (DAG.getTarget().Options.EmulatedTLS)
3523 return LowerToTLSEmulatedModel(GA, DAG);
3524
Kristof Beylsaea84612015-03-04 09:12:08 +00003525 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3526 if (Model == TLSModel::LocalDynamic)
3527 Model = TLSModel::GeneralDynamic;
3528 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003529
3530 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003531 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003532 SDLoc DL(Op);
3533 const GlobalValue *GV = GA->getGlobal();
3534
3535 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3536
3537 if (Model == TLSModel::LocalExec) {
3538 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003539 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003540 SDValue LoVar = DAG.getTargetGlobalAddress(
3541 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003542 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003543
Kristof Beylsaea84612015-03-04 09:12:08 +00003544 SDValue TPWithOff_lo =
3545 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003546 HiVar,
3547 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003548 0);
3549 SDValue TPWithOff =
3550 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003551 LoVar,
3552 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003553 0);
3554 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003555 } else if (Model == TLSModel::InitialExec) {
3556 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3557 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3558 } else if (Model == TLSModel::LocalDynamic) {
3559 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3560 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3561 // the beginning of the module's TLS region, followed by a DTPREL offset
3562 // calculation.
3563
3564 // These accesses will need deduplicating if there's more than one.
3565 AArch64FunctionInfo *MFI =
3566 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3567 MFI->incNumLocalDynamicTLSAccesses();
3568
Tim Northover3b0846e2014-05-24 12:50:23 +00003569 // The call needs a relocation too for linker relaxation. It doesn't make
3570 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3571 // the address.
3572 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3573 AArch64II::MO_TLS);
3574
3575 // Now we can calculate the offset from TPIDR_EL0 to this module's
3576 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003577 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003578
3579 // Now use :dtprel_whatever: operations to calculate this variable's offset
3580 // in its thread-storage area.
3581 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003582 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003583 SDValue LoVar = DAG.getTargetGlobalAddress(
3584 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003585 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3586
Kristof Beylsaea84612015-03-04 09:12:08 +00003587 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003588 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003589 0);
3590 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003591 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003592 0);
3593 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003594 // The call needs a relocation too for linker relaxation. It doesn't make
3595 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3596 // the address.
3597 SDValue SymAddr =
3598 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3599
3600 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003601 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003602 } else
3603 llvm_unreachable("Unsupported ELF TLS access model");
3604
3605 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3606}
3607
3608SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3609 SelectionDAG &DAG) const {
3610 if (Subtarget->isTargetDarwin())
3611 return LowerDarwinGlobalTLSAddress(Op, DAG);
3612 else if (Subtarget->isTargetELF())
3613 return LowerELFGlobalTLSAddress(Op, DAG);
3614
3615 llvm_unreachable("Unexpected platform trying to use TLS");
3616}
3617SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3618 SDValue Chain = Op.getOperand(0);
3619 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3620 SDValue LHS = Op.getOperand(2);
3621 SDValue RHS = Op.getOperand(3);
3622 SDValue Dest = Op.getOperand(4);
3623 SDLoc dl(Op);
3624
3625 // Handle f128 first, since lowering it will result in comparing the return
3626 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3627 // is expecting to deal with.
3628 if (LHS.getValueType() == MVT::f128) {
3629 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3630
3631 // If softenSetCCOperands returned a scalar, we need to compare the result
3632 // against zero to select between true and false values.
3633 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003634 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003635 CC = ISD::SETNE;
3636 }
3637 }
3638
3639 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3640 // instruction.
3641 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003642 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003643 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3644 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3645 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3646 "Unexpected condition code.");
3647 // Only lower legal XALUO ops.
3648 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3649 return SDValue();
3650
3651 // The actual operation with overflow check.
3652 AArch64CC::CondCode OFCC;
3653 SDValue Value, Overflow;
3654 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3655
3656 if (CC == ISD::SETNE)
3657 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003658 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003659
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003660 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3661 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003662 }
3663
3664 if (LHS.getValueType().isInteger()) {
3665 assert((LHS.getValueType() == RHS.getValueType()) &&
3666 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3667
3668 // If the RHS of the comparison is zero, we can potentially fold this
3669 // to a specialized branch.
3670 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3671 if (RHSC && RHSC->getZExtValue() == 0) {
3672 if (CC == ISD::SETEQ) {
3673 // See if we can use a TBZ to fold in an AND as well.
3674 // TBZ has a smaller branch displacement than CBZ. If the offset is
3675 // out of bounds, a late MI-layer pass rewrites branches.
3676 // 403.gcc is an example that hits this case.
3677 if (LHS.getOpcode() == ISD::AND &&
3678 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3679 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3680 SDValue Test = LHS.getOperand(0);
3681 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003682 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003683 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3684 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003685 }
3686
3687 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3688 } else if (CC == ISD::SETNE) {
3689 // See if we can use a TBZ to fold in an AND as well.
3690 // TBZ has a smaller branch displacement than CBZ. If the offset is
3691 // out of bounds, a late MI-layer pass rewrites branches.
3692 // 403.gcc is an example that hits this case.
3693 if (LHS.getOpcode() == ISD::AND &&
3694 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3695 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3696 SDValue Test = LHS.getOperand(0);
3697 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003698 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003699 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3700 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003701 }
3702
3703 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003704 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3705 // Don't combine AND since emitComparison converts the AND to an ANDS
3706 // (a.k.a. TST) and the test in the test bit and branch instruction
3707 // becomes redundant. This would also increase register pressure.
3708 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3709 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003710 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003711 }
3712 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003713 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3714 LHS.getOpcode() != ISD::AND) {
3715 // Don't combine AND since emitComparison converts the AND to an ANDS
3716 // (a.k.a. TST) and the test in the test bit and branch instruction
3717 // becomes redundant. This would also increase register pressure.
3718 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3719 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003720 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003721 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003722
3723 SDValue CCVal;
3724 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3725 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3726 Cmp);
3727 }
3728
3729 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3730
3731 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3732 // clean. Some of them require two branches to implement.
3733 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3734 AArch64CC::CondCode CC1, CC2;
3735 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003736 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003737 SDValue BR1 =
3738 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3739 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003740 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003741 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3742 Cmp);
3743 }
3744
3745 return BR1;
3746}
3747
3748SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3749 SelectionDAG &DAG) const {
3750 EVT VT = Op.getValueType();
3751 SDLoc DL(Op);
3752
3753 SDValue In1 = Op.getOperand(0);
3754 SDValue In2 = Op.getOperand(1);
3755 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003756
3757 if (SrcVT.bitsLT(VT))
3758 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3759 else if (SrcVT.bitsGT(VT))
3760 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003761
3762 EVT VecVT;
3763 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003764 uint64_t EltMask;
3765 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003766 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3767 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003768 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003769 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003770
3771 if (!VT.isVector()) {
3772 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3773 DAG.getUNDEF(VecVT), In1);
3774 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3775 DAG.getUNDEF(VecVT), In2);
3776 } else {
3777 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3778 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3779 }
3780 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3781 EltVT = MVT::i64;
3782 VecVT = MVT::v2i64;
3783
Eric Christopher572e03a2015-06-19 01:53:21 +00003784 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003785 // immediate moves cannot materialize that in a single instruction for
3786 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003787 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003788
3789 if (!VT.isVector()) {
3790 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3791 DAG.getUNDEF(VecVT), In1);
3792 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3793 DAG.getUNDEF(VecVT), In2);
3794 } else {
3795 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3796 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3797 }
3798 } else {
3799 llvm_unreachable("Invalid type for copysign!");
3800 }
3801
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003802 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003803
3804 // If we couldn't materialize the mask above, then the mask vector will be
3805 // the zero vector, and we need to negate it here.
3806 if (VT == MVT::f64 || VT == MVT::v2f64) {
3807 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3808 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3809 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3810 }
3811
3812 SDValue Sel =
3813 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3814
3815 if (VT == MVT::f32)
3816 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3817 else if (VT == MVT::f64)
3818 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3819 else
3820 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3821}
3822
3823SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003824 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3825 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003826 return SDValue();
3827
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003828 if (!Subtarget->hasNEON())
3829 return SDValue();
3830
Tim Northover3b0846e2014-05-24 12:50:23 +00003831 // While there is no integer popcount instruction, it can
3832 // be more efficiently lowered to the following sequence that uses
3833 // AdvSIMD registers/instructions as long as the copies to/from
3834 // the AdvSIMD registers are cheap.
3835 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3836 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3837 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3838 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3839 SDValue Val = Op.getOperand(0);
3840 SDLoc DL(Op);
3841 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003842
Hao Liue0335d72015-01-30 02:13:53 +00003843 if (VT == MVT::i32)
3844 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3845 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003846
Hao Liue0335d72015-01-30 02:13:53 +00003847 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003848 SDValue UaddLV = DAG.getNode(
3849 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003850 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003851
3852 if (VT == MVT::i64)
3853 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3854 return UaddLV;
3855}
3856
3857SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3858
3859 if (Op.getValueType().isVector())
3860 return LowerVSETCC(Op, DAG);
3861
3862 SDValue LHS = Op.getOperand(0);
3863 SDValue RHS = Op.getOperand(1);
3864 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3865 SDLoc dl(Op);
3866
3867 // We chose ZeroOrOneBooleanContents, so use zero and one.
3868 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003869 SDValue TVal = DAG.getConstant(1, dl, VT);
3870 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003871
3872 // Handle f128 first, since one possible outcome is a normal integer
3873 // comparison which gets picked up by the next if statement.
3874 if (LHS.getValueType() == MVT::f128) {
3875 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3876
3877 // If softenSetCCOperands returned a scalar, use it.
3878 if (!RHS.getNode()) {
3879 assert(LHS.getValueType() == Op.getValueType() &&
3880 "Unexpected setcc expansion!");
3881 return LHS;
3882 }
3883 }
3884
3885 if (LHS.getValueType().isInteger()) {
3886 SDValue CCVal;
3887 SDValue Cmp =
3888 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3889
3890 // Note that we inverted the condition above, so we reverse the order of
3891 // the true and false operands here. This will allow the setcc to be
3892 // matched to a single CSINC instruction.
3893 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3894 }
3895
3896 // Now we know we're dealing with FP values.
3897 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3898
3899 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3900 // and do the comparison.
3901 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3902
3903 AArch64CC::CondCode CC1, CC2;
3904 changeFPCCToAArch64CC(CC, CC1, CC2);
3905 if (CC2 == AArch64CC::AL) {
3906 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003907 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003908
3909 // Note that we inverted the condition above, so we reverse the order of
3910 // the true and false operands here. This will allow the setcc to be
3911 // matched to a single CSINC instruction.
3912 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3913 } else {
3914 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3915 // totally clean. Some of them require two CSELs to implement. As is in
3916 // this case, we emit the first CSEL and then emit a second using the output
3917 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3918
3919 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003920 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003921 SDValue CS1 =
3922 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3923
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003924 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003925 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3926 }
3927}
3928
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003929SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3930 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003931 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003932 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003933 // Handle f128 first, because it will result in a comparison of some RTLIB
3934 // call result against zero.
3935 if (LHS.getValueType() == MVT::f128) {
3936 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3937
3938 // If softenSetCCOperands returned a scalar, we need to compare the result
3939 // against zero to select between true and false values.
3940 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003941 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003942 CC = ISD::SETNE;
3943 }
3944 }
3945
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003946 // Also handle f16, for which we need to do a f32 comparison.
3947 if (LHS.getValueType() == MVT::f16) {
3948 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3949 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3950 }
3951
3952 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003953 if (LHS.getValueType().isInteger()) {
3954 assert((LHS.getValueType() == RHS.getValueType()) &&
3955 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3956
3957 unsigned Opcode = AArch64ISD::CSEL;
3958
3959 // If both the TVal and the FVal are constants, see if we can swap them in
3960 // order to for a CSINV or CSINC out of them.
3961 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3962 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3963
3964 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3965 std::swap(TVal, FVal);
3966 std::swap(CTVal, CFVal);
3967 CC = ISD::getSetCCInverse(CC, true);
3968 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3969 std::swap(TVal, FVal);
3970 std::swap(CTVal, CFVal);
3971 CC = ISD::getSetCCInverse(CC, true);
3972 } else if (TVal.getOpcode() == ISD::XOR) {
3973 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3974 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003975 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003976 std::swap(TVal, FVal);
3977 std::swap(CTVal, CFVal);
3978 CC = ISD::getSetCCInverse(CC, true);
3979 }
3980 } else if (TVal.getOpcode() == ISD::SUB) {
3981 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3982 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003983 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003984 std::swap(TVal, FVal);
3985 std::swap(CTVal, CFVal);
3986 CC = ISD::getSetCCInverse(CC, true);
3987 }
3988 } else if (CTVal && CFVal) {
3989 const int64_t TrueVal = CTVal->getSExtValue();
3990 const int64_t FalseVal = CFVal->getSExtValue();
3991 bool Swap = false;
3992
3993 // If both TVal and FVal are constants, see if FVal is the
3994 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3995 // instead of a CSEL in that case.
3996 if (TrueVal == ~FalseVal) {
3997 Opcode = AArch64ISD::CSINV;
3998 } else if (TrueVal == -FalseVal) {
3999 Opcode = AArch64ISD::CSNEG;
4000 } else if (TVal.getValueType() == MVT::i32) {
4001 // If our operands are only 32-bit wide, make sure we use 32-bit
4002 // arithmetic for the check whether we can use CSINC. This ensures that
4003 // the addition in the check will wrap around properly in case there is
4004 // an overflow (which would not be the case if we do the check with
4005 // 64-bit arithmetic).
4006 const uint32_t TrueVal32 = CTVal->getZExtValue();
4007 const uint32_t FalseVal32 = CFVal->getZExtValue();
4008
4009 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4010 Opcode = AArch64ISD::CSINC;
4011
4012 if (TrueVal32 > FalseVal32) {
4013 Swap = true;
4014 }
4015 }
4016 // 64-bit check whether we can use CSINC.
4017 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4018 Opcode = AArch64ISD::CSINC;
4019
4020 if (TrueVal > FalseVal) {
4021 Swap = true;
4022 }
4023 }
4024
4025 // Swap TVal and FVal if necessary.
4026 if (Swap) {
4027 std::swap(TVal, FVal);
4028 std::swap(CTVal, CFVal);
4029 CC = ISD::getSetCCInverse(CC, true);
4030 }
4031
4032 if (Opcode != AArch64ISD::CSEL) {
4033 // Drop FVal since we can get its value by simply inverting/negating
4034 // TVal.
4035 FVal = TVal;
4036 }
4037 }
4038
Chad Rosier58f505b2016-08-26 18:05:50 +00004039 // Avoid materializing a constant when possible by reusing a known value in
4040 // a register. However, don't perform this optimization if the known value
4041 // is one, zero or negative one. We can always materialize these values
4042 // using CSINC, CSEL and CSINV with wzr/xzr as the FVal, respectively.
4043 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4044 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4045 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4046 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4047 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4048 // "a != C ? x : a" to avoid materializing C.
4049 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4050 TVal = LHS;
4051 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4052 FVal = LHS;
4053 }
4054
Tim Northover3b0846e2014-05-24 12:50:23 +00004055 SDValue CCVal;
4056 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4057
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004058 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004059 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4060 }
4061
4062 // Now we know we're dealing with FP values.
4063 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4064 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004065 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004066 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4067
4068 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4069 // clean. Some of them require two CSELs to implement.
4070 AArch64CC::CondCode CC1, CC2;
4071 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004072 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004073 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4074
4075 // If we need a second CSEL, emit it, using the output of the first as the
4076 // RHS. We're effectively OR'ing the two CC's together.
4077 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004078 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004079 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4080 }
4081
4082 // Otherwise, return the output of the first CSEL.
4083 return CS1;
4084}
4085
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004086SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4087 SelectionDAG &DAG) const {
4088 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4089 SDValue LHS = Op.getOperand(0);
4090 SDValue RHS = Op.getOperand(1);
4091 SDValue TVal = Op.getOperand(2);
4092 SDValue FVal = Op.getOperand(3);
4093 SDLoc DL(Op);
4094 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4095}
4096
4097SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4098 SelectionDAG &DAG) const {
4099 SDValue CCVal = Op->getOperand(0);
4100 SDValue TVal = Op->getOperand(1);
4101 SDValue FVal = Op->getOperand(2);
4102 SDLoc DL(Op);
4103
4104 unsigned Opc = CCVal.getOpcode();
4105 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4106 // instruction.
4107 if (CCVal.getResNo() == 1 &&
4108 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4109 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4110 // Only lower legal XALUO ops.
4111 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4112 return SDValue();
4113
4114 AArch64CC::CondCode OFCC;
4115 SDValue Value, Overflow;
4116 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004117 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004118
4119 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4120 CCVal, Overflow);
4121 }
4122
4123 // Lower it the same way as we would lower a SELECT_CC node.
4124 ISD::CondCode CC;
4125 SDValue LHS, RHS;
4126 if (CCVal.getOpcode() == ISD::SETCC) {
4127 LHS = CCVal.getOperand(0);
4128 RHS = CCVal.getOperand(1);
4129 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4130 } else {
4131 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004132 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004133 CC = ISD::SETNE;
4134 }
4135 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4136}
4137
Tim Northover3b0846e2014-05-24 12:50:23 +00004138SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4139 SelectionDAG &DAG) const {
4140 // Jump table entries as PC relative offsets. No additional tweaking
4141 // is necessary here. Just get the address of the jump table.
4142 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004143 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004144 SDLoc DL(Op);
4145
4146 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4147 !Subtarget->isTargetMachO()) {
4148 const unsigned char MO_NC = AArch64II::MO_NC;
4149 return DAG.getNode(
4150 AArch64ISD::WrapperLarge, DL, PtrVT,
4151 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4152 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4153 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4154 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4155 AArch64II::MO_G0 | MO_NC));
4156 }
4157
4158 SDValue Hi =
4159 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4160 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4161 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4162 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4163 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4164}
4165
4166SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4167 SelectionDAG &DAG) const {
4168 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004169 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004170 SDLoc DL(Op);
4171
4172 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4173 // Use the GOT for the large code model on iOS.
4174 if (Subtarget->isTargetMachO()) {
4175 SDValue GotAddr = DAG.getTargetConstantPool(
4176 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4177 AArch64II::MO_GOT);
4178 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4179 }
4180
4181 const unsigned char MO_NC = AArch64II::MO_NC;
4182 return DAG.getNode(
4183 AArch64ISD::WrapperLarge, DL, PtrVT,
4184 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4185 CP->getOffset(), AArch64II::MO_G3),
4186 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4187 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4188 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4189 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4190 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4191 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4192 } else {
4193 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4194 // ELF, the only valid one on Darwin.
4195 SDValue Hi =
4196 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4197 CP->getOffset(), AArch64II::MO_PAGE);
4198 SDValue Lo = DAG.getTargetConstantPool(
4199 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4200 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4201
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::LowerBlockAddress(SDValue Op,
4208 SelectionDAG &DAG) const {
4209 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004210 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004211 SDLoc DL(Op);
4212 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4213 !Subtarget->isTargetMachO()) {
4214 const unsigned char MO_NC = AArch64II::MO_NC;
4215 return DAG.getNode(
4216 AArch64ISD::WrapperLarge, DL, PtrVT,
4217 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4218 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4219 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4220 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4221 } else {
4222 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4223 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4224 AArch64II::MO_NC);
4225 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4226 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4227 }
4228}
4229
4230SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4231 SelectionDAG &DAG) const {
4232 AArch64FunctionInfo *FuncInfo =
4233 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4234
4235 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004236 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4237 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004238 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4239 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004240 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004241}
4242
4243SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4244 SelectionDAG &DAG) const {
4245 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4246 // Standard, section B.3.
4247 MachineFunction &MF = DAG.getMachineFunction();
4248 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004249 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004250 SDLoc DL(Op);
4251
4252 SDValue Chain = Op.getOperand(0);
4253 SDValue VAList = Op.getOperand(1);
4254 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4255 SmallVector<SDValue, 4> MemOps;
4256
4257 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004258 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004259 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004260 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004261
4262 // void *__gr_top at offset 8
4263 int GPRSize = FuncInfo->getVarArgsGPRSize();
4264 if (GPRSize > 0) {
4265 SDValue GRTop, GRTopAddr;
4266
Mehdi Amini44ede332015-07-09 02:09:04 +00004267 GRTopAddr =
4268 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004269
Mehdi Amini44ede332015-07-09 02:09:04 +00004270 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4271 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4272 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004273
4274 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004275 MachinePointerInfo(SV, 8),
4276 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004277 }
4278
4279 // void *__vr_top at offset 16
4280 int FPRSize = FuncInfo->getVarArgsFPRSize();
4281 if (FPRSize > 0) {
4282 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004283 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4284 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004285
Mehdi Amini44ede332015-07-09 02:09:04 +00004286 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4287 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4288 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004289
4290 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004291 MachinePointerInfo(SV, 16),
4292 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004293 }
4294
4295 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004296 SDValue GROffsAddr =
4297 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004298 MemOps.push_back(DAG.getStore(
4299 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4300 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004301
4302 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004303 SDValue VROffsAddr =
4304 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004305 MemOps.push_back(DAG.getStore(
4306 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4307 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004308
4309 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4310}
4311
4312SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4313 SelectionDAG &DAG) const {
4314 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4315 : LowerAAPCS_VASTART(Op, DAG);
4316}
4317
4318SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4319 SelectionDAG &DAG) const {
4320 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4321 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004322 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004323 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4324 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4325 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4326
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004327 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4328 Op.getOperand(2),
4329 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004330 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004331 MachinePointerInfo(SrcSV));
4332}
4333
4334SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4335 assert(Subtarget->isTargetDarwin() &&
4336 "automatic va_arg instruction only works on Darwin");
4337
4338 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4339 EVT VT = Op.getValueType();
4340 SDLoc DL(Op);
4341 SDValue Chain = Op.getOperand(0);
4342 SDValue Addr = Op.getOperand(1);
4343 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004344 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004345
Justin Lebar9c375812016-07-15 18:27:10 +00004346 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004347 Chain = VAList.getValue(1);
4348
4349 if (Align > 8) {
4350 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004351 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4352 DAG.getConstant(Align - 1, DL, PtrVT));
4353 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4354 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004355 }
4356
4357 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004358 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004359
4360 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4361 // up to 64 bits. At the very least, we have to increase the striding of the
4362 // vaargs list to match this, and for FP values we need to introduce
4363 // FP_ROUND nodes as well.
4364 if (VT.isInteger() && !VT.isVector())
4365 ArgSize = 8;
4366 bool NeedFPTrunc = false;
4367 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4368 ArgSize = 8;
4369 NeedFPTrunc = true;
4370 }
4371
4372 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004373 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4374 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004375 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004376 SDValue APStore =
4377 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004378
4379 // Load the actual argument out of the pointer VAList
4380 if (NeedFPTrunc) {
4381 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004382 SDValue WideFP =
4383 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004384 // Round the value down to an f32.
4385 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004386 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004387 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4388 // Merge the rounded value with the chain output of the load.
4389 return DAG.getMergeValues(Ops, DL);
4390 }
4391
Justin Lebar9c375812016-07-15 18:27:10 +00004392 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004393}
4394
4395SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4396 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004397 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4398 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004399
4400 EVT VT = Op.getValueType();
4401 SDLoc DL(Op);
4402 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4403 SDValue FrameAddr =
4404 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4405 while (Depth--)
4406 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004407 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004408 return FrameAddr;
4409}
4410
4411// FIXME? Maybe this could be a TableGen attribute on some registers and
4412// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004413unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4414 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004415 unsigned Reg = StringSwitch<unsigned>(RegName)
4416 .Case("sp", AArch64::SP)
4417 .Default(0);
4418 if (Reg)
4419 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004420 report_fatal_error(Twine("Invalid register name \""
4421 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004422}
4423
4424SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4425 SelectionDAG &DAG) const {
4426 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004427 MachineFrameInfo &MFI = MF.getFrameInfo();
4428 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004429
4430 EVT VT = Op.getValueType();
4431 SDLoc DL(Op);
4432 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4433 if (Depth) {
4434 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004435 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004436 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4437 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004438 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004439 }
4440
4441 // Return LR, which contains the return address. Mark it an implicit live-in.
4442 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4443 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4444}
4445
4446/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4447/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4448SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4449 SelectionDAG &DAG) const {
4450 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4451 EVT VT = Op.getValueType();
4452 unsigned VTBits = VT.getSizeInBits();
4453 SDLoc dl(Op);
4454 SDValue ShOpLo = Op.getOperand(0);
4455 SDValue ShOpHi = Op.getOperand(1);
4456 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004457 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4458
4459 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4460
4461 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004462 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004463 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4464
4465 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4466 // is "undef". We wanted 0, so CSEL it directly.
4467 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4468 ISD::SETEQ, dl, DAG);
4469 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4470 HiBitsForLo =
4471 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4472 HiBitsForLo, CCVal, Cmp);
4473
Tim Northover3b0846e2014-05-24 12:50:23 +00004474 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004475 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004476
Tim Northoverf3be9d52015-12-02 00:33:54 +00004477 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4478 SDValue LoForNormalShift =
4479 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004480
Tim Northoverf3be9d52015-12-02 00:33:54 +00004481 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4482 dl, DAG);
4483 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4484 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4485 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4486 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004487
4488 // AArch64 shifts larger than the register width are wrapped rather than
4489 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004490 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4491 SDValue HiForBigShift =
4492 Opc == ISD::SRA
4493 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4494 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4495 : DAG.getConstant(0, dl, VT);
4496 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4497 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004498
4499 SDValue Ops[2] = { Lo, Hi };
4500 return DAG.getMergeValues(Ops, dl);
4501}
4502
Tim Northoverf3be9d52015-12-02 00:33:54 +00004503
Tim Northover3b0846e2014-05-24 12:50:23 +00004504/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4505/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4506SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004507 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004508 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4509 EVT VT = Op.getValueType();
4510 unsigned VTBits = VT.getSizeInBits();
4511 SDLoc dl(Op);
4512 SDValue ShOpLo = Op.getOperand(0);
4513 SDValue ShOpHi = Op.getOperand(1);
4514 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004515
4516 assert(Op.getOpcode() == ISD::SHL_PARTS);
4517 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004518 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004519 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4520
4521 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4522 // is "undef". We wanted 0, so CSEL it directly.
4523 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4524 ISD::SETEQ, dl, DAG);
4525 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4526 LoBitsForHi =
4527 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4528 LoBitsForHi, CCVal, Cmp);
4529
Tim Northover3b0846e2014-05-24 12:50:23 +00004530 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004531 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004532 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4533 SDValue HiForNormalShift =
4534 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004535
Tim Northoverf3be9d52015-12-02 00:33:54 +00004536 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004537
Tim Northoverf3be9d52015-12-02 00:33:54 +00004538 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4539 dl, DAG);
4540 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4541 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4542 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004543
4544 // AArch64 shifts of larger than register sizes are wrapped rather than
4545 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004546 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4547 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4548 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4549 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004550
4551 SDValue Ops[2] = { Lo, Hi };
4552 return DAG.getMergeValues(Ops, dl);
4553}
4554
4555bool AArch64TargetLowering::isOffsetFoldingLegal(
4556 const GlobalAddressSDNode *GA) const {
4557 // The AArch64 target doesn't support folding offsets into global addresses.
4558 return false;
4559}
4560
4561bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4562 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4563 // FIXME: We should be able to handle f128 as well with a clever lowering.
4564 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4565 return true;
4566
4567 if (VT == MVT::f64)
4568 return AArch64_AM::getFP64Imm(Imm) != -1;
4569 else if (VT == MVT::f32)
4570 return AArch64_AM::getFP32Imm(Imm) != -1;
4571 return false;
4572}
4573
4574//===----------------------------------------------------------------------===//
4575// AArch64 Optimization Hooks
4576//===----------------------------------------------------------------------===//
4577
Evandro Menezesbcb95cd2016-05-04 20:18:27 +00004578/// getEstimate - Return the appropriate estimate DAG for either the reciprocal
4579/// or the reciprocal square root.
4580static SDValue getEstimate(const AArch64Subtarget &ST,
4581 const AArch64TargetLowering::DAGCombinerInfo &DCI, unsigned Opcode,
4582 const SDValue &Operand, unsigned &ExtraSteps) {
4583 if (!ST.hasNEON())
4584 return SDValue();
4585
4586 EVT VT = Operand.getValueType();
Evandro Menezes238fa762016-07-19 22:31:11 +00004587 if (VT != MVT::f64 && VT != MVT::v1f64 && VT != MVT::v2f64 &&
4588 VT != MVT::f32 && VT != MVT::v1f32 &&
4589 VT != MVT::v2f32 && VT != MVT::v4f32 &&
4590 (!ST.hasFullFP16() ||
4591 (VT != MVT::f16 && VT != MVT::v4f16 && VT != MVT::v8f16)))
4592 return SDValue();
Evandro Menezesbcb95cd2016-05-04 20:18:27 +00004593
4594 std::string RecipOp;
4595 RecipOp = Opcode == (AArch64ISD::FRECPE) ? "div": "sqrt";
4596 RecipOp = ((VT.isVector()) ? "vec-": "") + RecipOp;
4597 RecipOp += (VT.getScalarType() == MVT::f64) ? "d": "f";
4598
4599 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
4600 if (!Recips.isEnabled(RecipOp))
4601 return SDValue();
4602
4603 ExtraSteps = Recips.getRefinementSteps(RecipOp);
4604 return DCI.DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4605}
4606
4607SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4608 DAGCombinerInfo &DCI, unsigned &ExtraSteps) const {
4609 return getEstimate(*Subtarget, DCI, AArch64ISD::FRECPE, Operand, ExtraSteps);
4610}
4611
4612SDValue AArch64TargetLowering::getRsqrtEstimate(SDValue Operand,
4613 DAGCombinerInfo &DCI, unsigned &ExtraSteps, bool &UseOneConst) const {
4614 UseOneConst = true;
4615 return getEstimate(*Subtarget, DCI, AArch64ISD::FRSQRTE, Operand, ExtraSteps);
4616}
4617
Tim Northover3b0846e2014-05-24 12:50:23 +00004618//===----------------------------------------------------------------------===//
4619// AArch64 Inline Assembly Support
4620//===----------------------------------------------------------------------===//
4621
4622// Table of Constraints
4623// TODO: This is the current set of constraints supported by ARM for the
4624// compiler, not all of them may make sense, e.g. S may be difficult to support.
4625//
4626// r - A general register
4627// w - An FP/SIMD register of some size in the range v0-v31
4628// x - An FP/SIMD register of some size in the range v0-v15
4629// I - Constant that can be used with an ADD instruction
4630// J - Constant that can be used with a SUB instruction
4631// K - Constant that can be used with a 32-bit logical instruction
4632// L - Constant that can be used with a 64-bit logical instruction
4633// M - Constant that can be used as a 32-bit MOV immediate
4634// N - Constant that can be used as a 64-bit MOV immediate
4635// Q - A memory reference with base register and no offset
4636// S - A symbolic address
4637// Y - Floating point constant zero
4638// Z - Integer constant zero
4639//
4640// Note that general register operands will be output using their 64-bit x
4641// register name, whatever the size of the variable, unless the asm operand
4642// is prefixed by the %w modifier. Floating-point and SIMD register operands
4643// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4644// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00004645const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4646 // At this point, we have to lower this constraint to something else, so we
4647 // lower it to an "r" or "w". However, by doing this we will force the result
4648 // to be in register, while the X constraint is much more permissive.
4649 //
4650 // Although we are correct (we are free to emit anything, without
4651 // constraints), we might break use cases that would expect us to be more
4652 // efficient and emit something else.
4653 if (!Subtarget->hasFPARMv8())
4654 return "r";
4655
4656 if (ConstraintVT.isFloatingPoint())
4657 return "w";
4658
4659 if (ConstraintVT.isVector() &&
4660 (ConstraintVT.getSizeInBits() == 64 ||
4661 ConstraintVT.getSizeInBits() == 128))
4662 return "w";
4663
4664 return "r";
4665}
Tim Northover3b0846e2014-05-24 12:50:23 +00004666
4667/// getConstraintType - Given a constraint letter, return the type of
4668/// constraint it is for this target.
4669AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004670AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004671 if (Constraint.size() == 1) {
4672 switch (Constraint[0]) {
4673 default:
4674 break;
4675 case 'z':
4676 return C_Other;
4677 case 'x':
4678 case 'w':
4679 return C_RegisterClass;
4680 // An address with a single base register. Due to the way we
4681 // currently handle addresses it is the same as 'r'.
4682 case 'Q':
4683 return C_Memory;
4684 }
4685 }
4686 return TargetLowering::getConstraintType(Constraint);
4687}
4688
4689/// Examine constraint type and operand type and determine a weight value.
4690/// This object must already have been set up with the operand type
4691/// and the current alternative constraint selected.
4692TargetLowering::ConstraintWeight
4693AArch64TargetLowering::getSingleConstraintMatchWeight(
4694 AsmOperandInfo &info, const char *constraint) const {
4695 ConstraintWeight weight = CW_Invalid;
4696 Value *CallOperandVal = info.CallOperandVal;
4697 // If we don't have a value, we can't do a match,
4698 // but allow it at the lowest weight.
4699 if (!CallOperandVal)
4700 return CW_Default;
4701 Type *type = CallOperandVal->getType();
4702 // Look at the constraint type.
4703 switch (*constraint) {
4704 default:
4705 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4706 break;
4707 case 'x':
4708 case 'w':
4709 if (type->isFloatingPointTy() || type->isVectorTy())
4710 weight = CW_Register;
4711 break;
4712 case 'z':
4713 weight = CW_Constant;
4714 break;
4715 }
4716 return weight;
4717}
4718
4719std::pair<unsigned, const TargetRegisterClass *>
4720AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004721 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004722 if (Constraint.size() == 1) {
4723 switch (Constraint[0]) {
4724 case 'r':
4725 if (VT.getSizeInBits() == 64)
4726 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4727 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4728 case 'w':
Akira Hatanakab8d28732016-07-21 21:39:05 +00004729 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00004730 return std::make_pair(0U, &AArch64::FPR32RegClass);
4731 if (VT.getSizeInBits() == 64)
4732 return std::make_pair(0U, &AArch64::FPR64RegClass);
4733 if (VT.getSizeInBits() == 128)
4734 return std::make_pair(0U, &AArch64::FPR128RegClass);
4735 break;
4736 // The instructions that this constraint is designed for can
4737 // only take 128-bit registers so just use that regclass.
4738 case 'x':
4739 if (VT.getSizeInBits() == 128)
4740 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4741 break;
4742 }
4743 }
4744 if (StringRef("{cc}").equals_lower(Constraint))
4745 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4746
4747 // Use the default implementation in TargetLowering to convert the register
4748 // constraint into a member of a register class.
4749 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004750 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004751
4752 // Not found as a standard register?
4753 if (!Res.second) {
4754 unsigned Size = Constraint.size();
4755 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4756 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004757 int RegNo;
4758 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4759 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00004760 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00004761 // By default we'll emit v0-v31 for this unless there's a modifier where
4762 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00004763 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4764 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4765 Res.second = &AArch64::FPR64RegClass;
4766 } else {
4767 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4768 Res.second = &AArch64::FPR128RegClass;
4769 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004770 }
4771 }
4772 }
4773
4774 return Res;
4775}
4776
4777/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4778/// vector. If it is invalid, don't add anything to Ops.
4779void AArch64TargetLowering::LowerAsmOperandForConstraint(
4780 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4781 SelectionDAG &DAG) const {
4782 SDValue Result;
4783
4784 // Currently only support length 1 constraints.
4785 if (Constraint.length() != 1)
4786 return;
4787
4788 char ConstraintLetter = Constraint[0];
4789 switch (ConstraintLetter) {
4790 default:
4791 break;
4792
4793 // This set of constraints deal with valid constants for various instructions.
4794 // Validate and return a target constant for them if we can.
4795 case 'z': {
4796 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004797 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004798 return;
4799
4800 if (Op.getValueType() == MVT::i64)
4801 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4802 else
4803 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4804 break;
4805 }
4806
4807 case 'I':
4808 case 'J':
4809 case 'K':
4810 case 'L':
4811 case 'M':
4812 case 'N':
4813 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4814 if (!C)
4815 return;
4816
4817 // Grab the value and do some validation.
4818 uint64_t CVal = C->getZExtValue();
4819 switch (ConstraintLetter) {
4820 // The I constraint applies only to simple ADD or SUB immediate operands:
4821 // i.e. 0 to 4095 with optional shift by 12
4822 // The J constraint applies only to ADD or SUB immediates that would be
4823 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4824 // instruction [or vice versa], in other words -1 to -4095 with optional
4825 // left shift by 12.
4826 case 'I':
4827 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4828 break;
4829 return;
4830 case 'J': {
4831 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004832 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4833 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004834 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004835 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004836 return;
4837 }
4838 // The K and L constraints apply *only* to logical immediates, including
4839 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4840 // been removed and MOV should be used). So these constraints have to
4841 // distinguish between bit patterns that are valid 32-bit or 64-bit
4842 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4843 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4844 // versa.
4845 case 'K':
4846 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4847 break;
4848 return;
4849 case 'L':
4850 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4851 break;
4852 return;
4853 // The M and N constraints are a superset of K and L respectively, for use
4854 // with the MOV (immediate) alias. As well as the logical immediates they
4855 // also match 32 or 64-bit immediates that can be loaded either using a
4856 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4857 // (M) or 64-bit 0x1234000000000000 (N) etc.
4858 // As a note some of this code is liberally stolen from the asm parser.
4859 case 'M': {
4860 if (!isUInt<32>(CVal))
4861 return;
4862 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4863 break;
4864 if ((CVal & 0xFFFF) == CVal)
4865 break;
4866 if ((CVal & 0xFFFF0000ULL) == CVal)
4867 break;
4868 uint64_t NCVal = ~(uint32_t)CVal;
4869 if ((NCVal & 0xFFFFULL) == NCVal)
4870 break;
4871 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4872 break;
4873 return;
4874 }
4875 case 'N': {
4876 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4877 break;
4878 if ((CVal & 0xFFFFULL) == CVal)
4879 break;
4880 if ((CVal & 0xFFFF0000ULL) == CVal)
4881 break;
4882 if ((CVal & 0xFFFF00000000ULL) == CVal)
4883 break;
4884 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4885 break;
4886 uint64_t NCVal = ~CVal;
4887 if ((NCVal & 0xFFFFULL) == NCVal)
4888 break;
4889 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4890 break;
4891 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4892 break;
4893 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4894 break;
4895 return;
4896 }
4897 default:
4898 return;
4899 }
4900
4901 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004902 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004903 break;
4904 }
4905
4906 if (Result.getNode()) {
4907 Ops.push_back(Result);
4908 return;
4909 }
4910
4911 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4912}
4913
4914//===----------------------------------------------------------------------===//
4915// AArch64 Advanced SIMD Support
4916//===----------------------------------------------------------------------===//
4917
4918/// WidenVector - Given a value in the V64 register class, produce the
4919/// equivalent value in the V128 register class.
4920static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4921 EVT VT = V64Reg.getValueType();
4922 unsigned NarrowSize = VT.getVectorNumElements();
4923 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4924 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4925 SDLoc DL(V64Reg);
4926
4927 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004928 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004929}
4930
4931/// getExtFactor - Determine the adjustment factor for the position when
4932/// generating an "extract from vector registers" instruction.
4933static unsigned getExtFactor(SDValue &V) {
4934 EVT EltType = V.getValueType().getVectorElementType();
4935 return EltType.getSizeInBits() / 8;
4936}
4937
4938/// NarrowVector - Given a value in the V128 register class, produce the
4939/// equivalent value in the V64 register class.
4940static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4941 EVT VT = V128Reg.getValueType();
4942 unsigned WideSize = VT.getVectorNumElements();
4943 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4944 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4945 SDLoc DL(V128Reg);
4946
4947 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4948}
4949
4950// Gather data to see if the operation can be modelled as a
4951// shuffle in combination with VEXTs.
4952SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4953 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004954 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004955 SDLoc dl(Op);
4956 EVT VT = Op.getValueType();
4957 unsigned NumElts = VT.getVectorNumElements();
4958
Tim Northover7324e842014-07-24 15:39:55 +00004959 struct ShuffleSourceInfo {
4960 SDValue Vec;
4961 unsigned MinElt;
4962 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004963
Tim Northover7324e842014-07-24 15:39:55 +00004964 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4965 // be compatible with the shuffle we intend to construct. As a result
4966 // ShuffleVec will be some sliding window into the original Vec.
4967 SDValue ShuffleVec;
4968
4969 // Code should guarantee that element i in Vec starts at element "WindowBase
4970 // + i * WindowScale in ShuffleVec".
4971 int WindowBase;
4972 int WindowScale;
4973
4974 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4975 ShuffleSourceInfo(SDValue Vec)
4976 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4977 WindowScale(1) {}
4978 };
4979
4980 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4981 // node.
4982 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004983 for (unsigned i = 0; i < NumElts; ++i) {
4984 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00004985 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00004986 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004987 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4988 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004989 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004990 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00004991 return SDValue();
4992 }
4993
Tim Northover7324e842014-07-24 15:39:55 +00004994 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004995 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00004996 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00004997 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004998 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004999
Tim Northover7324e842014-07-24 15:39:55 +00005000 // Update the minimum and maximum lane number seen.
5001 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5002 Source->MinElt = std::min(Source->MinElt, EltNo);
5003 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005004 }
5005
5006 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00005007 // are involved.
5008 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00005009 return SDValue();
5010
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005011 // Find out the smallest element size among result and two sources, and use
5012 // it as element size to build the shuffle_vector.
5013 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005014 for (auto &Source : Sources) {
5015 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005016 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5017 SmallestEltTy = SrcEltTy;
5018 }
5019 }
5020 unsigned ResMultiplier =
5021 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005022 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5023 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005024
Tim Northover7324e842014-07-24 15:39:55 +00005025 // If the source vector is too wide or too narrow, we may nevertheless be able
5026 // to construct a compatible shuffle either by concatenating it with UNDEF or
5027 // extracting a suitable range of elements.
5028 for (auto &Src : Sources) {
5029 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005030
Tim Northover7324e842014-07-24 15:39:55 +00005031 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005032 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005033
5034 // This stage of the search produces a source with the same element type as
5035 // the original, but with a total width matching the BUILD_VECTOR output.
5036 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005037 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5038 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005039
5040 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5041 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005042 // We can pad out the smaller vector for free, so if it's part of a
5043 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005044 Src.ShuffleVec =
5045 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5046 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005047 continue;
5048 }
5049
Tim Northover7324e842014-07-24 15:39:55 +00005050 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005051
James Molloyf497d552014-10-17 17:06:31 +00005052 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005053 // Span too large for a VEXT to cope
5054 return SDValue();
5055 }
5056
James Molloyf497d552014-10-17 17:06:31 +00005057 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005058 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005059 Src.ShuffleVec =
5060 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005061 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005062 Src.WindowBase = -NumSrcElts;
5063 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005064 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005065 Src.ShuffleVec =
5066 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005067 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005068 } else {
5069 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005070 SDValue VEXTSrc1 =
5071 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005072 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005073 SDValue VEXTSrc2 =
5074 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005075 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005076 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5077
5078 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005079 VEXTSrc2,
5080 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005081 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005082 }
5083 }
5084
Tim Northover7324e842014-07-24 15:39:55 +00005085 // Another possible incompatibility occurs from the vector element types. We
5086 // can fix this by bitcasting the source vectors to the same type we intend
5087 // for the shuffle.
5088 for (auto &Src : Sources) {
5089 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5090 if (SrcEltTy == SmallestEltTy)
5091 continue;
5092 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5093 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5094 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5095 Src.WindowBase *= Src.WindowScale;
5096 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005097
Tim Northover7324e842014-07-24 15:39:55 +00005098 // Final sanity check before we try to actually produce a shuffle.
5099 DEBUG(
5100 for (auto Src : Sources)
5101 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5102 );
5103
5104 // The stars all align, our next step is to produce the mask for the shuffle.
5105 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5106 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005107 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005108 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005109 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005110 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005111
David Majnemer0d955d02016-08-11 22:21:41 +00005112 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005113 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5114
5115 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5116 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5117 // segment.
5118 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5119 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5120 VT.getVectorElementType().getSizeInBits());
5121 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5122
5123 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5124 // starting at the appropriate offset.
5125 int *LaneMask = &Mask[i * ResMultiplier];
5126
5127 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5128 ExtractBase += NumElts * (Src - Sources.begin());
5129 for (int j = 0; j < LanesDefined; ++j)
5130 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005131 }
5132
5133 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005134 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5135 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005136
Tim Northover7324e842014-07-24 15:39:55 +00005137 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5138 for (unsigned i = 0; i < Sources.size(); ++i)
5139 ShuffleOps[i] = Sources[i].ShuffleVec;
5140
5141 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005142 ShuffleOps[1], Mask);
Tim Northover7324e842014-07-24 15:39:55 +00005143 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005144}
5145
5146// check if an EXT instruction can handle the shuffle mask when the
5147// vector sources of the shuffle are the same.
5148static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5149 unsigned NumElts = VT.getVectorNumElements();
5150
5151 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5152 if (M[0] < 0)
5153 return false;
5154
5155 Imm = M[0];
5156
5157 // If this is a VEXT shuffle, the immediate value is the index of the first
5158 // element. The other shuffle indices must be the successive elements after
5159 // the first one.
5160 unsigned ExpectedElt = Imm;
5161 for (unsigned i = 1; i < NumElts; ++i) {
5162 // Increment the expected index. If it wraps around, just follow it
5163 // back to index zero and keep going.
5164 ++ExpectedElt;
5165 if (ExpectedElt == NumElts)
5166 ExpectedElt = 0;
5167
5168 if (M[i] < 0)
5169 continue; // ignore UNDEF indices
5170 if (ExpectedElt != static_cast<unsigned>(M[i]))
5171 return false;
5172 }
5173
5174 return true;
5175}
5176
5177// check if an EXT instruction can handle the shuffle mask when the
5178// vector sources of the shuffle are different.
5179static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5180 unsigned &Imm) {
5181 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005182 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005183
5184 // Benefit form APInt to handle overflow when calculating expected element.
5185 unsigned NumElts = VT.getVectorNumElements();
5186 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5187 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5188 // The following shuffle indices must be the successive elements after the
5189 // first real element.
5190 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5191 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5192 if (FirstWrongElt != M.end())
5193 return false;
5194
5195 // The index of an EXT is the first element if it is not UNDEF.
5196 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005197 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005198 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5199 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5200 // ExpectedElt is the last mask index plus 1.
5201 Imm = ExpectedElt.getZExtValue();
5202
5203 // There are two difference cases requiring to reverse input vectors.
5204 // For example, for vector <4 x i32> we have the following cases,
5205 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5206 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5207 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5208 // to reverse two input vectors.
5209 if (Imm < NumElts)
5210 ReverseEXT = true;
5211 else
5212 Imm -= NumElts;
5213
5214 return true;
5215}
5216
5217/// isREVMask - Check if a vector shuffle corresponds to a REV
5218/// instruction with the specified blocksize. (The order of the elements
5219/// within each block of the vector is reversed.)
5220static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5221 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5222 "Only possible block sizes for REV are: 16, 32, 64");
5223
5224 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5225 if (EltSz == 64)
5226 return false;
5227
5228 unsigned NumElts = VT.getVectorNumElements();
5229 unsigned BlockElts = M[0] + 1;
5230 // If the first shuffle index is UNDEF, be optimistic.
5231 if (M[0] < 0)
5232 BlockElts = BlockSize / EltSz;
5233
5234 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5235 return false;
5236
5237 for (unsigned i = 0; i < NumElts; ++i) {
5238 if (M[i] < 0)
5239 continue; // ignore UNDEF indices
5240 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5241 return false;
5242 }
5243
5244 return true;
5245}
5246
5247static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5248 unsigned NumElts = VT.getVectorNumElements();
5249 WhichResult = (M[0] == 0 ? 0 : 1);
5250 unsigned Idx = WhichResult * NumElts / 2;
5251 for (unsigned i = 0; i != NumElts; i += 2) {
5252 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5253 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5254 return false;
5255 Idx += 1;
5256 }
5257
5258 return true;
5259}
5260
5261static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5262 unsigned NumElts = VT.getVectorNumElements();
5263 WhichResult = (M[0] == 0 ? 0 : 1);
5264 for (unsigned i = 0; i != NumElts; ++i) {
5265 if (M[i] < 0)
5266 continue; // ignore UNDEF indices
5267 if ((unsigned)M[i] != 2 * i + WhichResult)
5268 return false;
5269 }
5270
5271 return true;
5272}
5273
5274static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5275 unsigned NumElts = VT.getVectorNumElements();
5276 WhichResult = (M[0] == 0 ? 0 : 1);
5277 for (unsigned i = 0; i < NumElts; i += 2) {
5278 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5279 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5280 return false;
5281 }
5282 return true;
5283}
5284
5285/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5286/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5287/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5288static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5289 unsigned NumElts = VT.getVectorNumElements();
5290 WhichResult = (M[0] == 0 ? 0 : 1);
5291 unsigned Idx = WhichResult * NumElts / 2;
5292 for (unsigned i = 0; i != NumElts; i += 2) {
5293 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5294 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5295 return false;
5296 Idx += 1;
5297 }
5298
5299 return true;
5300}
5301
5302/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5303/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5304/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5305static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5306 unsigned Half = VT.getVectorNumElements() / 2;
5307 WhichResult = (M[0] == 0 ? 0 : 1);
5308 for (unsigned j = 0; j != 2; ++j) {
5309 unsigned Idx = WhichResult;
5310 for (unsigned i = 0; i != Half; ++i) {
5311 int MIdx = M[i + j * Half];
5312 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5313 return false;
5314 Idx += 2;
5315 }
5316 }
5317
5318 return true;
5319}
5320
5321/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5322/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5323/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5324static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5325 unsigned NumElts = VT.getVectorNumElements();
5326 WhichResult = (M[0] == 0 ? 0 : 1);
5327 for (unsigned i = 0; i < NumElts; i += 2) {
5328 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5329 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5330 return false;
5331 }
5332 return true;
5333}
5334
5335static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5336 bool &DstIsLeft, int &Anomaly) {
5337 if (M.size() != static_cast<size_t>(NumInputElements))
5338 return false;
5339
5340 int NumLHSMatch = 0, NumRHSMatch = 0;
5341 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5342
5343 for (int i = 0; i < NumInputElements; ++i) {
5344 if (M[i] == -1) {
5345 ++NumLHSMatch;
5346 ++NumRHSMatch;
5347 continue;
5348 }
5349
5350 if (M[i] == i)
5351 ++NumLHSMatch;
5352 else
5353 LastLHSMismatch = i;
5354
5355 if (M[i] == i + NumInputElements)
5356 ++NumRHSMatch;
5357 else
5358 LastRHSMismatch = i;
5359 }
5360
5361 if (NumLHSMatch == NumInputElements - 1) {
5362 DstIsLeft = true;
5363 Anomaly = LastLHSMismatch;
5364 return true;
5365 } else if (NumRHSMatch == NumInputElements - 1) {
5366 DstIsLeft = false;
5367 Anomaly = LastRHSMismatch;
5368 return true;
5369 }
5370
5371 return false;
5372}
5373
5374static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5375 if (VT.getSizeInBits() != 128)
5376 return false;
5377
5378 unsigned NumElts = VT.getVectorNumElements();
5379
5380 for (int I = 0, E = NumElts / 2; I != E; I++) {
5381 if (Mask[I] != I)
5382 return false;
5383 }
5384
5385 int Offset = NumElts / 2;
5386 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5387 if (Mask[I] != I + SplitLHS * Offset)
5388 return false;
5389 }
5390
5391 return true;
5392}
5393
5394static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5395 SDLoc DL(Op);
5396 EVT VT = Op.getValueType();
5397 SDValue V0 = Op.getOperand(0);
5398 SDValue V1 = Op.getOperand(1);
5399 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5400
5401 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5402 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5403 return SDValue();
5404
5405 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5406
5407 if (!isConcatMask(Mask, VT, SplitV0))
5408 return SDValue();
5409
5410 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5411 VT.getVectorNumElements() / 2);
5412 if (SplitV0) {
5413 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005414 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005415 }
5416 if (V1.getValueType().getSizeInBits() == 128) {
5417 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005418 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005419 }
5420 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5421}
5422
5423/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5424/// the specified operations to build the shuffle.
5425static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5426 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005427 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005428 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5429 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5430 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5431
5432 enum {
5433 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5434 OP_VREV,
5435 OP_VDUP0,
5436 OP_VDUP1,
5437 OP_VDUP2,
5438 OP_VDUP3,
5439 OP_VEXT1,
5440 OP_VEXT2,
5441 OP_VEXT3,
5442 OP_VUZPL, // VUZP, left result
5443 OP_VUZPR, // VUZP, right result
5444 OP_VZIPL, // VZIP, left result
5445 OP_VZIPR, // VZIP, right result
5446 OP_VTRNL, // VTRN, left result
5447 OP_VTRNR // VTRN, right result
5448 };
5449
5450 if (OpNum == OP_COPY) {
5451 if (LHSID == (1 * 9 + 2) * 9 + 3)
5452 return LHS;
5453 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5454 return RHS;
5455 }
5456
5457 SDValue OpLHS, OpRHS;
5458 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5459 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5460 EVT VT = OpLHS.getValueType();
5461
5462 switch (OpNum) {
5463 default:
5464 llvm_unreachable("Unknown shuffle opcode!");
5465 case OP_VREV:
5466 // VREV divides the vector in half and swaps within the half.
5467 if (VT.getVectorElementType() == MVT::i32 ||
5468 VT.getVectorElementType() == MVT::f32)
5469 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5470 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005471 if (VT.getVectorElementType() == MVT::i16 ||
5472 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005473 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5474 // vrev <4 x i8> -> REV16
5475 assert(VT.getVectorElementType() == MVT::i8);
5476 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5477 case OP_VDUP0:
5478 case OP_VDUP1:
5479 case OP_VDUP2:
5480 case OP_VDUP3: {
5481 EVT EltTy = VT.getVectorElementType();
5482 unsigned Opcode;
5483 if (EltTy == MVT::i8)
5484 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005485 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005486 Opcode = AArch64ISD::DUPLANE16;
5487 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5488 Opcode = AArch64ISD::DUPLANE32;
5489 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5490 Opcode = AArch64ISD::DUPLANE64;
5491 else
5492 llvm_unreachable("Invalid vector element type?");
5493
5494 if (VT.getSizeInBits() == 64)
5495 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005496 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005497 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5498 }
5499 case OP_VEXT1:
5500 case OP_VEXT2:
5501 case OP_VEXT3: {
5502 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5503 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005504 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005505 }
5506 case OP_VUZPL:
5507 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5508 OpRHS);
5509 case OP_VUZPR:
5510 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5511 OpRHS);
5512 case OP_VZIPL:
5513 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5514 OpRHS);
5515 case OP_VZIPR:
5516 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5517 OpRHS);
5518 case OP_VTRNL:
5519 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5520 OpRHS);
5521 case OP_VTRNR:
5522 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5523 OpRHS);
5524 }
5525}
5526
5527static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5528 SelectionDAG &DAG) {
5529 // Check to see if we can use the TBL instruction.
5530 SDValue V1 = Op.getOperand(0);
5531 SDValue V2 = Op.getOperand(1);
5532 SDLoc DL(Op);
5533
5534 EVT EltVT = Op.getValueType().getVectorElementType();
5535 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5536
5537 SmallVector<SDValue, 8> TBLMask;
5538 for (int Val : ShuffleMask) {
5539 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5540 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005541 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005542 }
5543 }
5544
5545 MVT IndexVT = MVT::v8i8;
5546 unsigned IndexLen = 8;
5547 if (Op.getValueType().getSizeInBits() == 128) {
5548 IndexVT = MVT::v16i8;
5549 IndexLen = 16;
5550 }
5551
5552 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5553 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5554
5555 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005556 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005557 if (IndexLen == 8)
5558 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5559 Shuffle = DAG.getNode(
5560 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005561 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005562 DAG.getBuildVector(IndexVT, DL,
5563 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005564 } else {
5565 if (IndexLen == 8) {
5566 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5567 Shuffle = DAG.getNode(
5568 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005569 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005570 DAG.getBuildVector(IndexVT, DL,
5571 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005572 } else {
5573 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5574 // cannot currently represent the register constraints on the input
5575 // table registers.
5576 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005577 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5578 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00005579 Shuffle = DAG.getNode(
5580 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005581 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5582 V2Cst, DAG.getBuildVector(IndexVT, DL,
5583 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005584 }
5585 }
5586 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5587}
5588
5589static unsigned getDUPLANEOp(EVT EltType) {
5590 if (EltType == MVT::i8)
5591 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005592 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005593 return AArch64ISD::DUPLANE16;
5594 if (EltType == MVT::i32 || EltType == MVT::f32)
5595 return AArch64ISD::DUPLANE32;
5596 if (EltType == MVT::i64 || EltType == MVT::f64)
5597 return AArch64ISD::DUPLANE64;
5598
5599 llvm_unreachable("Invalid vector element type?");
5600}
5601
5602SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5603 SelectionDAG &DAG) const {
5604 SDLoc dl(Op);
5605 EVT VT = Op.getValueType();
5606
5607 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5608
5609 // Convert shuffles that are directly supported on NEON to target-specific
5610 // DAG nodes, instead of keeping them as shuffles and matching them again
5611 // during code selection. This is more efficient and avoids the possibility
5612 // of inconsistencies between legalization and selection.
5613 ArrayRef<int> ShuffleMask = SVN->getMask();
5614
5615 SDValue V1 = Op.getOperand(0);
5616 SDValue V2 = Op.getOperand(1);
5617
Craig Topperbc56e3b2016-06-30 04:38:51 +00005618 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005619 int Lane = SVN->getSplatIndex();
5620 // If this is undef splat, generate it via "just" vdup, if possible.
5621 if (Lane == -1)
5622 Lane = 0;
5623
5624 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5625 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5626 V1.getOperand(0));
5627 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5628 // constant. If so, we can just reference the lane's definition directly.
5629 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5630 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5631 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5632
5633 // Otherwise, duplicate from the lane of the input vector.
5634 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5635
5636 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5637 // to make a vector of the same size as this SHUFFLE. We can ignore the
5638 // extract entirely, and canonicalise the concat using WidenVector.
5639 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5640 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5641 V1 = V1.getOperand(0);
5642 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5643 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5644 Lane -= Idx * VT.getVectorNumElements() / 2;
5645 V1 = WidenVector(V1.getOperand(Idx), DAG);
5646 } else if (VT.getSizeInBits() == 64)
5647 V1 = WidenVector(V1, DAG);
5648
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005649 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005650 }
5651
5652 if (isREVMask(ShuffleMask, VT, 64))
5653 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5654 if (isREVMask(ShuffleMask, VT, 32))
5655 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5656 if (isREVMask(ShuffleMask, VT, 16))
5657 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5658
5659 bool ReverseEXT = false;
5660 unsigned Imm;
5661 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5662 if (ReverseEXT)
5663 std::swap(V1, V2);
5664 Imm *= getExtFactor(V1);
5665 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005666 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00005667 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005668 Imm *= getExtFactor(V1);
5669 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005670 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005671 }
5672
5673 unsigned WhichResult;
5674 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5675 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5676 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5677 }
5678 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5679 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5680 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5681 }
5682 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5683 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5684 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5685 }
5686
5687 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5688 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5689 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5690 }
5691 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5692 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5693 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5694 }
5695 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5696 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5697 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5698 }
5699
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005700 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005701 return Concat;
5702
5703 bool DstIsLeft;
5704 int Anomaly;
5705 int NumInputElements = V1.getValueType().getVectorNumElements();
5706 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5707 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005708 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005709
5710 SDValue SrcVec = V1;
5711 int SrcLane = ShuffleMask[Anomaly];
5712 if (SrcLane >= NumInputElements) {
5713 SrcVec = V2;
5714 SrcLane -= VT.getVectorNumElements();
5715 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005716 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005717
5718 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005719
5720 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005721 ScalarVT = MVT::i32;
5722
5723 return DAG.getNode(
5724 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5725 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5726 DstLaneV);
5727 }
5728
5729 // If the shuffle is not directly supported and it has 4 elements, use
5730 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5731 unsigned NumElts = VT.getVectorNumElements();
5732 if (NumElts == 4) {
5733 unsigned PFIndexes[4];
5734 for (unsigned i = 0; i != 4; ++i) {
5735 if (ShuffleMask[i] < 0)
5736 PFIndexes[i] = 8;
5737 else
5738 PFIndexes[i] = ShuffleMask[i];
5739 }
5740
5741 // Compute the index in the perfect shuffle table.
5742 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5743 PFIndexes[2] * 9 + PFIndexes[3];
5744 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5745 unsigned Cost = (PFEntry >> 30);
5746
5747 if (Cost <= 4)
5748 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5749 }
5750
5751 return GenerateTBL(Op, ShuffleMask, DAG);
5752}
5753
5754static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5755 APInt &UndefBits) {
5756 EVT VT = BVN->getValueType(0);
5757 APInt SplatBits, SplatUndef;
5758 unsigned SplatBitSize;
5759 bool HasAnyUndefs;
5760 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5761 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5762
5763 for (unsigned i = 0; i < NumSplats; ++i) {
5764 CnstBits <<= SplatBitSize;
5765 UndefBits <<= SplatBitSize;
5766 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5767 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5768 }
5769
5770 return true;
5771 }
5772
5773 return false;
5774}
5775
5776SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5777 SelectionDAG &DAG) const {
5778 BuildVectorSDNode *BVN =
5779 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5780 SDValue LHS = Op.getOperand(0);
5781 SDLoc dl(Op);
5782 EVT VT = Op.getValueType();
5783
5784 if (!BVN)
5785 return Op;
5786
5787 APInt CnstBits(VT.getSizeInBits(), 0);
5788 APInt UndefBits(VT.getSizeInBits(), 0);
5789 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5790 // We only have BIC vector immediate instruction, which is and-not.
5791 CnstBits = ~CnstBits;
5792
5793 // We make use of a little bit of goto ickiness in order to avoid having to
5794 // duplicate the immediate matching logic for the undef toggled case.
5795 bool SecondTry = false;
5796 AttemptModImm:
5797
5798 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5799 CnstBits = CnstBits.zextOrTrunc(64);
5800 uint64_t CnstVal = CnstBits.getZExtValue();
5801
5802 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5803 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5804 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5805 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005806 DAG.getConstant(CnstVal, dl, MVT::i32),
5807 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005808 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005809 }
5810
5811 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5812 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5813 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5814 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005815 DAG.getConstant(CnstVal, dl, MVT::i32),
5816 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005817 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005818 }
5819
5820 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5821 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5822 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5823 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005824 DAG.getConstant(CnstVal, dl, MVT::i32),
5825 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005826 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005827 }
5828
5829 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5830 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5831 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5832 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005833 DAG.getConstant(CnstVal, dl, MVT::i32),
5834 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005835 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005836 }
5837
5838 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5839 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5840 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5841 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005842 DAG.getConstant(CnstVal, dl, MVT::i32),
5843 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005844 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005845 }
5846
5847 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5848 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5849 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5850 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005851 DAG.getConstant(CnstVal, dl, MVT::i32),
5852 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005853 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005854 }
5855 }
5856
5857 if (SecondTry)
5858 goto FailedModImm;
5859 SecondTry = true;
5860 CnstBits = ~UndefBits;
5861 goto AttemptModImm;
5862 }
5863
5864// We can always fall back to a non-immediate AND.
5865FailedModImm:
5866 return Op;
5867}
5868
5869// Specialized code to quickly find if PotentialBVec is a BuildVector that
5870// consists of only the same constant int value, returned in reference arg
5871// ConstVal
5872static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5873 uint64_t &ConstVal) {
5874 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5875 if (!Bvec)
5876 return false;
5877 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5878 if (!FirstElt)
5879 return false;
5880 EVT VT = Bvec->getValueType(0);
5881 unsigned NumElts = VT.getVectorNumElements();
5882 for (unsigned i = 1; i < NumElts; ++i)
5883 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5884 return false;
5885 ConstVal = FirstElt->getZExtValue();
5886 return true;
5887}
5888
5889static unsigned getIntrinsicID(const SDNode *N) {
5890 unsigned Opcode = N->getOpcode();
5891 switch (Opcode) {
5892 default:
5893 return Intrinsic::not_intrinsic;
5894 case ISD::INTRINSIC_WO_CHAIN: {
5895 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5896 if (IID < Intrinsic::num_intrinsics)
5897 return IID;
5898 return Intrinsic::not_intrinsic;
5899 }
5900 }
5901}
5902
5903// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5904// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5905// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5906// Also, logical shift right -> sri, with the same structure.
5907static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5908 EVT VT = N->getValueType(0);
5909
5910 if (!VT.isVector())
5911 return SDValue();
5912
5913 SDLoc DL(N);
5914
5915 // Is the first op an AND?
5916 const SDValue And = N->getOperand(0);
5917 if (And.getOpcode() != ISD::AND)
5918 return SDValue();
5919
5920 // Is the second op an shl or lshr?
5921 SDValue Shift = N->getOperand(1);
5922 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5923 // or AArch64ISD::VLSHR vector, #shift
5924 unsigned ShiftOpc = Shift.getOpcode();
5925 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5926 return SDValue();
5927 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5928
5929 // Is the shift amount constant?
5930 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5931 if (!C2node)
5932 return SDValue();
5933
5934 // Is the and mask vector all constant?
5935 uint64_t C1;
5936 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5937 return SDValue();
5938
5939 // Is C1 == ~C2, taking into account how much one can shift elements of a
5940 // particular size?
5941 uint64_t C2 = C2node->getZExtValue();
5942 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5943 if (C2 > ElemSizeInBits)
5944 return SDValue();
5945 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5946 if ((C1 & ElemMask) != (~C2 & ElemMask))
5947 return SDValue();
5948
5949 SDValue X = And.getOperand(0);
5950 SDValue Y = Shift.getOperand(0);
5951
5952 unsigned Intrin =
5953 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5954 SDValue ResultSLI =
5955 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005956 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5957 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005958
5959 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5960 DEBUG(N->dump(&DAG));
5961 DEBUG(dbgs() << "into: \n");
5962 DEBUG(ResultSLI->dump(&DAG));
5963
5964 ++NumShiftInserts;
5965 return ResultSLI;
5966}
5967
5968SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5969 SelectionDAG &DAG) const {
5970 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5971 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005972 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005973 return Res;
5974 }
5975
5976 BuildVectorSDNode *BVN =
5977 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5978 SDValue LHS = Op.getOperand(1);
5979 SDLoc dl(Op);
5980 EVT VT = Op.getValueType();
5981
5982 // OR commutes, so try swapping the operands.
5983 if (!BVN) {
5984 LHS = Op.getOperand(0);
5985 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5986 }
5987 if (!BVN)
5988 return Op;
5989
5990 APInt CnstBits(VT.getSizeInBits(), 0);
5991 APInt UndefBits(VT.getSizeInBits(), 0);
5992 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5993 // We make use of a little bit of goto ickiness in order to avoid having to
5994 // duplicate the immediate matching logic for the undef toggled case.
5995 bool SecondTry = false;
5996 AttemptModImm:
5997
5998 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5999 CnstBits = CnstBits.zextOrTrunc(64);
6000 uint64_t CnstVal = CnstBits.getZExtValue();
6001
6002 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6003 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6004 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6005 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006006 DAG.getConstant(CnstVal, dl, MVT::i32),
6007 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006008 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006009 }
6010
6011 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6012 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6013 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6014 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006015 DAG.getConstant(CnstVal, dl, MVT::i32),
6016 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006017 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006018 }
6019
6020 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6021 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6022 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6023 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006024 DAG.getConstant(CnstVal, dl, MVT::i32),
6025 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006026 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006027 }
6028
6029 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6030 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6031 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6032 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006033 DAG.getConstant(CnstVal, dl, MVT::i32),
6034 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006035 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006036 }
6037
6038 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6039 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6040 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6041 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006042 DAG.getConstant(CnstVal, dl, MVT::i32),
6043 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006044 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006045 }
6046
6047 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6048 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6049 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6050 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006051 DAG.getConstant(CnstVal, dl, MVT::i32),
6052 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006053 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006054 }
6055 }
6056
6057 if (SecondTry)
6058 goto FailedModImm;
6059 SecondTry = true;
6060 CnstBits = UndefBits;
6061 goto AttemptModImm;
6062 }
6063
6064// We can always fall back to a non-immediate OR.
6065FailedModImm:
6066 return Op;
6067}
6068
Kevin Qin4473c192014-07-07 02:45:40 +00006069// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6070// be truncated to fit element width.
6071static SDValue NormalizeBuildVector(SDValue Op,
6072 SelectionDAG &DAG) {
6073 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006074 SDLoc dl(Op);
6075 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006076 EVT EltTy= VT.getVectorElementType();
6077
6078 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6079 return Op;
6080
6081 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006082 for (SDValue Lane : Op->ops()) {
6083 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006084 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006085 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006086 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006087 }
6088 Ops.push_back(Lane);
6089 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006090 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006091}
6092
6093SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6094 SelectionDAG &DAG) const {
6095 SDLoc dl(Op);
6096 EVT VT = Op.getValueType();
6097 Op = NormalizeBuildVector(Op, DAG);
6098 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006099
6100 APInt CnstBits(VT.getSizeInBits(), 0);
6101 APInt UndefBits(VT.getSizeInBits(), 0);
6102 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6103 // We make use of a little bit of goto ickiness in order to avoid having to
6104 // duplicate the immediate matching logic for the undef toggled case.
6105 bool SecondTry = false;
6106 AttemptModImm:
6107
6108 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6109 CnstBits = CnstBits.zextOrTrunc(64);
6110 uint64_t CnstVal = CnstBits.getZExtValue();
6111
6112 // Certain magic vector constants (used to express things like NOT
6113 // and NEG) are passed through unmodified. This allows codegen patterns
6114 // for these operations to match. Special-purpose patterns will lower
6115 // these immediates to MOVIs if it proves necessary.
6116 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6117 return Op;
6118
6119 // The many faces of MOVI...
6120 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6121 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6122 if (VT.getSizeInBits() == 128) {
6123 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006124 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006125 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006126 }
6127
6128 // Support the V64 version via subregister insertion.
6129 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006130 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006131 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006132 }
6133
6134 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6135 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6136 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6137 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006138 DAG.getConstant(CnstVal, dl, MVT::i32),
6139 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006140 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006141 }
6142
6143 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6144 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6145 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6146 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006147 DAG.getConstant(CnstVal, dl, MVT::i32),
6148 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006149 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006150 }
6151
6152 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6153 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6154 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6155 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006156 DAG.getConstant(CnstVal, dl, MVT::i32),
6157 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006158 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006159 }
6160
6161 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6162 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6163 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6164 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006165 DAG.getConstant(CnstVal, dl, MVT::i32),
6166 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006167 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006168 }
6169
6170 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6171 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6172 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6173 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006174 DAG.getConstant(CnstVal, dl, MVT::i32),
6175 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006176 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006177 }
6178
6179 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6180 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6181 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6182 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006183 DAG.getConstant(CnstVal, dl, MVT::i32),
6184 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006185 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006186 }
6187
6188 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6189 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6190 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6191 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006192 DAG.getConstant(CnstVal, dl, MVT::i32),
6193 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006194 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006195 }
6196
6197 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6198 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6199 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6200 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006201 DAG.getConstant(CnstVal, dl, MVT::i32),
6202 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006203 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006204 }
6205
6206 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6207 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6208 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6209 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006210 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006211 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006212 }
6213
6214 // The few faces of FMOV...
6215 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6216 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6217 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6218 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006219 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006220 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006221 }
6222
6223 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6224 VT.getSizeInBits() == 128) {
6225 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6226 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006227 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006228 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006229 }
6230
6231 // The many faces of MVNI...
6232 CnstVal = ~CnstVal;
6233 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6234 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6235 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6236 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006237 DAG.getConstant(CnstVal, dl, MVT::i32),
6238 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006239 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006240 }
6241
6242 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6243 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6244 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6245 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006246 DAG.getConstant(CnstVal, dl, MVT::i32),
6247 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006248 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006249 }
6250
6251 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6252 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6253 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6254 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006255 DAG.getConstant(CnstVal, dl, MVT::i32),
6256 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006257 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006258 }
6259
6260 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6261 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6262 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6263 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006264 DAG.getConstant(CnstVal, dl, MVT::i32),
6265 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006266 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006267 }
6268
6269 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6270 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6271 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6272 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006273 DAG.getConstant(CnstVal, dl, MVT::i32),
6274 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006275 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006276 }
6277
6278 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6279 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6280 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6281 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006282 DAG.getConstant(CnstVal, dl, MVT::i32),
6283 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006284 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006285 }
6286
6287 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6288 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6289 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6290 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006291 DAG.getConstant(CnstVal, dl, MVT::i32),
6292 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006293 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006294 }
6295
6296 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6297 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6298 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6299 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006300 DAG.getConstant(CnstVal, dl, MVT::i32),
6301 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006302 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006303 }
6304 }
6305
6306 if (SecondTry)
6307 goto FailedModImm;
6308 SecondTry = true;
6309 CnstBits = UndefBits;
6310 goto AttemptModImm;
6311 }
6312FailedModImm:
6313
6314 // Scan through the operands to find some interesting properties we can
6315 // exploit:
6316 // 1) If only one value is used, we can use a DUP, or
6317 // 2) if only the low element is not undef, we can just insert that, or
6318 // 3) if only one constant value is used (w/ some non-constant lanes),
6319 // we can splat the constant value into the whole vector then fill
6320 // in the non-constant lanes.
6321 // 4) FIXME: If different constant values are used, but we can intelligently
6322 // select the values we'll be overwriting for the non-constant
6323 // lanes such that we can directly materialize the vector
6324 // some other way (MOVI, e.g.), we can be sneaky.
6325 unsigned NumElts = VT.getVectorNumElements();
6326 bool isOnlyLowElement = true;
6327 bool usesOnlyOneValue = true;
6328 bool usesOnlyOneConstantValue = true;
6329 bool isConstant = true;
6330 unsigned NumConstantLanes = 0;
6331 SDValue Value;
6332 SDValue ConstantValue;
6333 for (unsigned i = 0; i < NumElts; ++i) {
6334 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006335 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006336 continue;
6337 if (i > 0)
6338 isOnlyLowElement = false;
6339 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6340 isConstant = false;
6341
6342 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6343 ++NumConstantLanes;
6344 if (!ConstantValue.getNode())
6345 ConstantValue = V;
6346 else if (ConstantValue != V)
6347 usesOnlyOneConstantValue = false;
6348 }
6349
6350 if (!Value.getNode())
6351 Value = V;
6352 else if (V != Value)
6353 usesOnlyOneValue = false;
6354 }
6355
6356 if (!Value.getNode())
6357 return DAG.getUNDEF(VT);
6358
6359 if (isOnlyLowElement)
6360 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6361
6362 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6363 // i32 and try again.
6364 if (usesOnlyOneValue) {
6365 if (!isConstant) {
6366 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6367 Value.getValueType() != VT)
6368 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6369
6370 // This is actually a DUPLANExx operation, which keeps everything vectory.
6371
6372 // DUPLANE works on 128-bit vectors, widen it if necessary.
6373 SDValue Lane = Value.getOperand(1);
6374 Value = Value.getOperand(0);
6375 if (Value.getValueType().getSizeInBits() == 64)
6376 Value = WidenVector(Value, DAG);
6377
6378 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6379 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6380 }
6381
6382 if (VT.getVectorElementType().isFloatingPoint()) {
6383 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006384 EVT EltTy = VT.getVectorElementType();
6385 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6386 "Unsupported floating-point vector type");
6387 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006388 for (unsigned i = 0; i < NumElts; ++i)
6389 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6390 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006391 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Tim Northover3b0846e2014-05-24 12:50:23 +00006392 Val = LowerBUILD_VECTOR(Val, DAG);
6393 if (Val.getNode())
6394 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6395 }
6396 }
6397
6398 // If there was only one constant value used and for more than one lane,
6399 // start by splatting that value, then replace the non-constant lanes. This
6400 // is better than the default, which will perform a separate initialization
6401 // for each lane.
6402 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6403 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6404 // Now insert the non-constant lanes.
6405 for (unsigned i = 0; i < NumElts; ++i) {
6406 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006407 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006408 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6409 // Note that type legalization likely mucked about with the VT of the
6410 // source operand, so we may have to convert it here before inserting.
6411 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6412 }
6413 }
6414 return Val;
6415 }
6416
6417 // If all elements are constants and the case above didn't get hit, fall back
6418 // to the default expansion, which will generate a load from the constant
6419 // pool.
6420 if (isConstant)
6421 return SDValue();
6422
6423 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6424 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006425 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006426 return shuffle;
6427 }
6428
6429 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6430 // know the default expansion would otherwise fall back on something even
6431 // worse. For a vector with one or two non-undef values, that's
6432 // scalar_to_vector for the elements followed by a shuffle (provided the
6433 // shuffle is valid for the target) and materialization element by element
6434 // on the stack followed by a load for everything else.
6435 if (!isConstant && !usesOnlyOneValue) {
6436 SDValue Vec = DAG.getUNDEF(VT);
6437 SDValue Op0 = Op.getOperand(0);
6438 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6439 unsigned i = 0;
6440 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6441 // a) Avoid a RMW dependency on the full vector register, and
6442 // b) Allow the register coalescer to fold away the copy if the
6443 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006444 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6445 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
Sanjay Patel75068522016-03-14 18:09:43 +00006446 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
Matthias Braun0acbd082015-08-31 18:25:15 +00006447 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006448 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6449 MachineSDNode *N =
6450 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006451 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006452 Vec = SDValue(N, 0);
6453 ++i;
6454 }
6455 for (; i < NumElts; ++i) {
6456 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006457 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006458 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006459 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006460 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6461 }
6462 return Vec;
6463 }
6464
6465 // Just use the default expansion. We failed to find a better alternative.
6466 return SDValue();
6467}
6468
6469SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6470 SelectionDAG &DAG) const {
6471 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6472
Tim Northovere4b8e132014-07-15 10:00:26 +00006473 // Check for non-constant or out of range lane.
6474 EVT VT = Op.getOperand(0).getValueType();
6475 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6476 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006477 return SDValue();
6478
Tim Northover3b0846e2014-05-24 12:50:23 +00006479
6480 // Insertion/extraction are legal for V128 types.
6481 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006482 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6483 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006484 return Op;
6485
6486 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006487 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006488 return SDValue();
6489
6490 // For V64 types, we perform insertion by expanding the value
6491 // to a V128 type and perform the insertion on that.
6492 SDLoc DL(Op);
6493 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6494 EVT WideTy = WideVec.getValueType();
6495
6496 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6497 Op.getOperand(1), Op.getOperand(2));
6498 // Re-narrow the resultant vector.
6499 return NarrowVector(Node, DAG);
6500}
6501
6502SDValue
6503AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6504 SelectionDAG &DAG) const {
6505 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6506
Tim Northovere4b8e132014-07-15 10:00:26 +00006507 // Check for non-constant or out of range lane.
6508 EVT VT = Op.getOperand(0).getValueType();
6509 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6510 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006511 return SDValue();
6512
Tim Northover3b0846e2014-05-24 12:50:23 +00006513
6514 // Insertion/extraction are legal for V128 types.
6515 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006516 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6517 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006518 return Op;
6519
6520 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006521 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006522 return SDValue();
6523
6524 // For V64 types, we perform extraction by expanding the value
6525 // to a V128 type and perform the extraction on that.
6526 SDLoc DL(Op);
6527 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6528 EVT WideTy = WideVec.getValueType();
6529
6530 EVT ExtrTy = WideTy.getVectorElementType();
6531 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6532 ExtrTy = MVT::i32;
6533
6534 // For extractions, we just return the result directly.
6535 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6536 Op.getOperand(1));
6537}
6538
6539SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6540 SelectionDAG &DAG) const {
6541 EVT VT = Op.getOperand(0).getValueType();
6542 SDLoc dl(Op);
6543 // Just in case...
6544 if (!VT.isVector())
6545 return SDValue();
6546
6547 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6548 if (!Cst)
6549 return SDValue();
6550 unsigned Val = Cst->getZExtValue();
6551
6552 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006553
6554 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6555 if (Val == 0)
6556 return Op;
6557
Tim Northover3b0846e2014-05-24 12:50:23 +00006558 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6559 // that directly.
6560 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6561 return Op;
6562
6563 return SDValue();
6564}
6565
6566bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6567 EVT VT) const {
6568 if (VT.getVectorNumElements() == 4 &&
6569 (VT.is128BitVector() || VT.is64BitVector())) {
6570 unsigned PFIndexes[4];
6571 for (unsigned i = 0; i != 4; ++i) {
6572 if (M[i] < 0)
6573 PFIndexes[i] = 8;
6574 else
6575 PFIndexes[i] = M[i];
6576 }
6577
6578 // Compute the index in the perfect shuffle table.
6579 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6580 PFIndexes[2] * 9 + PFIndexes[3];
6581 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6582 unsigned Cost = (PFEntry >> 30);
6583
6584 if (Cost <= 4)
6585 return true;
6586 }
6587
6588 bool DummyBool;
6589 int DummyInt;
6590 unsigned DummyUnsigned;
6591
6592 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6593 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6594 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6595 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6596 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6597 isZIPMask(M, VT, DummyUnsigned) ||
6598 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6599 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6600 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6601 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6602 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6603}
6604
6605/// getVShiftImm - Check if this is a valid build_vector for the immediate
6606/// operand of a vector shift operation, where all the elements of the
6607/// build_vector must have the same constant integer value.
6608static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6609 // Ignore bit_converts.
6610 while (Op.getOpcode() == ISD::BITCAST)
6611 Op = Op.getOperand(0);
6612 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6613 APInt SplatBits, SplatUndef;
6614 unsigned SplatBitSize;
6615 bool HasAnyUndefs;
6616 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6617 HasAnyUndefs, ElementBits) ||
6618 SplatBitSize > ElementBits)
6619 return false;
6620 Cnt = SplatBits.getSExtValue();
6621 return true;
6622}
6623
6624/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6625/// operand of a vector shift left operation. That value must be in the range:
6626/// 0 <= Value < ElementBits for a left shift; or
6627/// 0 <= Value <= ElementBits for a long left shift.
6628static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6629 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006630 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006631 if (!getVShiftImm(Op, ElementBits, Cnt))
6632 return false;
6633 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6634}
6635
6636/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006637/// operand of a vector shift right operation. The value must be in the range:
6638/// 1 <= Value <= ElementBits for a right shift; or
6639static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006640 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006641 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006642 if (!getVShiftImm(Op, ElementBits, Cnt))
6643 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006644 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6645}
6646
6647SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6648 SelectionDAG &DAG) const {
6649 EVT VT = Op.getValueType();
6650 SDLoc DL(Op);
6651 int64_t Cnt;
6652
6653 if (!Op.getOperand(1).getValueType().isVector())
6654 return Op;
6655 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6656
6657 switch (Op.getOpcode()) {
6658 default:
6659 llvm_unreachable("unexpected shift opcode");
6660
6661 case ISD::SHL:
6662 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006663 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6664 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006665 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006666 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6667 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006668 Op.getOperand(0), Op.getOperand(1));
6669 case ISD::SRA:
6670 case ISD::SRL:
6671 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006672 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006673 unsigned Opc =
6674 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006675 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6676 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006677 }
6678
6679 // Right shift register. Note, there is not a shift right register
6680 // instruction, but the shift left register instruction takes a signed
6681 // value, where negative numbers specify a right shift.
6682 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6683 : Intrinsic::aarch64_neon_ushl;
6684 // negate the shift amount
6685 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6686 SDValue NegShiftLeft =
6687 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006688 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6689 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006690 return NegShiftLeft;
6691 }
6692
6693 return SDValue();
6694}
6695
6696static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6697 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006698 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006699 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006700 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6701 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006702
6703 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6704 APInt CnstBits(VT.getSizeInBits(), 0);
6705 APInt UndefBits(VT.getSizeInBits(), 0);
6706 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6707 bool IsZero = IsCnst && (CnstBits == 0);
6708
6709 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6710 switch (CC) {
6711 default:
6712 return SDValue();
6713 case AArch64CC::NE: {
6714 SDValue Fcmeq;
6715 if (IsZero)
6716 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6717 else
6718 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6719 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6720 }
6721 case AArch64CC::EQ:
6722 if (IsZero)
6723 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6724 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6725 case AArch64CC::GE:
6726 if (IsZero)
6727 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6728 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6729 case AArch64CC::GT:
6730 if (IsZero)
6731 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6732 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6733 case AArch64CC::LS:
6734 if (IsZero)
6735 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6736 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6737 case AArch64CC::LT:
6738 if (!NoNans)
6739 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00006740 // If we ignore NaNs then we can use to the MI implementation.
6741 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00006742 case AArch64CC::MI:
6743 if (IsZero)
6744 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6745 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6746 }
6747 }
6748
6749 switch (CC) {
6750 default:
6751 return SDValue();
6752 case AArch64CC::NE: {
6753 SDValue Cmeq;
6754 if (IsZero)
6755 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6756 else
6757 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6758 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6759 }
6760 case AArch64CC::EQ:
6761 if (IsZero)
6762 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6763 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6764 case AArch64CC::GE:
6765 if (IsZero)
6766 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6767 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6768 case AArch64CC::GT:
6769 if (IsZero)
6770 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6771 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6772 case AArch64CC::LE:
6773 if (IsZero)
6774 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6775 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6776 case AArch64CC::LS:
6777 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6778 case AArch64CC::LO:
6779 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6780 case AArch64CC::LT:
6781 if (IsZero)
6782 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6783 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6784 case AArch64CC::HI:
6785 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6786 case AArch64CC::HS:
6787 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6788 }
6789}
6790
6791SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6792 SelectionDAG &DAG) const {
6793 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6794 SDValue LHS = Op.getOperand(0);
6795 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006796 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006797 SDLoc dl(Op);
6798
6799 if (LHS.getValueType().getVectorElementType().isInteger()) {
6800 assert(LHS.getValueType() == RHS.getValueType());
6801 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006802 SDValue Cmp =
6803 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6804 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006805 }
6806
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006807 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6808 return SDValue();
6809
Tim Northover3b0846e2014-05-24 12:50:23 +00006810 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6811 LHS.getValueType().getVectorElementType() == MVT::f64);
6812
6813 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6814 // clean. Some of them require two branches to implement.
6815 AArch64CC::CondCode CC1, CC2;
6816 bool ShouldInvert;
6817 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6818
6819 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6820 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006821 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006822 if (!Cmp.getNode())
6823 return SDValue();
6824
6825 if (CC2 != AArch64CC::AL) {
6826 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006827 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006828 if (!Cmp2.getNode())
6829 return SDValue();
6830
Tim Northover45aa89c2015-02-08 00:50:47 +00006831 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006832 }
6833
Tim Northover45aa89c2015-02-08 00:50:47 +00006834 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6835
Tim Northover3b0846e2014-05-24 12:50:23 +00006836 if (ShouldInvert)
6837 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6838
6839 return Cmp;
6840}
6841
6842/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6843/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6844/// specified in the intrinsic calls.
6845bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6846 const CallInst &I,
6847 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006848 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006849 switch (Intrinsic) {
6850 case Intrinsic::aarch64_neon_ld2:
6851 case Intrinsic::aarch64_neon_ld3:
6852 case Intrinsic::aarch64_neon_ld4:
6853 case Intrinsic::aarch64_neon_ld1x2:
6854 case Intrinsic::aarch64_neon_ld1x3:
6855 case Intrinsic::aarch64_neon_ld1x4:
6856 case Intrinsic::aarch64_neon_ld2lane:
6857 case Intrinsic::aarch64_neon_ld3lane:
6858 case Intrinsic::aarch64_neon_ld4lane:
6859 case Intrinsic::aarch64_neon_ld2r:
6860 case Intrinsic::aarch64_neon_ld3r:
6861 case Intrinsic::aarch64_neon_ld4r: {
6862 Info.opc = ISD::INTRINSIC_W_CHAIN;
6863 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006864 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006865 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6866 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6867 Info.offset = 0;
6868 Info.align = 0;
6869 Info.vol = false; // volatile loads with NEON intrinsics not supported
6870 Info.readMem = true;
6871 Info.writeMem = false;
6872 return true;
6873 }
6874 case Intrinsic::aarch64_neon_st2:
6875 case Intrinsic::aarch64_neon_st3:
6876 case Intrinsic::aarch64_neon_st4:
6877 case Intrinsic::aarch64_neon_st1x2:
6878 case Intrinsic::aarch64_neon_st1x3:
6879 case Intrinsic::aarch64_neon_st1x4:
6880 case Intrinsic::aarch64_neon_st2lane:
6881 case Intrinsic::aarch64_neon_st3lane:
6882 case Intrinsic::aarch64_neon_st4lane: {
6883 Info.opc = ISD::INTRINSIC_VOID;
6884 // Conservatively set memVT to the entire set of vectors stored.
6885 unsigned NumElts = 0;
6886 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6887 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6888 if (!ArgTy->isVectorTy())
6889 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006890 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006891 }
6892 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6893 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6894 Info.offset = 0;
6895 Info.align = 0;
6896 Info.vol = false; // volatile stores with NEON intrinsics not supported
6897 Info.readMem = false;
6898 Info.writeMem = true;
6899 return true;
6900 }
6901 case Intrinsic::aarch64_ldaxr:
6902 case Intrinsic::aarch64_ldxr: {
6903 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6904 Info.opc = ISD::INTRINSIC_W_CHAIN;
6905 Info.memVT = MVT::getVT(PtrTy->getElementType());
6906 Info.ptrVal = I.getArgOperand(0);
6907 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006908 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006909 Info.vol = true;
6910 Info.readMem = true;
6911 Info.writeMem = false;
6912 return true;
6913 }
6914 case Intrinsic::aarch64_stlxr:
6915 case Intrinsic::aarch64_stxr: {
6916 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6917 Info.opc = ISD::INTRINSIC_W_CHAIN;
6918 Info.memVT = MVT::getVT(PtrTy->getElementType());
6919 Info.ptrVal = I.getArgOperand(1);
6920 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006921 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006922 Info.vol = true;
6923 Info.readMem = false;
6924 Info.writeMem = true;
6925 return true;
6926 }
6927 case Intrinsic::aarch64_ldaxp:
6928 case Intrinsic::aarch64_ldxp: {
6929 Info.opc = ISD::INTRINSIC_W_CHAIN;
6930 Info.memVT = MVT::i128;
6931 Info.ptrVal = I.getArgOperand(0);
6932 Info.offset = 0;
6933 Info.align = 16;
6934 Info.vol = true;
6935 Info.readMem = true;
6936 Info.writeMem = false;
6937 return true;
6938 }
6939 case Intrinsic::aarch64_stlxp:
6940 case Intrinsic::aarch64_stxp: {
6941 Info.opc = ISD::INTRINSIC_W_CHAIN;
6942 Info.memVT = MVT::i128;
6943 Info.ptrVal = I.getArgOperand(2);
6944 Info.offset = 0;
6945 Info.align = 16;
6946 Info.vol = true;
6947 Info.readMem = false;
6948 Info.writeMem = true;
6949 return true;
6950 }
6951 default:
6952 break;
6953 }
6954
6955 return false;
6956}
6957
6958// Truncations from 64-bit GPR to 32-bit GPR is free.
6959bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6960 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6961 return false;
6962 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6963 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006964 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006965}
6966bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006967 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006968 return false;
6969 unsigned NumBits1 = VT1.getSizeInBits();
6970 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006971 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006972}
6973
Chad Rosier54390052015-02-23 19:15:16 +00006974/// Check if it is profitable to hoist instruction in then/else to if.
6975/// Not profitable if I and it's user can form a FMA instruction
6976/// because we prefer FMSUB/FMADD.
6977bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6978 if (I->getOpcode() != Instruction::FMul)
6979 return true;
6980
6981 if (I->getNumUses() != 1)
6982 return true;
6983
6984 Instruction *User = I->user_back();
6985
6986 if (User &&
6987 !(User->getOpcode() == Instruction::FSub ||
6988 User->getOpcode() == Instruction::FAdd))
6989 return true;
6990
6991 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006992 const DataLayout &DL = I->getModule()->getDataLayout();
6993 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006994
Eric Christopher114fa1c2016-02-29 22:50:49 +00006995 return !(isFMAFasterThanFMulAndFAdd(VT) &&
6996 isOperationLegalOrCustom(ISD::FMA, VT) &&
6997 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
6998 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00006999}
7000
Tim Northover3b0846e2014-05-24 12:50:23 +00007001// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7002// 64-bit GPR.
7003bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7004 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7005 return false;
7006 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7007 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007008 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007009}
7010bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007011 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007012 return false;
7013 unsigned NumBits1 = VT1.getSizeInBits();
7014 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007015 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007016}
7017
7018bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7019 EVT VT1 = Val.getValueType();
7020 if (isZExtFree(VT1, VT2)) {
7021 return true;
7022 }
7023
7024 if (Val.getOpcode() != ISD::LOAD)
7025 return false;
7026
7027 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007028 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7029 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7030 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007031}
7032
Quentin Colombet6843ac42015-03-31 20:52:32 +00007033bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7034 if (isa<FPExtInst>(Ext))
7035 return false;
7036
7037 // Vector types are next free.
7038 if (Ext->getType()->isVectorTy())
7039 return false;
7040
7041 for (const Use &U : Ext->uses()) {
7042 // The extension is free if we can fold it with a left shift in an
7043 // addressing mode or an arithmetic operation: add, sub, and cmp.
7044
7045 // Is there a shift?
7046 const Instruction *Instr = cast<Instruction>(U.getUser());
7047
7048 // Is this a constant shift?
7049 switch (Instr->getOpcode()) {
7050 case Instruction::Shl:
7051 if (!isa<ConstantInt>(Instr->getOperand(1)))
7052 return false;
7053 break;
7054 case Instruction::GetElementPtr: {
7055 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007056 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007057 std::advance(GTI, U.getOperandNo());
7058 Type *IdxTy = *GTI;
7059 // This extension will end up with a shift because of the scaling factor.
7060 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7061 // Get the shift amount based on the scaling factor:
7062 // log2(sizeof(IdxTy)) - log2(8).
7063 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007064 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007065 // Is the constant foldable in the shift of the addressing mode?
7066 // I.e., shift amount is between 1 and 4 inclusive.
7067 if (ShiftAmt == 0 || ShiftAmt > 4)
7068 return false;
7069 break;
7070 }
7071 case Instruction::Trunc:
7072 // Check if this is a noop.
7073 // trunc(sext ty1 to ty2) to ty1.
7074 if (Instr->getType() == Ext->getOperand(0)->getType())
7075 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00007076 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007077 default:
7078 return false;
7079 }
7080
7081 // At this point we can use the bfm family, so this extension is free
7082 // for that use.
7083 }
7084 return true;
7085}
7086
Tim Northover3b0846e2014-05-24 12:50:23 +00007087bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7088 unsigned &RequiredAligment) const {
7089 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7090 return false;
7091 // Cyclone supports unaligned accesses.
7092 RequiredAligment = 0;
7093 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7094 return NumBits == 32 || NumBits == 64;
7095}
7096
7097bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7098 unsigned &RequiredAligment) const {
7099 if (!LoadedType.isSimple() ||
7100 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7101 return false;
7102 // Cyclone supports unaligned accesses.
7103 RequiredAligment = 0;
7104 unsigned NumBits = LoadedType.getSizeInBits();
7105 return NumBits == 32 || NumBits == 64;
7106}
7107
Hao Liu7ec8ee32015-06-26 02:32:07 +00007108/// \brief Lower an interleaved load into a ldN intrinsic.
7109///
7110/// E.g. Lower an interleaved load (Factor = 2):
7111/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7112/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7113/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7114///
7115/// Into:
7116/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7117/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7118/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7119bool AArch64TargetLowering::lowerInterleavedLoad(
7120 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7121 ArrayRef<unsigned> Indices, unsigned Factor) const {
7122 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7123 "Invalid interleave factor");
7124 assert(!Shuffles.empty() && "Empty shufflevector input");
7125 assert(Shuffles.size() == Indices.size() &&
7126 "Unmatched number of shufflevectors and indices");
7127
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007128 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007129
7130 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007131 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007132
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007133 // Skip if we do not have NEON and skip illegal vector types.
7134 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007135 return false;
7136
7137 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7138 // load integer vectors first and then convert to pointer vectors.
7139 Type *EltTy = VecTy->getVectorElementType();
7140 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007141 VecTy =
7142 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007143
7144 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7145 Type *Tys[2] = {VecTy, PtrTy};
7146 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7147 Intrinsic::aarch64_neon_ld3,
7148 Intrinsic::aarch64_neon_ld4};
7149 Function *LdNFunc =
7150 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7151
7152 IRBuilder<> Builder(LI);
7153 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7154
7155 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7156
7157 // Replace uses of each shufflevector with the corresponding vector loaded
7158 // by ldN.
7159 for (unsigned i = 0; i < Shuffles.size(); i++) {
7160 ShuffleVectorInst *SVI = Shuffles[i];
7161 unsigned Index = Indices[i];
7162
7163 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7164
7165 // Convert the integer vector to pointer vector if the element is pointer.
7166 if (EltTy->isPointerTy())
7167 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7168
7169 SVI->replaceAllUsesWith(SubVec);
7170 }
7171
7172 return true;
7173}
7174
7175/// \brief Get a mask consisting of sequential integers starting from \p Start.
7176///
7177/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7178static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7179 unsigned NumElts) {
7180 SmallVector<Constant *, 16> Mask;
7181 for (unsigned i = 0; i < NumElts; i++)
7182 Mask.push_back(Builder.getInt32(Start + i));
7183
7184 return ConstantVector::get(Mask);
7185}
7186
7187/// \brief Lower an interleaved store into a stN intrinsic.
7188///
7189/// E.g. Lower an interleaved store (Factor = 3):
7190/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7191/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7192/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7193///
7194/// Into:
7195/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7196/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7197/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7198/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7199///
7200/// Note that the new shufflevectors will be removed and we'll only generate one
7201/// st3 instruction in CodeGen.
7202bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7203 ShuffleVectorInst *SVI,
7204 unsigned Factor) const {
7205 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7206 "Invalid interleave factor");
7207
7208 VectorType *VecTy = SVI->getType();
7209 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7210 "Invalid interleaved store");
7211
7212 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7213 Type *EltTy = VecTy->getVectorElementType();
7214 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7215
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007216 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007217 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007218
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007219 // Skip if we do not have NEON and skip illegal vector types.
7220 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007221 return false;
7222
7223 Value *Op0 = SVI->getOperand(0);
7224 Value *Op1 = SVI->getOperand(1);
7225 IRBuilder<> Builder(SI);
7226
7227 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7228 // vectors to integer vectors.
7229 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007230 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007231 unsigned NumOpElts =
7232 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7233
7234 // Convert to the corresponding integer vector.
7235 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7236 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7237 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7238
7239 SubVecTy = VectorType::get(IntTy, NumSubElts);
7240 }
7241
7242 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7243 Type *Tys[2] = {SubVecTy, PtrTy};
7244 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7245 Intrinsic::aarch64_neon_st3,
7246 Intrinsic::aarch64_neon_st4};
7247 Function *StNFunc =
7248 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7249
7250 SmallVector<Value *, 5> Ops;
7251
7252 // Split the shufflevector operands into sub vectors for the new stN call.
7253 for (unsigned i = 0; i < Factor; i++)
7254 Ops.push_back(Builder.CreateShuffleVector(
7255 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7256
7257 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7258 Builder.CreateCall(StNFunc, Ops);
7259 return true;
7260}
7261
Tim Northover3b0846e2014-05-24 12:50:23 +00007262static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7263 unsigned AlignCheck) {
7264 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7265 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7266}
7267
7268EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7269 unsigned SrcAlign, bool IsMemset,
7270 bool ZeroMemset,
7271 bool MemcpyStrSrc,
7272 MachineFunction &MF) const {
7273 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7274 // instruction to materialize the v2i64 zero and one store (with restrictive
7275 // addressing mode). Just do two i64 store of zero-registers.
7276 bool Fast;
7277 const Function *F = MF.getFunction();
7278 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007279 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007280 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007281 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007282 return MVT::f128;
7283
Lang Hames90333852015-04-09 03:40:33 +00007284 if (Size >= 8 &&
7285 (memOpAlign(SrcAlign, DstAlign, 8) ||
7286 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7287 return MVT::i64;
7288
7289 if (Size >= 4 &&
7290 (memOpAlign(SrcAlign, DstAlign, 4) ||
7291 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007292 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007293
7294 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007295}
7296
7297// 12-bit optionally shifted immediates are legal for adds.
7298bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berry486f49c2016-06-07 16:48:43 +00007299 // Avoid UB for INT64_MIN.
7300 if (Immed == std::numeric_limits<int64_t>::min())
7301 return false;
7302 // Same encoding for add/sub, just flip the sign.
7303 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007304 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007305}
7306
7307// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7308// immediates is the same as for an add or a sub.
7309bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007310 return isLegalAddImmediate(Immed);
7311}
7312
7313/// isLegalAddressingMode - Return true if the addressing mode represented
7314/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007315bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7316 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007317 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007318 // AArch64 has five basic addressing modes:
7319 // reg
7320 // reg + 9-bit signed offset
7321 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7322 // reg1 + reg2
7323 // reg + SIZE_IN_BYTES * reg
7324
7325 // No global is ever allowed as a base.
7326 if (AM.BaseGV)
7327 return false;
7328
7329 // No reg+reg+imm addressing.
7330 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7331 return false;
7332
7333 // check reg + imm case:
7334 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7335 uint64_t NumBytes = 0;
7336 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007337 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007338 NumBytes = NumBits / 8;
7339 if (!isPowerOf2_64(NumBits))
7340 NumBytes = 0;
7341 }
7342
7343 if (!AM.Scale) {
7344 int64_t Offset = AM.BaseOffs;
7345
7346 // 9-bit signed offset
7347 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7348 return true;
7349
7350 // 12-bit unsigned offset
7351 unsigned shift = Log2_64(NumBytes);
7352 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7353 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7354 (Offset >> shift) << shift == Offset)
7355 return true;
7356 return false;
7357 }
7358
7359 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7360
Eric Christopher114fa1c2016-02-29 22:50:49 +00007361 return !AM.Scale || AM.Scale == 1 ||
7362 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007363}
7364
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007365int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7366 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007367 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007368 // Scaling factors are not free at all.
7369 // Operands | Rt Latency
7370 // -------------------------------------------
7371 // Rt, [Xn, Xm] | 4
7372 // -------------------------------------------
7373 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7374 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007375 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007376 // Scale represents reg2 * scale, thus account for 1 if
7377 // it is not equal to 0 or 1.
7378 return AM.Scale != 0 && AM.Scale != 1;
7379 return -1;
7380}
7381
7382bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7383 VT = VT.getScalarType();
7384
7385 if (!VT.isSimple())
7386 return false;
7387
7388 switch (VT.getSimpleVT().SimpleTy) {
7389 case MVT::f32:
7390 case MVT::f64:
7391 return true;
7392 default:
7393 break;
7394 }
7395
7396 return false;
7397}
7398
7399const MCPhysReg *
7400AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7401 // LR is a callee-save register, but we must treat it as clobbered by any call
7402 // site. Hence we include LR in the scratch registers, which are in turn added
7403 // as implicit-defs for stackmaps and patchpoints.
7404 static const MCPhysReg ScratchRegs[] = {
7405 AArch64::X16, AArch64::X17, AArch64::LR, 0
7406 };
7407 return ScratchRegs;
7408}
7409
7410bool
7411AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7412 EVT VT = N->getValueType(0);
7413 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7414 // it with shift to let it be lowered to UBFX.
7415 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7416 isa<ConstantSDNode>(N->getOperand(1))) {
7417 uint64_t TruncMask = N->getConstantOperandVal(1);
7418 if (isMask_64(TruncMask) &&
7419 N->getOperand(0).getOpcode() == ISD::SRL &&
7420 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7421 return false;
7422 }
7423 return true;
7424}
7425
7426bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7427 Type *Ty) const {
7428 assert(Ty->isIntegerTy());
7429
7430 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7431 if (BitSize == 0)
7432 return false;
7433
7434 int64_t Val = Imm.getSExtValue();
7435 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7436 return true;
7437
7438 if ((int64_t)Val < 0)
7439 Val = ~Val;
7440 if (BitSize == 32)
7441 Val &= (1LL << 32) - 1;
7442
7443 unsigned LZ = countLeadingZeros((uint64_t)Val);
7444 unsigned Shift = (63 - LZ) / 16;
7445 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007446 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007447}
7448
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007449/// Turn vector tests of the signbit in the form of:
7450/// xor (sra X, elt_size(X)-1), -1
7451/// into:
7452/// cmge X, X, #0
7453static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7454 const AArch64Subtarget *Subtarget) {
7455 EVT VT = N->getValueType(0);
7456 if (!Subtarget->hasNEON() || !VT.isVector())
7457 return SDValue();
7458
7459 // There must be a shift right algebraic before the xor, and the xor must be a
7460 // 'not' operation.
7461 SDValue Shift = N->getOperand(0);
7462 SDValue Ones = N->getOperand(1);
7463 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7464 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7465 return SDValue();
7466
7467 // The shift should be smearing the sign bit across each vector element.
7468 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7469 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7470 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7471 return SDValue();
7472
7473 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7474}
7475
Tim Northover3b0846e2014-05-24 12:50:23 +00007476// Generate SUBS and CSEL for integer abs.
7477static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7478 EVT VT = N->getValueType(0);
7479
7480 SDValue N0 = N->getOperand(0);
7481 SDValue N1 = N->getOperand(1);
7482 SDLoc DL(N);
7483
7484 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7485 // and change it to SUB and CSEL.
7486 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7487 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7488 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7489 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7490 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007491 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007492 N0.getOperand(0));
7493 // Generate SUBS & CSEL.
7494 SDValue Cmp =
7495 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007496 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007497 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007498 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007499 SDValue(Cmp.getNode(), 1));
7500 }
7501 return SDValue();
7502}
7503
Tim Northover3b0846e2014-05-24 12:50:23 +00007504static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7505 TargetLowering::DAGCombinerInfo &DCI,
7506 const AArch64Subtarget *Subtarget) {
7507 if (DCI.isBeforeLegalizeOps())
7508 return SDValue();
7509
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007510 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7511 return Cmp;
7512
Tim Northover3b0846e2014-05-24 12:50:23 +00007513 return performIntegerAbsCombine(N, DAG);
7514}
7515
Chad Rosier17020f92014-07-23 14:57:52 +00007516SDValue
7517AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7518 SelectionDAG &DAG,
7519 std::vector<SDNode *> *Created) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +00007520 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7521 if (isIntDivCheap(N->getValueType(0), Attr))
7522 return SDValue(N,0); // Lower SDIV as SDIV
7523
Chad Rosier17020f92014-07-23 14:57:52 +00007524 // fold (sdiv X, pow2)
7525 EVT VT = N->getValueType(0);
7526 if ((VT != MVT::i32 && VT != MVT::i64) ||
7527 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7528 return SDValue();
7529
7530 SDLoc DL(N);
7531 SDValue N0 = N->getOperand(0);
7532 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007533 SDValue Zero = DAG.getConstant(0, DL, VT);
7534 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007535
7536 // Add (N0 < 0) ? Pow2 - 1 : 0;
7537 SDValue CCVal;
7538 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7539 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7540 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7541
7542 if (Created) {
7543 Created->push_back(Cmp.getNode());
7544 Created->push_back(Add.getNode());
7545 Created->push_back(CSel.getNode());
7546 }
7547
7548 // Divide by pow2.
7549 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007550 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007551
7552 // If we're dividing by a positive value, we're done. Otherwise, we must
7553 // negate the result.
7554 if (Divisor.isNonNegative())
7555 return SRA;
7556
7557 if (Created)
7558 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007559 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007560}
7561
Tim Northover3b0846e2014-05-24 12:50:23 +00007562static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7563 TargetLowering::DAGCombinerInfo &DCI,
7564 const AArch64Subtarget *Subtarget) {
7565 if (DCI.isBeforeLegalizeOps())
7566 return SDValue();
7567
7568 // Multiplication of a power of two plus/minus one can be done more
7569 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7570 // future CPUs have a cheaper MADD instruction, this may need to be
7571 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7572 // 64-bit is 5 cycles, so this is always a win.
7573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00007574 const APInt &Value = C->getAPIntValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00007575 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007576 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007577 if (Value.isNonNegative()) {
7578 // (mul x, 2^N + 1) => (add (shl x, N), x)
7579 APInt VM1 = Value - 1;
7580 if (VM1.isPowerOf2()) {
7581 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007582 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7583 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7584 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007585 N->getOperand(0));
7586 }
7587 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7588 APInt VP1 = Value + 1;
7589 if (VP1.isPowerOf2()) {
7590 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007591 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7592 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7593 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007594 N->getOperand(0));
7595 }
7596 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007597 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7598 APInt VNP1 = -Value + 1;
7599 if (VNP1.isPowerOf2()) {
7600 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007601 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7602 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7603 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007604 ShiftedVal);
7605 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007606 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7607 APInt VNM1 = -Value - 1;
7608 if (VNM1.isPowerOf2()) {
7609 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007610 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7611 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007612 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007613 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7614 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007615 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007616 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007617 }
7618 return SDValue();
7619}
7620
Jim Grosbachf7502c42014-07-18 00:40:52 +00007621static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7622 SelectionDAG &DAG) {
7623 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7624 // optimize away operation when it's from a constant.
7625 //
7626 // The general transformation is:
7627 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7628 // AND(VECTOR_CMP(x,y), constant2)
7629 // constant2 = UNARYOP(constant)
7630
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007631 // Early exit if this isn't a vector operation, the operand of the
7632 // unary operation isn't a bitwise AND, or if the sizes of the operations
7633 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007634 EVT VT = N->getValueType(0);
7635 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007636 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7637 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007638 return SDValue();
7639
Jim Grosbach724e4382014-07-23 20:41:43 +00007640 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007641 // make the transformation for non-constant splats as well, but it's unclear
7642 // that would be a benefit as it would not eliminate any operations, just
7643 // perform one more step in scalar code before moving to the vector unit.
7644 if (BuildVectorSDNode *BV =
7645 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007646 // Bail out if the vector isn't a constant.
7647 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007648 return SDValue();
7649
7650 // Everything checks out. Build up the new and improved node.
7651 SDLoc DL(N);
7652 EVT IntVT = BV->getValueType(0);
7653 // Create a new constant of the appropriate type for the transformed
7654 // DAG.
7655 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7656 // The AND node needs bitcasts to/from an integer vector type around it.
7657 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7658 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7659 N->getOperand(0)->getOperand(0), MaskConst);
7660 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7661 return Res;
7662 }
7663
7664 return SDValue();
7665}
7666
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007667static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7668 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007669 // First try to optimize away the conversion when it's conditionally from
7670 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007671 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007672 return Res;
7673
Tim Northover3b0846e2014-05-24 12:50:23 +00007674 EVT VT = N->getValueType(0);
7675 if (VT != MVT::f32 && VT != MVT::f64)
7676 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007677
Tim Northover3b0846e2014-05-24 12:50:23 +00007678 // Only optimize when the source and destination types have the same width.
7679 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7680 return SDValue();
7681
7682 // If the result of an integer load is only used by an integer-to-float
7683 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007684 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007685 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007686 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007687 // Do not change the width of a volatile load.
7688 !cast<LoadSDNode>(N0)->isVolatile()) {
7689 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7690 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00007691 LN0->getPointerInfo(), LN0->getAlignment(),
7692 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00007693
7694 // Make sure successors of the original load stay after it by updating them
7695 // to use the new Chain.
7696 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7697
7698 unsigned Opcode =
7699 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7700 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7701 }
7702
7703 return SDValue();
7704}
7705
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007706/// Fold a floating-point multiply by power of two into floating-point to
7707/// fixed-point conversion.
7708static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00007709 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007710 const AArch64Subtarget *Subtarget) {
7711 if (!Subtarget->hasNEON())
7712 return SDValue();
7713
7714 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00007715 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7716 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007717 return SDValue();
7718
7719 SDValue ConstVec = Op->getOperand(1);
7720 if (!isa<BuildVectorSDNode>(ConstVec))
7721 return SDValue();
7722
7723 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7724 uint32_t FloatBits = FloatTy.getSizeInBits();
7725 if (FloatBits != 32 && FloatBits != 64)
7726 return SDValue();
7727
7728 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7729 uint32_t IntBits = IntTy.getSizeInBits();
7730 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7731 return SDValue();
7732
7733 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7734 if (IntBits > FloatBits)
7735 return SDValue();
7736
7737 BitVector UndefElements;
7738 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7739 int32_t Bits = IntBits == 64 ? 64 : 32;
7740 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7741 if (C == -1 || C == 0 || C > Bits)
7742 return SDValue();
7743
7744 MVT ResTy;
7745 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7746 switch (NumLanes) {
7747 default:
7748 return SDValue();
7749 case 2:
7750 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7751 break;
7752 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00007753 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007754 break;
7755 }
7756
Silviu Barangafa00ba32016-08-08 13:13:57 +00007757 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7758 return SDValue();
7759
7760 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7761 "Illegal vector type after legalization");
7762
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007763 SDLoc DL(N);
7764 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7765 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7766 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7767 SDValue FixConv =
7768 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7769 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7770 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7771 // We can handle smaller integers by generating an extra trunc.
7772 if (IntBits < FloatBits)
7773 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7774
7775 return FixConv;
7776}
7777
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007778/// Fold a floating-point divide by power of two into fixed-point to
7779/// floating-point conversion.
7780static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00007781 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007782 const AArch64Subtarget *Subtarget) {
7783 if (!Subtarget->hasNEON())
7784 return SDValue();
7785
7786 SDValue Op = N->getOperand(0);
7787 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00007788 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7789 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007790 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7791 return SDValue();
7792
7793 SDValue ConstVec = N->getOperand(1);
7794 if (!isa<BuildVectorSDNode>(ConstVec))
7795 return SDValue();
7796
7797 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7798 int32_t IntBits = IntTy.getSizeInBits();
7799 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7800 return SDValue();
7801
7802 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7803 int32_t FloatBits = FloatTy.getSizeInBits();
7804 if (FloatBits != 32 && FloatBits != 64)
7805 return SDValue();
7806
7807 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7808 if (IntBits > FloatBits)
7809 return SDValue();
7810
7811 BitVector UndefElements;
7812 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7813 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7814 if (C == -1 || C == 0 || C > FloatBits)
7815 return SDValue();
7816
7817 MVT ResTy;
7818 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7819 switch (NumLanes) {
7820 default:
7821 return SDValue();
7822 case 2:
7823 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7824 break;
7825 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00007826 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007827 break;
7828 }
7829
Tim Northover85cf5642016-08-26 18:52:31 +00007830 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7831 return SDValue();
7832
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007833 SDLoc DL(N);
7834 SDValue ConvInput = Op.getOperand(0);
7835 bool IsSigned = Opc == ISD::SINT_TO_FP;
7836 if (IntBits < FloatBits)
7837 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7838 ResTy, ConvInput);
7839
7840 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7841 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7842 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7843 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7844 DAG.getConstant(C, DL, MVT::i32));
7845}
7846
Tim Northover3b0846e2014-05-24 12:50:23 +00007847/// An EXTR instruction is made up of two shifts, ORed together. This helper
7848/// searches for and classifies those shifts.
7849static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7850 bool &FromHi) {
7851 if (N.getOpcode() == ISD::SHL)
7852 FromHi = false;
7853 else if (N.getOpcode() == ISD::SRL)
7854 FromHi = true;
7855 else
7856 return false;
7857
7858 if (!isa<ConstantSDNode>(N.getOperand(1)))
7859 return false;
7860
7861 ShiftAmount = N->getConstantOperandVal(1);
7862 Src = N->getOperand(0);
7863 return true;
7864}
7865
7866/// EXTR instruction extracts a contiguous chunk of bits from two existing
7867/// registers viewed as a high/low pair. This function looks for the pattern:
7868/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7869/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7870/// independent.
7871static SDValue tryCombineToEXTR(SDNode *N,
7872 TargetLowering::DAGCombinerInfo &DCI) {
7873 SelectionDAG &DAG = DCI.DAG;
7874 SDLoc DL(N);
7875 EVT VT = N->getValueType(0);
7876
7877 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7878
7879 if (VT != MVT::i32 && VT != MVT::i64)
7880 return SDValue();
7881
7882 SDValue LHS;
7883 uint32_t ShiftLHS = 0;
7884 bool LHSFromHi = 0;
7885 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7886 return SDValue();
7887
7888 SDValue RHS;
7889 uint32_t ShiftRHS = 0;
7890 bool RHSFromHi = 0;
7891 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7892 return SDValue();
7893
7894 // If they're both trying to come from the high part of the register, they're
7895 // not really an EXTR.
7896 if (LHSFromHi == RHSFromHi)
7897 return SDValue();
7898
7899 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7900 return SDValue();
7901
7902 if (LHSFromHi) {
7903 std::swap(LHS, RHS);
7904 std::swap(ShiftLHS, ShiftRHS);
7905 }
7906
7907 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007908 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007909}
7910
7911static SDValue tryCombineToBSL(SDNode *N,
7912 TargetLowering::DAGCombinerInfo &DCI) {
7913 EVT VT = N->getValueType(0);
7914 SelectionDAG &DAG = DCI.DAG;
7915 SDLoc DL(N);
7916
7917 if (!VT.isVector())
7918 return SDValue();
7919
7920 SDValue N0 = N->getOperand(0);
7921 if (N0.getOpcode() != ISD::AND)
7922 return SDValue();
7923
7924 SDValue N1 = N->getOperand(1);
7925 if (N1.getOpcode() != ISD::AND)
7926 return SDValue();
7927
7928 // We only have to look for constant vectors here since the general, variable
7929 // case can be handled in TableGen.
7930 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7931 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7932 for (int i = 1; i >= 0; --i)
7933 for (int j = 1; j >= 0; --j) {
7934 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7935 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7936 if (!BVN0 || !BVN1)
7937 continue;
7938
7939 bool FoundMatch = true;
7940 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7941 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7942 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7943 if (!CN0 || !CN1 ||
7944 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7945 FoundMatch = false;
7946 break;
7947 }
7948 }
7949
7950 if (FoundMatch)
7951 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7952 N0->getOperand(1 - i), N1->getOperand(1 - j));
7953 }
7954
7955 return SDValue();
7956}
7957
7958static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7959 const AArch64Subtarget *Subtarget) {
7960 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00007961 SelectionDAG &DAG = DCI.DAG;
7962 EVT VT = N->getValueType(0);
7963
7964 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7965 return SDValue();
7966
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007967 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007968 return Res;
7969
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007970 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007971 return Res;
7972
7973 return SDValue();
7974}
7975
Chad Rosier14aa2ad2016-05-26 19:41:33 +00007976static SDValue performSRLCombine(SDNode *N,
7977 TargetLowering::DAGCombinerInfo &DCI) {
7978 SelectionDAG &DAG = DCI.DAG;
7979 EVT VT = N->getValueType(0);
7980 if (VT != MVT::i32 && VT != MVT::i64)
7981 return SDValue();
7982
7983 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
7984 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
7985 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
7986 SDValue N0 = N->getOperand(0);
7987 if (N0.getOpcode() == ISD::BSWAP) {
7988 SDLoc DL(N);
7989 SDValue N1 = N->getOperand(1);
7990 SDValue N00 = N0.getOperand(0);
7991 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
7992 uint64_t ShiftAmt = C->getZExtValue();
7993 if (VT == MVT::i32 && ShiftAmt == 16 &&
7994 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
7995 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7996 if (VT == MVT::i64 && ShiftAmt == 32 &&
7997 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
7998 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7999 }
8000 }
8001 return SDValue();
8002}
8003
Tim Northover3b0846e2014-05-24 12:50:23 +00008004static SDValue performBitcastCombine(SDNode *N,
8005 TargetLowering::DAGCombinerInfo &DCI,
8006 SelectionDAG &DAG) {
8007 // Wait 'til after everything is legalized to try this. That way we have
8008 // legal vector types and such.
8009 if (DCI.isBeforeLegalizeOps())
8010 return SDValue();
8011
8012 // Remove extraneous bitcasts around an extract_subvector.
8013 // For example,
8014 // (v4i16 (bitconvert
8015 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8016 // becomes
8017 // (extract_subvector ((v8i16 ...), (i64 4)))
8018
8019 // Only interested in 64-bit vectors as the ultimate result.
8020 EVT VT = N->getValueType(0);
8021 if (!VT.isVector())
8022 return SDValue();
8023 if (VT.getSimpleVT().getSizeInBits() != 64)
8024 return SDValue();
8025 // Is the operand an extract_subvector starting at the beginning or halfway
8026 // point of the vector? A low half may also come through as an
8027 // EXTRACT_SUBREG, so look for that, too.
8028 SDValue Op0 = N->getOperand(0);
8029 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8030 !(Op0->isMachineOpcode() &&
8031 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8032 return SDValue();
8033 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8034 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8035 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8036 return SDValue();
8037 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8038 if (idx != AArch64::dsub)
8039 return SDValue();
8040 // The dsub reference is equivalent to a lane zero subvector reference.
8041 idx = 0;
8042 }
8043 // Look through the bitcast of the input to the extract.
8044 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8045 return SDValue();
8046 SDValue Source = Op0->getOperand(0)->getOperand(0);
8047 // If the source type has twice the number of elements as our destination
8048 // type, we know this is an extract of the high or low half of the vector.
8049 EVT SVT = Source->getValueType(0);
8050 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8051 return SDValue();
8052
8053 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8054
8055 // Create the simplified form to just extract the low or high half of the
8056 // vector directly rather than bothering with the bitcasts.
8057 SDLoc dl(N);
8058 unsigned NumElements = VT.getVectorNumElements();
8059 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008060 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008061 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8062 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008063 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008064 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8065 Source, SubReg),
8066 0);
8067 }
8068}
8069
8070static SDValue performConcatVectorsCombine(SDNode *N,
8071 TargetLowering::DAGCombinerInfo &DCI,
8072 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008073 SDLoc dl(N);
8074 EVT VT = N->getValueType(0);
8075 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8076
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008077 // Optimize concat_vectors of truncated vectors, where the intermediate
8078 // type is illegal, to avoid said illegality, e.g.,
8079 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8080 // (v2i16 (truncate (v2i64)))))
8081 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008082 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8083 // (v4i32 (bitcast (v2i64))),
8084 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008085 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8086 // on both input and result type, so we might generate worse code.
8087 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8088 if (N->getNumOperands() == 2 &&
8089 N0->getOpcode() == ISD::TRUNCATE &&
8090 N1->getOpcode() == ISD::TRUNCATE) {
8091 SDValue N00 = N0->getOperand(0);
8092 SDValue N10 = N1->getOperand(0);
8093 EVT N00VT = N00.getValueType();
8094
8095 if (N00VT == N10.getValueType() &&
8096 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8097 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008098 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8099 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8100 for (size_t i = 0; i < Mask.size(); ++i)
8101 Mask[i] = i * 2;
8102 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8103 DAG.getVectorShuffle(
8104 MidVT, dl,
8105 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8106 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008107 }
8108 }
8109
Tim Northover3b0846e2014-05-24 12:50:23 +00008110 // Wait 'til after everything is legalized to try this. That way we have
8111 // legal vector types and such.
8112 if (DCI.isBeforeLegalizeOps())
8113 return SDValue();
8114
Tim Northover3b0846e2014-05-24 12:50:23 +00008115 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8116 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8117 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008118 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008119 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008120 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008121 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008122 }
8123
8124 // Canonicalise concat_vectors so that the right-hand vector has as few
8125 // bit-casts as possible before its real operation. The primary matching
8126 // destination for these operations will be the narrowing "2" instructions,
8127 // which depend on the operation being performed on this right-hand vector.
8128 // For example,
8129 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8130 // becomes
8131 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8132
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008133 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008134 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008135 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008136 MVT RHSTy = RHS.getValueType().getSimpleVT();
8137 // If the RHS is not a vector, this is not the pattern we're looking for.
8138 if (!RHSTy.isVector())
8139 return SDValue();
8140
8141 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8142
8143 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8144 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008145 return DAG.getNode(ISD::BITCAST, dl, VT,
8146 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8147 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8148 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008149}
8150
8151static SDValue tryCombineFixedPointConvert(SDNode *N,
8152 TargetLowering::DAGCombinerInfo &DCI,
8153 SelectionDAG &DAG) {
8154 // Wait 'til after everything is legalized to try this. That way we have
8155 // legal vector types and such.
8156 if (DCI.isBeforeLegalizeOps())
8157 return SDValue();
8158 // Transform a scalar conversion of a value from a lane extract into a
8159 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8160 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8161 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8162 //
8163 // The second form interacts better with instruction selection and the
8164 // register allocator to avoid cross-class register copies that aren't
8165 // coalescable due to a lane reference.
8166
8167 // Check the operand and see if it originates from a lane extract.
8168 SDValue Op1 = N->getOperand(1);
8169 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8170 // Yep, no additional predication needed. Perform the transform.
8171 SDValue IID = N->getOperand(0);
8172 SDValue Shift = N->getOperand(2);
8173 SDValue Vec = Op1.getOperand(0);
8174 SDValue Lane = Op1.getOperand(1);
8175 EVT ResTy = N->getValueType(0);
8176 EVT VecResTy;
8177 SDLoc DL(N);
8178
8179 // The vector width should be 128 bits by the time we get here, even
8180 // if it started as 64 bits (the extract_vector handling will have
8181 // done so).
8182 assert(Vec.getValueType().getSizeInBits() == 128 &&
8183 "unexpected vector size on extract_vector_elt!");
8184 if (Vec.getValueType() == MVT::v4i32)
8185 VecResTy = MVT::v4f32;
8186 else if (Vec.getValueType() == MVT::v2i64)
8187 VecResTy = MVT::v2f64;
8188 else
Craig Topper2a30d782014-06-18 05:05:13 +00008189 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008190
8191 SDValue Convert =
8192 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8193 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8194 }
8195 return SDValue();
8196}
8197
8198// AArch64 high-vector "long" operations are formed by performing the non-high
8199// version on an extract_subvector of each operand which gets the high half:
8200//
8201// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8202//
8203// However, there are cases which don't have an extract_high explicitly, but
8204// have another operation that can be made compatible with one for free. For
8205// example:
8206//
8207// (dupv64 scalar) --> (extract_high (dup128 scalar))
8208//
8209// This routine does the actual conversion of such DUPs, once outer routines
8210// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008211// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8212// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008213static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008214 switch (N.getOpcode()) {
8215 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008216 case AArch64ISD::DUPLANE8:
8217 case AArch64ISD::DUPLANE16:
8218 case AArch64ISD::DUPLANE32:
8219 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008220 case AArch64ISD::MOVI:
8221 case AArch64ISD::MOVIshift:
8222 case AArch64ISD::MOVIedit:
8223 case AArch64ISD::MOVImsl:
8224 case AArch64ISD::MVNIshift:
8225 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008226 break;
8227 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008228 // FMOV could be supported, but isn't very useful, as it would only occur
8229 // if you passed a bitcast' floating point immediate to an eligible long
8230 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008231 return SDValue();
8232 }
8233
8234 MVT NarrowTy = N.getSimpleValueType();
8235 if (!NarrowTy.is64BitVector())
8236 return SDValue();
8237
8238 MVT ElementTy = NarrowTy.getVectorElementType();
8239 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008240 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008241
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008242 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008243 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8244 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008245 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008246}
8247
8248static bool isEssentiallyExtractSubvector(SDValue N) {
8249 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8250 return true;
8251
8252 return N.getOpcode() == ISD::BITCAST &&
8253 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8254}
8255
8256/// \brief Helper structure to keep track of ISD::SET_CC operands.
8257struct GenericSetCCInfo {
8258 const SDValue *Opnd0;
8259 const SDValue *Opnd1;
8260 ISD::CondCode CC;
8261};
8262
8263/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8264struct AArch64SetCCInfo {
8265 const SDValue *Cmp;
8266 AArch64CC::CondCode CC;
8267};
8268
8269/// \brief Helper structure to keep track of SetCC information.
8270union SetCCInfo {
8271 GenericSetCCInfo Generic;
8272 AArch64SetCCInfo AArch64;
8273};
8274
8275/// \brief Helper structure to be able to read SetCC information. If set to
8276/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8277/// GenericSetCCInfo.
8278struct SetCCInfoAndKind {
8279 SetCCInfo Info;
8280 bool IsAArch64;
8281};
8282
8283/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8284/// an
8285/// AArch64 lowered one.
8286/// \p SetCCInfo is filled accordingly.
8287/// \post SetCCInfo is meanginfull only when this function returns true.
8288/// \return True when Op is a kind of SET_CC operation.
8289static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8290 // If this is a setcc, this is straight forward.
8291 if (Op.getOpcode() == ISD::SETCC) {
8292 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8293 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8294 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8295 SetCCInfo.IsAArch64 = false;
8296 return true;
8297 }
8298 // Otherwise, check if this is a matching csel instruction.
8299 // In other words:
8300 // - csel 1, 0, cc
8301 // - csel 0, 1, !cc
8302 if (Op.getOpcode() != AArch64ISD::CSEL)
8303 return false;
8304 // Set the information about the operands.
8305 // TODO: we want the operands of the Cmp not the csel
8306 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8307 SetCCInfo.IsAArch64 = true;
8308 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8309 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8310
8311 // Check that the operands matches the constraints:
8312 // (1) Both operands must be constants.
8313 // (2) One must be 1 and the other must be 0.
8314 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8315 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8316
8317 // Check (1).
8318 if (!TValue || !FValue)
8319 return false;
8320
8321 // Check (2).
8322 if (!TValue->isOne()) {
8323 // Update the comparison when we are interested in !cc.
8324 std::swap(TValue, FValue);
8325 SetCCInfo.Info.AArch64.CC =
8326 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8327 }
8328 return TValue->isOne() && FValue->isNullValue();
8329}
8330
8331// Returns true if Op is setcc or zext of setcc.
8332static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8333 if (isSetCC(Op, Info))
8334 return true;
8335 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8336 isSetCC(Op->getOperand(0), Info));
8337}
8338
8339// The folding we want to perform is:
8340// (add x, [zext] (setcc cc ...) )
8341// -->
8342// (csel x, (add x, 1), !cc ...)
8343//
8344// The latter will get matched to a CSINC instruction.
8345static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8346 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8347 SDValue LHS = Op->getOperand(0);
8348 SDValue RHS = Op->getOperand(1);
8349 SetCCInfoAndKind InfoAndKind;
8350
8351 // If neither operand is a SET_CC, give up.
8352 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8353 std::swap(LHS, RHS);
8354 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8355 return SDValue();
8356 }
8357
8358 // FIXME: This could be generatized to work for FP comparisons.
8359 EVT CmpVT = InfoAndKind.IsAArch64
8360 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8361 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8362 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8363 return SDValue();
8364
8365 SDValue CCVal;
8366 SDValue Cmp;
8367 SDLoc dl(Op);
8368 if (InfoAndKind.IsAArch64) {
8369 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008370 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8371 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008372 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8373 } else
8374 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8375 *InfoAndKind.Info.Generic.Opnd1,
8376 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8377 CCVal, DAG, dl);
8378
8379 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008380 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008381 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8382}
8383
8384// The basic add/sub long vector instructions have variants with "2" on the end
8385// which act on the high-half of their inputs. They are normally matched by
8386// patterns like:
8387//
8388// (add (zeroext (extract_high LHS)),
8389// (zeroext (extract_high RHS)))
8390// -> uaddl2 vD, vN, vM
8391//
8392// However, if one of the extracts is something like a duplicate, this
8393// instruction can still be used profitably. This function puts the DAG into a
8394// more appropriate form for those patterns to trigger.
8395static SDValue performAddSubLongCombine(SDNode *N,
8396 TargetLowering::DAGCombinerInfo &DCI,
8397 SelectionDAG &DAG) {
8398 if (DCI.isBeforeLegalizeOps())
8399 return SDValue();
8400
8401 MVT VT = N->getSimpleValueType(0);
8402 if (!VT.is128BitVector()) {
8403 if (N->getOpcode() == ISD::ADD)
8404 return performSetccAddFolding(N, DAG);
8405 return SDValue();
8406 }
8407
8408 // Make sure both branches are extended in the same way.
8409 SDValue LHS = N->getOperand(0);
8410 SDValue RHS = N->getOperand(1);
8411 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8412 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8413 LHS.getOpcode() != RHS.getOpcode())
8414 return SDValue();
8415
8416 unsigned ExtType = LHS.getOpcode();
8417
8418 // It's not worth doing if at least one of the inputs isn't already an
8419 // extract, but we don't know which it'll be so we have to try both.
8420 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8421 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8422 if (!RHS.getNode())
8423 return SDValue();
8424
8425 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8426 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8427 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8428 if (!LHS.getNode())
8429 return SDValue();
8430
8431 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8432 }
8433
8434 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8435}
8436
8437// Massage DAGs which we can use the high-half "long" operations on into
8438// something isel will recognize better. E.g.
8439//
8440// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8441// (aarch64_neon_umull (extract_high (v2i64 vec)))
8442// (extract_high (v2i64 (dup128 scalar)))))
8443//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008444static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008445 TargetLowering::DAGCombinerInfo &DCI,
8446 SelectionDAG &DAG) {
8447 if (DCI.isBeforeLegalizeOps())
8448 return SDValue();
8449
Hal Finkelcd8664c2015-12-11 23:11:52 +00008450 SDValue LHS = N->getOperand(1);
8451 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008452 assert(LHS.getValueType().is64BitVector() &&
8453 RHS.getValueType().is64BitVector() &&
8454 "unexpected shape for long operation");
8455
8456 // Either node could be a DUP, but it's not worth doing both of them (you'd
8457 // just as well use the non-high version) so look for a corresponding extract
8458 // operation on the other "wing".
8459 if (isEssentiallyExtractSubvector(LHS)) {
8460 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8461 if (!RHS.getNode())
8462 return SDValue();
8463 } else if (isEssentiallyExtractSubvector(RHS)) {
8464 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8465 if (!LHS.getNode())
8466 return SDValue();
8467 }
8468
Hal Finkelcd8664c2015-12-11 23:11:52 +00008469 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8470 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008471}
8472
8473static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8474 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8475 unsigned ElemBits = ElemTy.getSizeInBits();
8476
8477 int64_t ShiftAmount;
8478 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8479 APInt SplatValue, SplatUndef;
8480 unsigned SplatBitSize;
8481 bool HasAnyUndefs;
8482 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8483 HasAnyUndefs, ElemBits) ||
8484 SplatBitSize != ElemBits)
8485 return SDValue();
8486
8487 ShiftAmount = SplatValue.getSExtValue();
8488 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8489 ShiftAmount = CVN->getSExtValue();
8490 } else
8491 return SDValue();
8492
8493 unsigned Opcode;
8494 bool IsRightShift;
8495 switch (IID) {
8496 default:
8497 llvm_unreachable("Unknown shift intrinsic");
8498 case Intrinsic::aarch64_neon_sqshl:
8499 Opcode = AArch64ISD::SQSHL_I;
8500 IsRightShift = false;
8501 break;
8502 case Intrinsic::aarch64_neon_uqshl:
8503 Opcode = AArch64ISD::UQSHL_I;
8504 IsRightShift = false;
8505 break;
8506 case Intrinsic::aarch64_neon_srshl:
8507 Opcode = AArch64ISD::SRSHR_I;
8508 IsRightShift = true;
8509 break;
8510 case Intrinsic::aarch64_neon_urshl:
8511 Opcode = AArch64ISD::URSHR_I;
8512 IsRightShift = true;
8513 break;
8514 case Intrinsic::aarch64_neon_sqshlu:
8515 Opcode = AArch64ISD::SQSHLU_I;
8516 IsRightShift = false;
8517 break;
8518 }
8519
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008520 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8521 SDLoc dl(N);
8522 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8523 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8524 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8525 SDLoc dl(N);
8526 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8527 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8528 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008529
8530 return SDValue();
8531}
8532
8533// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8534// the intrinsics must be legal and take an i32, this means there's almost
8535// certainly going to be a zext in the DAG which we can eliminate.
8536static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8537 SDValue AndN = N->getOperand(2);
8538 if (AndN.getOpcode() != ISD::AND)
8539 return SDValue();
8540
8541 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8542 if (!CMask || CMask->getZExtValue() != Mask)
8543 return SDValue();
8544
8545 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8546 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8547}
8548
Ahmed Bougachafab58922015-03-10 20:45:38 +00008549static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8550 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008551 SDLoc dl(N);
8552 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8553 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008554 N->getOperand(1).getSimpleValueType(),
8555 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008556 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008557}
8558
Tim Northover3b0846e2014-05-24 12:50:23 +00008559static SDValue performIntrinsicCombine(SDNode *N,
8560 TargetLowering::DAGCombinerInfo &DCI,
8561 const AArch64Subtarget *Subtarget) {
8562 SelectionDAG &DAG = DCI.DAG;
8563 unsigned IID = getIntrinsicID(N);
8564 switch (IID) {
8565 default:
8566 break;
8567 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8568 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8569 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008570 case Intrinsic::aarch64_neon_saddv:
8571 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8572 case Intrinsic::aarch64_neon_uaddv:
8573 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8574 case Intrinsic::aarch64_neon_sminv:
8575 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8576 case Intrinsic::aarch64_neon_uminv:
8577 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8578 case Intrinsic::aarch64_neon_smaxv:
8579 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8580 case Intrinsic::aarch64_neon_umaxv:
8581 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008582 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008583 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008584 N->getOperand(1), N->getOperand(2));
8585 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008586 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008587 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008588 case Intrinsic::aarch64_neon_fmaxnm:
8589 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8590 N->getOperand(1), N->getOperand(2));
8591 case Intrinsic::aarch64_neon_fminnm:
8592 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8593 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008594 case Intrinsic::aarch64_neon_smull:
8595 case Intrinsic::aarch64_neon_umull:
8596 case Intrinsic::aarch64_neon_pmull:
8597 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008598 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008599 case Intrinsic::aarch64_neon_sqshl:
8600 case Intrinsic::aarch64_neon_uqshl:
8601 case Intrinsic::aarch64_neon_sqshlu:
8602 case Intrinsic::aarch64_neon_srshl:
8603 case Intrinsic::aarch64_neon_urshl:
8604 return tryCombineShiftImm(IID, N, DAG);
8605 case Intrinsic::aarch64_crc32b:
8606 case Intrinsic::aarch64_crc32cb:
8607 return tryCombineCRC32(0xff, N, DAG);
8608 case Intrinsic::aarch64_crc32h:
8609 case Intrinsic::aarch64_crc32ch:
8610 return tryCombineCRC32(0xffff, N, DAG);
8611 }
8612 return SDValue();
8613}
8614
8615static SDValue performExtendCombine(SDNode *N,
8616 TargetLowering::DAGCombinerInfo &DCI,
8617 SelectionDAG &DAG) {
8618 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8619 // we can convert that DUP into another extract_high (of a bigger DUP), which
8620 // helps the backend to decide that an sabdl2 would be useful, saving a real
8621 // extract_high operation.
8622 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008623 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008624 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008625 unsigned IID = getIntrinsicID(ABDNode);
8626 if (IID == Intrinsic::aarch64_neon_sabd ||
8627 IID == Intrinsic::aarch64_neon_uabd) {
8628 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8629 if (!NewABD.getNode())
8630 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008631
Hal Finkelcd8664c2015-12-11 23:11:52 +00008632 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8633 NewABD);
8634 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008635 }
8636
8637 // This is effectively a custom type legalization for AArch64.
8638 //
8639 // Type legalization will split an extend of a small, legal, type to a larger
8640 // illegal type by first splitting the destination type, often creating
8641 // illegal source types, which then get legalized in isel-confusing ways,
8642 // leading to really terrible codegen. E.g.,
8643 // %result = v8i32 sext v8i8 %value
8644 // becomes
8645 // %losrc = extract_subreg %value, ...
8646 // %hisrc = extract_subreg %value, ...
8647 // %lo = v4i32 sext v4i8 %losrc
8648 // %hi = v4i32 sext v4i8 %hisrc
8649 // Things go rapidly downhill from there.
8650 //
8651 // For AArch64, the [sz]ext vector instructions can only go up one element
8652 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8653 // take two instructions.
8654 //
8655 // This implies that the most efficient way to do the extend from v8i8
8656 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8657 // the normal splitting to happen for the v8i16->v8i32.
8658
8659 // This is pre-legalization to catch some cases where the default
8660 // type legalization will create ill-tempered code.
8661 if (!DCI.isBeforeLegalizeOps())
8662 return SDValue();
8663
8664 // We're only interested in cleaning things up for non-legal vector types
8665 // here. If both the source and destination are legal, things will just
8666 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008667 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008668 EVT ResVT = N->getValueType(0);
8669 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8670 return SDValue();
8671 // If the vector type isn't a simple VT, it's beyond the scope of what
8672 // we're worried about here. Let legalization do its thing and hope for
8673 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008674 SDValue Src = N->getOperand(0);
8675 EVT SrcVT = Src->getValueType(0);
8676 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008677 return SDValue();
8678
Tim Northover3b0846e2014-05-24 12:50:23 +00008679 // If the source VT is a 64-bit vector, we can play games and get the
8680 // better results we want.
8681 if (SrcVT.getSizeInBits() != 64)
8682 return SDValue();
8683
8684 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8685 unsigned ElementCount = SrcVT.getVectorNumElements();
8686 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8687 SDLoc DL(N);
8688 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8689
8690 // Now split the rest of the operation into two halves, each with a 64
8691 // bit source.
8692 EVT LoVT, HiVT;
8693 SDValue Lo, Hi;
8694 unsigned NumElements = ResVT.getVectorNumElements();
8695 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8696 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8697 ResVT.getVectorElementType(), NumElements / 2);
8698
8699 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8700 LoVT.getVectorNumElements());
8701 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008702 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008703 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008704 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008705 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8706 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8707
8708 // Now combine the parts back together so we still have a single result
8709 // like the combiner expects.
8710 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8711}
8712
8713/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8714/// value. The load store optimizer pass will merge them to store pair stores.
8715/// This has better performance than a splat of the scalar followed by a split
8716/// vector store. Even if the stores are not merged it is four stores vs a dup,
8717/// followed by an ext.b and two stores.
8718static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8719 SDValue StVal = St->getValue();
8720 EVT VT = StVal.getValueType();
8721
8722 // Don't replace floating point stores, they possibly won't be transformed to
8723 // stp because of the store pair suppress pass.
8724 if (VT.isFloatingPoint())
8725 return SDValue();
8726
8727 // Check for insert vector elements.
8728 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8729 return SDValue();
8730
8731 // We can express a splat as store pair(s) for 2 or 4 elements.
8732 unsigned NumVecElts = VT.getVectorNumElements();
8733 if (NumVecElts != 4 && NumVecElts != 2)
8734 return SDValue();
8735 SDValue SplatVal = StVal.getOperand(1);
8736 unsigned RemainInsertElts = NumVecElts - 1;
8737
8738 // Check that this is a splat.
8739 while (--RemainInsertElts) {
8740 SDValue NextInsertElt = StVal.getOperand(0);
8741 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8742 return SDValue();
8743 if (NextInsertElt.getOperand(1) != SplatVal)
8744 return SDValue();
8745 StVal = NextInsertElt;
8746 }
8747 unsigned OrigAlignment = St->getAlignment();
8748 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8749 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8750
8751 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008752 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008753 // Most of the time the three stores should be replaced by store pair
8754 // instructions (stp).
8755 SDLoc DL(St);
8756 SDValue BasePtr = St->getBasePtr();
8757 SDValue NewST1 =
8758 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00008759 St->getAlignment(), St->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008760
8761 unsigned Offset = EltOffset;
8762 while (--NumVecElts) {
8763 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008764 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008765 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00008766 St->getPointerInfo(), Alignment,
8767 St->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008768 Offset += EltOffset;
8769 }
8770 return NewST1;
8771}
8772
Tim Northover339c83e2015-11-10 00:44:23 +00008773static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8774 SelectionDAG &DAG,
8775 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008776 if (!DCI.isBeforeLegalize())
8777 return SDValue();
8778
8779 StoreSDNode *S = cast<StoreSDNode>(N);
8780 if (S->isVolatile())
8781 return SDValue();
8782
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008783 // FIXME: The logic for deciding if an unaligned store should be split should
8784 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8785 // a call to that function here.
8786
Matthias Braun651cff42016-06-02 18:03:53 +00008787 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00008788 return SDValue();
8789
Sanjay Patel924879a2015-08-04 15:49:57 +00008790 // Don't split at -Oz.
8791 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008792 return SDValue();
8793
8794 SDValue StVal = S->getValue();
8795 EVT VT = StVal.getValueType();
8796
8797 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8798 // those up regresses performance on micro-benchmarks and olden/bh.
8799 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8800 return SDValue();
8801
8802 // Split unaligned 16B stores. They are terrible for performance.
8803 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8804 // extensions can use this to mark that it does not want splitting to happen
8805 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8806 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8807 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8808 S->getAlignment() <= 2)
8809 return SDValue();
8810
8811 // If we get a splat of a scalar convert this vector store to a store of
8812 // scalars. They will be merged into store pairs thereby removing two
8813 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008814 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008815 return ReplacedSplat;
8816
8817 SDLoc DL(S);
8818 unsigned NumElts = VT.getVectorNumElements() / 2;
8819 // Split VT into two.
8820 EVT HalfVT =
8821 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8822 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008823 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008824 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008825 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008826 SDValue BasePtr = S->getBasePtr();
8827 SDValue NewST1 =
8828 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00008829 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008830 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008831 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008832 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00008833 S->getPointerInfo(), S->getAlignment(),
8834 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008835}
8836
8837/// Target-specific DAG combine function for post-increment LD1 (lane) and
8838/// post-increment LD1R.
8839static SDValue performPostLD1Combine(SDNode *N,
8840 TargetLowering::DAGCombinerInfo &DCI,
8841 bool IsLaneOp) {
8842 if (DCI.isBeforeLegalizeOps())
8843 return SDValue();
8844
8845 SelectionDAG &DAG = DCI.DAG;
8846 EVT VT = N->getValueType(0);
8847
8848 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8849 SDNode *LD = N->getOperand(LoadIdx).getNode();
8850 // If it is not LOAD, can not do such combine.
8851 if (LD->getOpcode() != ISD::LOAD)
8852 return SDValue();
8853
8854 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8855 EVT MemVT = LoadSDN->getMemoryVT();
8856 // Check if memory operand is the same type as the vector element.
8857 if (MemVT != VT.getVectorElementType())
8858 return SDValue();
8859
8860 // Check if there are other uses. If so, do not combine as it will introduce
8861 // an extra load.
8862 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8863 ++UI) {
8864 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8865 continue;
8866 if (*UI != N)
8867 return SDValue();
8868 }
8869
8870 SDValue Addr = LD->getOperand(1);
8871 SDValue Vector = N->getOperand(0);
8872 // Search for a use of the address operand that is an increment.
8873 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8874 Addr.getNode()->use_end(); UI != UE; ++UI) {
8875 SDNode *User = *UI;
8876 if (User->getOpcode() != ISD::ADD
8877 || UI.getUse().getResNo() != Addr.getResNo())
8878 continue;
8879
8880 // Check that the add is independent of the load. Otherwise, folding it
8881 // would create a cycle.
8882 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8883 continue;
8884 // Also check that add is not used in the vector operand. This would also
8885 // create a cycle.
8886 if (User->isPredecessorOf(Vector.getNode()))
8887 continue;
8888
8889 // If the increment is a constant, it must match the memory ref size.
8890 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8891 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8892 uint32_t IncVal = CInc->getZExtValue();
8893 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8894 if (IncVal != NumBytes)
8895 continue;
8896 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8897 }
8898
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008899 // Finally, check that the vector doesn't depend on the load.
8900 // Again, this would create a cycle.
8901 // The load depending on the vector is fine, as that's the case for the
8902 // LD1*post we'll eventually generate anyway.
8903 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8904 continue;
8905
Tim Northover3b0846e2014-05-24 12:50:23 +00008906 SmallVector<SDValue, 8> Ops;
8907 Ops.push_back(LD->getOperand(0)); // Chain
8908 if (IsLaneOp) {
8909 Ops.push_back(Vector); // The vector to be inserted
8910 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8911 }
8912 Ops.push_back(Addr);
8913 Ops.push_back(Inc);
8914
8915 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008916 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008917 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8918 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8919 MemVT,
8920 LoadSDN->getMemOperand());
8921
8922 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00008923 SDValue NewResults[] = {
8924 SDValue(LD, 0), // The result of load
8925 SDValue(UpdN.getNode(), 2) // Chain
8926 };
Tim Northover3b0846e2014-05-24 12:50:23 +00008927 DCI.CombineTo(LD, NewResults);
8928 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8929 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8930
8931 break;
8932 }
8933 return SDValue();
8934}
8935
Tim Northover339c83e2015-11-10 00:44:23 +00008936/// Simplify \Addr given that the top byte of it is ignored by HW during
8937/// address translation.
8938static bool performTBISimplification(SDValue Addr,
8939 TargetLowering::DAGCombinerInfo &DCI,
8940 SelectionDAG &DAG) {
8941 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8942 APInt KnownZero, KnownOne;
8943 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8944 DCI.isBeforeLegalizeOps());
8945 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8946 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8947 DCI.CommitTargetLoweringOpt(TLO);
8948 return true;
8949 }
8950 return false;
8951}
8952
8953static SDValue performSTORECombine(SDNode *N,
8954 TargetLowering::DAGCombinerInfo &DCI,
8955 SelectionDAG &DAG,
8956 const AArch64Subtarget *Subtarget) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008957 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00008958 return Split;
8959
8960 if (Subtarget->supportsAddressTopByteIgnored() &&
8961 performTBISimplification(N->getOperand(2), DCI, DAG))
8962 return SDValue(N, 0);
8963
8964 return SDValue();
8965}
8966
8967 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008968/// LoopVectorizer for the across vector reduction. It consists of
8969/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8970/// are reduced, where s is an induction variable from 0 to
8971/// log2(NumVectorElements).
8972static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8973 unsigned Op,
8974 SelectionDAG &DAG) {
8975 EVT VTy = OpV->getOperand(0).getValueType();
8976 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008977 return SDValue();
8978
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008979 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008980 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8981 if (NumVecElts != 4)
8982 return SDValue();
8983 } else {
8984 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8985 return SDValue();
8986 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008987
8988 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008989 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008990 // Iterate over each step of the across vector reduction.
8991 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008992 SDValue CurOp = PreOp.getOperand(0);
8993 SDValue Shuffle = PreOp.getOperand(1);
8994 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008995 // Try to swap the 1st and 2nd operand as add and min/max instructions
8996 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008997 CurOp = PreOp.getOperand(1);
8998 Shuffle = PreOp.getOperand(0);
8999 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9000 return SDValue();
9001 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009002
9003 // Check if the input vector is fed by the operator we want to handle,
9004 // except the last step; the very first input vector is not necessarily
9005 // the same operator we are handling.
9006 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9007 return SDValue();
9008
Chad Rosier6c36eff2015-09-03 18:13:57 +00009009 // Check if it forms one step of the across vector reduction.
9010 // E.g.,
9011 // %cur = add %1, %0
9012 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9013 // %pre = add %cur, %shuffle
9014 if (Shuffle.getOperand(0) != CurOp)
9015 return SDValue();
9016
9017 int NumMaskElts = 1 << CurStep;
9018 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9019 // Check mask values in each step.
9020 // We expect the shuffle mask in each step follows a specific pattern
9021 // denoted here by the <M, U> form, where M is a sequence of integers
9022 // starting from NumMaskElts, increasing by 1, and the number integers
9023 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9024 // of undef in U should be NumVecElts - NumMaskElts.
9025 // E.g., for <8 x i16>, mask values in each step should be :
9026 // step 0 : <1,u,u,u,u,u,u,u>
9027 // step 1 : <2,3,u,u,u,u,u,u>
9028 // step 2 : <4,5,6,7,u,u,u,u>
9029 for (int i = 0; i < NumVecElts; ++i)
9030 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9031 (i >= NumMaskElts && !(Mask[i] < 0)))
9032 return SDValue();
9033
9034 PreOp = CurOp;
9035 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009036 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009037 bool IsIntrinsic = false;
9038
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009039 switch (Op) {
9040 default:
9041 llvm_unreachable("Unexpected operator for across vector reduction");
9042 case ISD::ADD:
9043 Opcode = AArch64ISD::UADDV;
9044 break;
9045 case ISD::SMAX:
9046 Opcode = AArch64ISD::SMAXV;
9047 break;
9048 case ISD::UMAX:
9049 Opcode = AArch64ISD::UMAXV;
9050 break;
9051 case ISD::SMIN:
9052 Opcode = AArch64ISD::SMINV;
9053 break;
9054 case ISD::UMIN:
9055 Opcode = AArch64ISD::UMINV;
9056 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009057 case ISD::FMAXNUM:
9058 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9059 IsIntrinsic = true;
9060 break;
9061 case ISD::FMINNUM:
9062 Opcode = Intrinsic::aarch64_neon_fminnmv;
9063 IsIntrinsic = true;
9064 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009065 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009066 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00009067
9068 return IsIntrinsic
9069 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9070 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9071 : DAG.getNode(
9072 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9073 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9074 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009075}
9076
9077/// Target-specific DAG combine for the across vector min/max reductions.
9078/// This function specifically handles the final clean-up step of the vector
9079/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9080/// pattern, which narrows down and finds the final min/max value from all
9081/// elements of the vector.
9082/// For example, for a <16 x i8> vector :
9083/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9084/// %smax0 = smax %arr, svn0
9085/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9086/// %smax1 = smax %smax0, %svn1
9087/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9088/// %smax2 = smax %smax1, svn2
9089/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9090/// %sc = setcc %smax2, %svn3, gt
9091/// %n0 = extract_vector_elt %sc, #0
9092/// %n1 = extract_vector_elt %smax2, #0
9093/// %n2 = extract_vector_elt $smax2, #1
9094/// %result = select %n0, %n1, n2
9095/// becomes :
9096/// %1 = smaxv %0
9097/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009098static SDValue
9099performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9100 const AArch64Subtarget *Subtarget) {
9101 if (!Subtarget->hasNEON())
9102 return SDValue();
9103
9104 SDValue N0 = N->getOperand(0);
9105 SDValue IfTrue = N->getOperand(1);
9106 SDValue IfFalse = N->getOperand(2);
9107
9108 // Check if the SELECT merges up the final result of the min/max
9109 // from a vector.
9110 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9111 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9112 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9113 return SDValue();
9114
9115 // Expect N0 is fed by SETCC.
9116 SDValue SetCC = N0.getOperand(0);
9117 EVT SetCCVT = SetCC.getValueType();
9118 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9119 SetCCVT.getVectorElementType() != MVT::i1)
9120 return SDValue();
9121
9122 SDValue VectorOp = SetCC.getOperand(0);
9123 unsigned Op = VectorOp->getOpcode();
9124 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009125 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9126 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009127 return SDValue();
9128
9129 EVT VTy = VectorOp.getValueType();
9130 if (!VTy.isVector())
9131 return SDValue();
9132
Jun Bum Lim0aace132015-10-09 14:11:25 +00009133 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009134 return SDValue();
9135
Jun Bum Lim0aace132015-10-09 14:11:25 +00009136 EVT EltTy = VTy.getVectorElementType();
9137 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9138 if (EltTy != MVT::f32)
9139 return SDValue();
9140 } else {
9141 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9142 return SDValue();
9143 }
9144
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009145 // Check if extracting from the same vector.
9146 // For example,
9147 // %sc = setcc %vector, %svn1, gt
9148 // %n0 = extract_vector_elt %sc, #0
9149 // %n1 = extract_vector_elt %vector, #0
9150 // %n2 = extract_vector_elt $vector, #1
9151 if (!(VectorOp == IfTrue->getOperand(0) &&
9152 VectorOp == IfFalse->getOperand(0)))
9153 return SDValue();
9154
9155 // Check if the condition code is matched with the operator type.
9156 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9157 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9158 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9159 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009160 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9161 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9162 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9163 CC != ISD::SETGE) ||
9164 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9165 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9166 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009167 return SDValue();
9168
9169 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009170 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009171 return SDValue();
9172
9173 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009174 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009175 return SDValue();
9176
9177 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009178 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009179 return SDValue();
9180
9181 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9182}
9183
9184/// Target-specific DAG combine for the across vector add reduction.
9185/// This function specifically handles the final clean-up step of the vector
9186/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9187/// pattern, which adds all elements of a vector together.
9188/// For example, for a <4 x i32> vector :
9189/// %1 = vector_shuffle %0, <2,3,u,u>
9190/// %2 = add %0, %1
9191/// %3 = vector_shuffle %2, <1,u,u,u>
9192/// %4 = add %2, %3
9193/// %result = extract_vector_elt %4, 0
9194/// becomes :
9195/// %0 = uaddv %0
9196/// %result = extract_vector_elt %0, 0
9197static SDValue
9198performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9199 const AArch64Subtarget *Subtarget) {
9200 if (!Subtarget->hasNEON())
9201 return SDValue();
9202 SDValue N0 = N->getOperand(0);
9203 SDValue N1 = N->getOperand(1);
9204
9205 // Check if the input vector is fed by the ADD.
9206 if (N0->getOpcode() != ISD::ADD)
9207 return SDValue();
9208
9209 // The vector extract idx must constant zero because we only expect the final
9210 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009211 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009212 return SDValue();
9213
9214 EVT VTy = N0.getValueType();
9215 if (!VTy.isVector())
9216 return SDValue();
9217
9218 EVT EltTy = VTy.getVectorElementType();
9219 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9220 return SDValue();
9221
Jun Bum Lim0aace132015-10-09 14:11:25 +00009222 if (VTy.getSizeInBits() < 64)
9223 return SDValue();
9224
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009225 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009226}
9227
Tim Northover3b0846e2014-05-24 12:50:23 +00009228/// Target-specific DAG combine function for NEON load/store intrinsics
9229/// to merge base address updates.
9230static SDValue performNEONPostLDSTCombine(SDNode *N,
9231 TargetLowering::DAGCombinerInfo &DCI,
9232 SelectionDAG &DAG) {
9233 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9234 return SDValue();
9235
9236 unsigned AddrOpIdx = N->getNumOperands() - 1;
9237 SDValue Addr = N->getOperand(AddrOpIdx);
9238
9239 // Search for a use of the address operand that is an increment.
9240 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9241 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9242 SDNode *User = *UI;
9243 if (User->getOpcode() != ISD::ADD ||
9244 UI.getUse().getResNo() != Addr.getResNo())
9245 continue;
9246
9247 // Check that the add is independent of the load/store. Otherwise, folding
9248 // it would create a cycle.
9249 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9250 continue;
9251
9252 // Find the new opcode for the updating load/store.
9253 bool IsStore = false;
9254 bool IsLaneOp = false;
9255 bool IsDupOp = false;
9256 unsigned NewOpc = 0;
9257 unsigned NumVecs = 0;
9258 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9259 switch (IntNo) {
9260 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9261 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9262 NumVecs = 2; break;
9263 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9264 NumVecs = 3; break;
9265 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9266 NumVecs = 4; break;
9267 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9268 NumVecs = 2; IsStore = true; break;
9269 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9270 NumVecs = 3; IsStore = true; break;
9271 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9272 NumVecs = 4; IsStore = true; break;
9273 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9274 NumVecs = 2; break;
9275 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9276 NumVecs = 3; break;
9277 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9278 NumVecs = 4; break;
9279 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9280 NumVecs = 2; IsStore = true; break;
9281 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9282 NumVecs = 3; IsStore = true; break;
9283 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9284 NumVecs = 4; IsStore = true; break;
9285 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9286 NumVecs = 2; IsDupOp = true; break;
9287 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9288 NumVecs = 3; IsDupOp = true; break;
9289 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9290 NumVecs = 4; IsDupOp = true; break;
9291 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9292 NumVecs = 2; IsLaneOp = true; break;
9293 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9294 NumVecs = 3; IsLaneOp = true; break;
9295 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9296 NumVecs = 4; IsLaneOp = true; break;
9297 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9298 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9299 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9300 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9301 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9302 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9303 }
9304
9305 EVT VecTy;
9306 if (IsStore)
9307 VecTy = N->getOperand(2).getValueType();
9308 else
9309 VecTy = N->getValueType(0);
9310
9311 // If the increment is a constant, it must match the memory ref size.
9312 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9313 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9314 uint32_t IncVal = CInc->getZExtValue();
9315 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9316 if (IsLaneOp || IsDupOp)
9317 NumBytes /= VecTy.getVectorNumElements();
9318 if (IncVal != NumBytes)
9319 continue;
9320 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9321 }
9322 SmallVector<SDValue, 8> Ops;
9323 Ops.push_back(N->getOperand(0)); // Incoming chain
9324 // Load lane and store have vector list as input.
9325 if (IsLaneOp || IsStore)
9326 for (unsigned i = 2; i < AddrOpIdx; ++i)
9327 Ops.push_back(N->getOperand(i));
9328 Ops.push_back(Addr); // Base register
9329 Ops.push_back(Inc);
9330
9331 // Return Types.
9332 EVT Tys[6];
9333 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9334 unsigned n;
9335 for (n = 0; n < NumResultVecs; ++n)
9336 Tys[n] = VecTy;
9337 Tys[n++] = MVT::i64; // Type of write back register
9338 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009339 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009340
9341 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9342 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9343 MemInt->getMemoryVT(),
9344 MemInt->getMemOperand());
9345
9346 // Update the uses.
9347 std::vector<SDValue> NewResults;
9348 for (unsigned i = 0; i < NumResultVecs; ++i) {
9349 NewResults.push_back(SDValue(UpdN.getNode(), i));
9350 }
9351 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9352 DCI.CombineTo(N, NewResults);
9353 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9354
9355 break;
9356 }
9357 return SDValue();
9358}
9359
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009360// Checks to see if the value is the prescribed width and returns information
9361// about its extension mode.
9362static
9363bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9364 ExtType = ISD::NON_EXTLOAD;
9365 switch(V.getNode()->getOpcode()) {
9366 default:
9367 return false;
9368 case ISD::LOAD: {
9369 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9370 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9371 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9372 ExtType = LoadNode->getExtensionType();
9373 return true;
9374 }
9375 return false;
9376 }
9377 case ISD::AssertSext: {
9378 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9379 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9380 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9381 ExtType = ISD::SEXTLOAD;
9382 return true;
9383 }
9384 return false;
9385 }
9386 case ISD::AssertZext: {
9387 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9388 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9389 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9390 ExtType = ISD::ZEXTLOAD;
9391 return true;
9392 }
9393 return false;
9394 }
9395 case ISD::Constant:
9396 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009397 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9398 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009399 }
9400 }
9401
9402 return true;
9403}
9404
9405// This function does a whole lot of voodoo to determine if the tests are
9406// equivalent without and with a mask. Essentially what happens is that given a
9407// DAG resembling:
9408//
9409// +-------------+ +-------------+ +-------------+ +-------------+
9410// | Input | | AddConstant | | CompConstant| | CC |
9411// +-------------+ +-------------+ +-------------+ +-------------+
9412// | | | |
9413// V V | +----------+
9414// +-------------+ +----+ | |
9415// | ADD | |0xff| | |
9416// +-------------+ +----+ | |
9417// | | | |
9418// V V | |
9419// +-------------+ | |
9420// | AND | | |
9421// +-------------+ | |
9422// | | |
9423// +-----+ | |
9424// | | |
9425// V V V
9426// +-------------+
9427// | CMP |
9428// +-------------+
9429//
9430// The AND node may be safely removed for some combinations of inputs. In
9431// particular we need to take into account the extension type of the Input,
9432// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9433// width of the input (this can work for any width inputs, the above graph is
9434// specific to 8 bits.
9435//
9436// The specific equations were worked out by generating output tables for each
9437// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9438// problem was simplified by working with 4 bit inputs, which means we only
9439// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9440// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9441// patterns present in both extensions (0,7). For every distinct set of
9442// AddConstant and CompConstants bit patterns we can consider the masked and
9443// unmasked versions to be equivalent if the result of this function is true for
9444// all 16 distinct bit patterns of for the current extension type of Input (w0).
9445//
9446// sub w8, w0, w1
9447// and w10, w8, #0x0f
9448// cmp w8, w2
9449// cset w9, AArch64CC
9450// cmp w10, w2
9451// cset w11, AArch64CC
9452// cmp w9, w11
9453// cset w0, eq
9454// ret
9455//
9456// Since the above function shows when the outputs are equivalent it defines
9457// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9458// would be expensive to run during compiles. The equations below were written
9459// in a test harness that confirmed they gave equivalent outputs to the above
9460// for all inputs function, so they can be used determine if the removal is
9461// legal instead.
9462//
9463// isEquivalentMaskless() is the code for testing if the AND can be removed
9464// factored out of the DAG recognition as the DAG can take several forms.
9465
David Majnemere61e4bf2016-06-21 05:10:24 +00009466static bool isEquivalentMaskless(unsigned CC, unsigned width,
9467 ISD::LoadExtType ExtType, int AddConstant,
9468 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009469 // By being careful about our equations and only writing the in term
9470 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9471 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009472 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009473
9474 // For the purposes of these comparisons sign extending the type is
9475 // equivalent to zero extending the add and displacing it by half the integer
9476 // width. Provided we are careful and make sure our equations are valid over
9477 // the whole range we can just adjust the input and avoid writing equations
9478 // for sign extended inputs.
9479 if (ExtType == ISD::SEXTLOAD)
9480 AddConstant -= (1 << (width-1));
9481
9482 switch(CC) {
9483 case AArch64CC::LE:
9484 case AArch64CC::GT: {
9485 if ((AddConstant == 0) ||
9486 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9487 (AddConstant >= 0 && CompConstant < 0) ||
9488 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9489 return true;
9490 } break;
9491 case AArch64CC::LT:
9492 case AArch64CC::GE: {
9493 if ((AddConstant == 0) ||
9494 (AddConstant >= 0 && CompConstant <= 0) ||
9495 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9496 return true;
9497 } break;
9498 case AArch64CC::HI:
9499 case AArch64CC::LS: {
9500 if ((AddConstant >= 0 && CompConstant < 0) ||
9501 (AddConstant <= 0 && CompConstant >= -1 &&
9502 CompConstant < AddConstant + MaxUInt))
9503 return true;
9504 } break;
9505 case AArch64CC::PL:
9506 case AArch64CC::MI: {
9507 if ((AddConstant == 0) ||
9508 (AddConstant > 0 && CompConstant <= 0) ||
9509 (AddConstant < 0 && CompConstant <= AddConstant))
9510 return true;
9511 } break;
9512 case AArch64CC::LO:
9513 case AArch64CC::HS: {
9514 if ((AddConstant >= 0 && CompConstant <= 0) ||
9515 (AddConstant <= 0 && CompConstant >= 0 &&
9516 CompConstant <= AddConstant + MaxUInt))
9517 return true;
9518 } break;
9519 case AArch64CC::EQ:
9520 case AArch64CC::NE: {
9521 if ((AddConstant > 0 && CompConstant < 0) ||
9522 (AddConstant < 0 && CompConstant >= 0 &&
9523 CompConstant < AddConstant + MaxUInt) ||
9524 (AddConstant >= 0 && CompConstant >= 0 &&
9525 CompConstant >= AddConstant) ||
9526 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9527
9528 return true;
9529 } break;
9530 case AArch64CC::VS:
9531 case AArch64CC::VC:
9532 case AArch64CC::AL:
9533 case AArch64CC::NV:
9534 return true;
9535 case AArch64CC::Invalid:
9536 break;
9537 }
9538
9539 return false;
9540}
9541
9542static
9543SDValue performCONDCombine(SDNode *N,
9544 TargetLowering::DAGCombinerInfo &DCI,
9545 SelectionDAG &DAG, unsigned CCIndex,
9546 unsigned CmpIndex) {
9547 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9548 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9549 unsigned CondOpcode = SubsNode->getOpcode();
9550
9551 if (CondOpcode != AArch64ISD::SUBS)
9552 return SDValue();
9553
9554 // There is a SUBS feeding this condition. Is it fed by a mask we can
9555 // use?
9556
9557 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9558 unsigned MaskBits = 0;
9559
9560 if (AndNode->getOpcode() != ISD::AND)
9561 return SDValue();
9562
9563 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9564 uint32_t CNV = CN->getZExtValue();
9565 if (CNV == 255)
9566 MaskBits = 8;
9567 else if (CNV == 65535)
9568 MaskBits = 16;
9569 }
9570
9571 if (!MaskBits)
9572 return SDValue();
9573
9574 SDValue AddValue = AndNode->getOperand(0);
9575
9576 if (AddValue.getOpcode() != ISD::ADD)
9577 return SDValue();
9578
9579 // The basic dag structure is correct, grab the inputs and validate them.
9580
9581 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9582 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9583 SDValue SubsInputValue = SubsNode->getOperand(1);
9584
9585 // The mask is present and the provenance of all the values is a smaller type,
9586 // lets see if the mask is superfluous.
9587
9588 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9589 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9590 return SDValue();
9591
9592 ISD::LoadExtType ExtType;
9593
9594 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9595 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9596 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9597 return SDValue();
9598
9599 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9600 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9601 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9602 return SDValue();
9603
9604 // The AND is not necessary, remove it.
9605
9606 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9607 SubsNode->getValueType(1));
9608 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9609
9610 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9611 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9612
9613 return SDValue(N, 0);
9614}
9615
Tim Northover3b0846e2014-05-24 12:50:23 +00009616// Optimize compare with zero and branch.
9617static SDValue performBRCONDCombine(SDNode *N,
9618 TargetLowering::DAGCombinerInfo &DCI,
9619 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009620 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009621 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009622 SDValue Chain = N->getOperand(0);
9623 SDValue Dest = N->getOperand(1);
9624 SDValue CCVal = N->getOperand(2);
9625 SDValue Cmp = N->getOperand(3);
9626
9627 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9628 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9629 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9630 return SDValue();
9631
9632 unsigned CmpOpc = Cmp.getOpcode();
9633 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9634 return SDValue();
9635
9636 // Only attempt folding if there is only one use of the flag and no use of the
9637 // value.
9638 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9639 return SDValue();
9640
9641 SDValue LHS = Cmp.getOperand(0);
9642 SDValue RHS = Cmp.getOperand(1);
9643
9644 assert(LHS.getValueType() == RHS.getValueType() &&
9645 "Expected the value type to be the same for both operands!");
9646 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9647 return SDValue();
9648
Artyom Skrobov314ee042015-11-25 19:41:11 +00009649 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009650 std::swap(LHS, RHS);
9651
Artyom Skrobov314ee042015-11-25 19:41:11 +00009652 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009653 return SDValue();
9654
9655 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9656 LHS.getOpcode() == ISD::SRL)
9657 return SDValue();
9658
9659 // Fold the compare into the branch instruction.
9660 SDValue BR;
9661 if (CC == AArch64CC::EQ)
9662 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9663 else
9664 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9665
9666 // Do not add new nodes to DAG combiner worklist.
9667 DCI.CombineTo(N, BR, false);
9668
9669 return SDValue();
9670}
9671
Geoff Berry9e934b02016-01-04 18:55:47 +00009672// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9673// as well as whether the test should be inverted. This code is required to
9674// catch these cases (as opposed to standard dag combines) because
9675// AArch64ISD::TBZ is matched during legalization.
9676static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9677 SelectionDAG &DAG) {
9678
9679 if (!Op->hasOneUse())
9680 return Op;
9681
9682 // We don't handle undef/constant-fold cases below, as they should have
9683 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9684 // etc.)
9685
9686 // (tbz (trunc x), b) -> (tbz x, b)
9687 // This case is just here to enable more of the below cases to be caught.
9688 if (Op->getOpcode() == ISD::TRUNCATE &&
9689 Bit < Op->getValueType(0).getSizeInBits()) {
9690 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9691 }
9692
9693 if (Op->getNumOperands() != 2)
9694 return Op;
9695
9696 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9697 if (!C)
9698 return Op;
9699
9700 switch (Op->getOpcode()) {
9701 default:
9702 return Op;
9703
9704 // (tbz (and x, m), b) -> (tbz x, b)
9705 case ISD::AND:
9706 if ((C->getZExtValue() >> Bit) & 1)
9707 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9708 return Op;
9709
9710 // (tbz (shl x, c), b) -> (tbz x, b-c)
9711 case ISD::SHL:
9712 if (C->getZExtValue() <= Bit &&
9713 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9714 Bit = Bit - C->getZExtValue();
9715 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9716 }
9717 return Op;
9718
9719 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9720 case ISD::SRA:
9721 Bit = Bit + C->getZExtValue();
9722 if (Bit >= Op->getValueType(0).getSizeInBits())
9723 Bit = Op->getValueType(0).getSizeInBits() - 1;
9724 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9725
9726 // (tbz (srl x, c), b) -> (tbz x, b+c)
9727 case ISD::SRL:
9728 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9729 Bit = Bit + C->getZExtValue();
9730 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9731 }
9732 return Op;
9733
9734 // (tbz (xor x, -1), b) -> (tbnz x, b)
9735 case ISD::XOR:
9736 if ((C->getZExtValue() >> Bit) & 1)
9737 Invert = !Invert;
9738 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9739 }
9740}
9741
9742// Optimize test single bit zero/non-zero and branch.
9743static SDValue performTBZCombine(SDNode *N,
9744 TargetLowering::DAGCombinerInfo &DCI,
9745 SelectionDAG &DAG) {
9746 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9747 bool Invert = false;
9748 SDValue TestSrc = N->getOperand(1);
9749 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9750
9751 if (TestSrc == NewTestSrc)
9752 return SDValue();
9753
9754 unsigned NewOpc = N->getOpcode();
9755 if (Invert) {
9756 if (NewOpc == AArch64ISD::TBZ)
9757 NewOpc = AArch64ISD::TBNZ;
9758 else {
9759 assert(NewOpc == AArch64ISD::TBNZ);
9760 NewOpc = AArch64ISD::TBZ;
9761 }
9762 }
9763
9764 SDLoc DL(N);
9765 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9766 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9767}
9768
Tim Northover3b0846e2014-05-24 12:50:23 +00009769// vselect (v1i1 setcc) ->
9770// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9771// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9772// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9773// such VSELECT.
9774static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9775 SDValue N0 = N->getOperand(0);
9776 EVT CCVT = N0.getValueType();
9777
9778 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9779 CCVT.getVectorElementType() != MVT::i1)
9780 return SDValue();
9781
9782 EVT ResVT = N->getValueType(0);
9783 EVT CmpVT = N0.getOperand(0).getValueType();
9784 // Only combine when the result type is of the same size as the compared
9785 // operands.
9786 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9787 return SDValue();
9788
9789 SDValue IfTrue = N->getOperand(1);
9790 SDValue IfFalse = N->getOperand(2);
9791 SDValue SetCC =
9792 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9793 N0.getOperand(0), N0.getOperand(1),
9794 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9795 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9796 IfTrue, IfFalse);
9797}
9798
9799/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9800/// the compare-mask instructions rather than going via NZCV, even if LHS and
9801/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9802/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009803static SDValue performSelectCombine(SDNode *N,
9804 TargetLowering::DAGCombinerInfo &DCI) {
9805 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009806 SDValue N0 = N->getOperand(0);
9807 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009808
Ahmed Bougachac004c602015-04-27 21:43:12 +00009809 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009810 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009811
Ahmed Bougachac004c602015-04-27 21:43:12 +00009812 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9813 // scalar SetCCResultType. We also don't expect vectors, because we assume
9814 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9815 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9816 "Scalar-SETCC feeding SELECT has unexpected result type!");
9817
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009818 // If NumMaskElts == 0, the comparison is larger than select result. The
9819 // largest real NEON comparison is 64-bits per lane, which means the result is
9820 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009821 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009822
9823 // Don't try to do this optimization when the setcc itself has i1 operands.
9824 // There are no legal vectors of i1, so this would be pointless.
9825 if (SrcVT == MVT::i1)
9826 return SDValue();
9827
Tim Northover3c0915e2014-08-29 15:34:58 +00009828 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009829 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009830 return SDValue();
9831
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009832 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009833 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9834
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009835 // Also bail out if the vector CCVT isn't the same size as ResVT.
9836 // This can happen if the SETCC operand size doesn't divide the ResVT size
9837 // (e.g., f64 vs v3f32).
9838 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9839 return SDValue();
9840
Ahmed Bougachac004c602015-04-27 21:43:12 +00009841 // Make sure we didn't create illegal types, if we're not supposed to.
9842 assert(DCI.isBeforeLegalize() ||
9843 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9844
Tim Northover3b0846e2014-05-24 12:50:23 +00009845 // First perform a vector comparison, where lane 0 is the one we're interested
9846 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009847 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009848 SDValue LHS =
9849 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9850 SDValue RHS =
9851 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9852 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9853
9854 // Now duplicate the comparison mask we want across all other lanes.
9855 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +00009856 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009857 Mask = DAG.getNode(ISD::BITCAST, DL,
9858 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009859
9860 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9861}
9862
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009863/// Get rid of unnecessary NVCASTs (that don't change the type).
9864static SDValue performNVCASTCombine(SDNode *N) {
9865 if (N->getValueType(0) == N->getOperand(0).getValueType())
9866 return N->getOperand(0);
9867
9868 return SDValue();
9869}
9870
Tim Northover3b0846e2014-05-24 12:50:23 +00009871SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9872 DAGCombinerInfo &DCI) const {
9873 SelectionDAG &DAG = DCI.DAG;
9874 switch (N->getOpcode()) {
9875 default:
9876 break;
9877 case ISD::ADD:
9878 case ISD::SUB:
9879 return performAddSubLongCombine(N, DCI, DAG);
9880 case ISD::XOR:
9881 return performXorCombine(N, DAG, DCI, Subtarget);
9882 case ISD::MUL:
9883 return performMulCombine(N, DAG, DCI, Subtarget);
9884 case ISD::SINT_TO_FP:
9885 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009886 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009887 case ISD::FP_TO_SINT:
9888 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009889 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009890 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +00009891 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009892 case ISD::OR:
9893 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009894 case ISD::SRL:
9895 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +00009896 case ISD::INTRINSIC_WO_CHAIN:
9897 return performIntrinsicCombine(N, DCI, Subtarget);
9898 case ISD::ANY_EXTEND:
9899 case ISD::ZERO_EXTEND:
9900 case ISD::SIGN_EXTEND:
9901 return performExtendCombine(N, DCI, DAG);
9902 case ISD::BITCAST:
9903 return performBitcastCombine(N, DCI, DAG);
9904 case ISD::CONCAT_VECTORS:
9905 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009906 case ISD::SELECT: {
9907 SDValue RV = performSelectCombine(N, DCI);
9908 if (!RV.getNode())
9909 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9910 return RV;
9911 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009912 case ISD::VSELECT:
9913 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009914 case ISD::LOAD:
9915 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9916 return SDValue(N, 0);
9917 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009918 case ISD::STORE:
9919 return performSTORECombine(N, DCI, DAG, Subtarget);
9920 case AArch64ISD::BRCOND:
9921 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009922 case AArch64ISD::TBNZ:
9923 case AArch64ISD::TBZ:
9924 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009925 case AArch64ISD::CSEL:
9926 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009927 case AArch64ISD::DUP:
9928 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009929 case AArch64ISD::NVCAST:
9930 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009931 case ISD::INSERT_VECTOR_ELT:
9932 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009933 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009934 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009935 case ISD::INTRINSIC_VOID:
9936 case ISD::INTRINSIC_W_CHAIN:
9937 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9938 case Intrinsic::aarch64_neon_ld2:
9939 case Intrinsic::aarch64_neon_ld3:
9940 case Intrinsic::aarch64_neon_ld4:
9941 case Intrinsic::aarch64_neon_ld1x2:
9942 case Intrinsic::aarch64_neon_ld1x3:
9943 case Intrinsic::aarch64_neon_ld1x4:
9944 case Intrinsic::aarch64_neon_ld2lane:
9945 case Intrinsic::aarch64_neon_ld3lane:
9946 case Intrinsic::aarch64_neon_ld4lane:
9947 case Intrinsic::aarch64_neon_ld2r:
9948 case Intrinsic::aarch64_neon_ld3r:
9949 case Intrinsic::aarch64_neon_ld4r:
9950 case Intrinsic::aarch64_neon_st2:
9951 case Intrinsic::aarch64_neon_st3:
9952 case Intrinsic::aarch64_neon_st4:
9953 case Intrinsic::aarch64_neon_st1x2:
9954 case Intrinsic::aarch64_neon_st1x3:
9955 case Intrinsic::aarch64_neon_st1x4:
9956 case Intrinsic::aarch64_neon_st2lane:
9957 case Intrinsic::aarch64_neon_st3lane:
9958 case Intrinsic::aarch64_neon_st4lane:
9959 return performNEONPostLDSTCombine(N, DCI, DAG);
9960 default:
9961 break;
9962 }
9963 }
9964 return SDValue();
9965}
9966
9967// Check if the return value is used as only a return value, as otherwise
9968// we can't perform a tail-call. In particular, we need to check for
9969// target ISD nodes that are returns and any other "odd" constructs
9970// that the generic analysis code won't necessarily catch.
9971bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9972 SDValue &Chain) const {
9973 if (N->getNumValues() != 1)
9974 return false;
9975 if (!N->hasNUsesOfValue(1, 0))
9976 return false;
9977
9978 SDValue TCChain = Chain;
9979 SDNode *Copy = *N->use_begin();
9980 if (Copy->getOpcode() == ISD::CopyToReg) {
9981 // If the copy has a glue operand, we conservatively assume it isn't safe to
9982 // perform a tail call.
9983 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9984 MVT::Glue)
9985 return false;
9986 TCChain = Copy->getOperand(0);
9987 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9988 return false;
9989
9990 bool HasRet = false;
9991 for (SDNode *Node : Copy->uses()) {
9992 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9993 return false;
9994 HasRet = true;
9995 }
9996
9997 if (!HasRet)
9998 return false;
9999
10000 Chain = TCChain;
10001 return true;
10002}
10003
10004// Return whether the an instruction can potentially be optimized to a tail
10005// call. This will cause the optimizers to attempt to move, or duplicate,
10006// return instructions to help enable tail call optimizations for this
10007// instruction.
10008bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010009 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010010}
10011
10012bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10013 SDValue &Offset,
10014 ISD::MemIndexedMode &AM,
10015 bool &IsInc,
10016 SelectionDAG &DAG) const {
10017 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10018 return false;
10019
10020 Base = Op->getOperand(0);
10021 // All of the indexed addressing mode instructions take a signed
10022 // 9 bit immediate offset.
10023 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10024 int64_t RHSC = (int64_t)RHS->getZExtValue();
10025 if (RHSC >= 256 || RHSC <= -256)
10026 return false;
10027 IsInc = (Op->getOpcode() == ISD::ADD);
10028 Offset = Op->getOperand(1);
10029 return true;
10030 }
10031 return false;
10032}
10033
10034bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10035 SDValue &Offset,
10036 ISD::MemIndexedMode &AM,
10037 SelectionDAG &DAG) const {
10038 EVT VT;
10039 SDValue Ptr;
10040 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10041 VT = LD->getMemoryVT();
10042 Ptr = LD->getBasePtr();
10043 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10044 VT = ST->getMemoryVT();
10045 Ptr = ST->getBasePtr();
10046 } else
10047 return false;
10048
10049 bool IsInc;
10050 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10051 return false;
10052 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10053 return true;
10054}
10055
10056bool AArch64TargetLowering::getPostIndexedAddressParts(
10057 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10058 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10059 EVT VT;
10060 SDValue Ptr;
10061 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10062 VT = LD->getMemoryVT();
10063 Ptr = LD->getBasePtr();
10064 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10065 VT = ST->getMemoryVT();
10066 Ptr = ST->getBasePtr();
10067 } else
10068 return false;
10069
10070 bool IsInc;
10071 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10072 return false;
10073 // Post-indexing updates the base, so it's not a valid transform
10074 // if that's not the same as the load's pointer.
10075 if (Ptr != Base)
10076 return false;
10077 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10078 return true;
10079}
10080
Tim Northoverf8bfe212014-07-18 13:07:05 +000010081static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10082 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010083 SDLoc DL(N);
10084 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010085
10086 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10087 return;
10088
Tim Northoverf8bfe212014-07-18 13:07:05 +000010089 Op = SDValue(
10090 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10091 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010092 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010093 0);
10094 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10095 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10096}
10097
Charlie Turner434d4592015-10-16 15:38:25 +000010098static void ReplaceReductionResults(SDNode *N,
10099 SmallVectorImpl<SDValue> &Results,
10100 SelectionDAG &DAG, unsigned InterOp,
10101 unsigned AcrossOp) {
10102 EVT LoVT, HiVT;
10103 SDValue Lo, Hi;
10104 SDLoc dl(N);
10105 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10106 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10107 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10108 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10109 Results.push_back(SplitVal);
10110}
10111
Tim Northover2f32e7f2016-08-04 19:32:28 +000010112static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10113 SDLoc DL(N);
10114 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10115 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10116 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10117 DAG.getConstant(64, DL, MVT::i64)));
10118 return std::make_pair(Lo, Hi);
10119}
10120
Tim Northovercdf15292016-04-14 17:03:29 +000010121static void ReplaceCMP_SWAP_128Results(SDNode *N,
10122 SmallVectorImpl<SDValue> & Results,
10123 SelectionDAG &DAG) {
10124 assert(N->getValueType(0) == MVT::i128 &&
10125 "AtomicCmpSwap on types less than 128 should be legal");
Tim Northover2f32e7f2016-08-04 19:32:28 +000010126 auto Desired = splitInt128(N->getOperand(2), DAG);
10127 auto New = splitInt128(N->getOperand(3), DAG);
10128 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10129 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000010130 SDNode *CmpSwap = DAG.getMachineNode(
10131 AArch64::CMP_SWAP_128, SDLoc(N),
10132 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10133
10134 MachineFunction &MF = DAG.getMachineFunction();
10135 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10136 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10137 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10138
10139 Results.push_back(SDValue(CmpSwap, 0));
10140 Results.push_back(SDValue(CmpSwap, 1));
10141 Results.push_back(SDValue(CmpSwap, 3));
10142}
10143
Tim Northover3b0846e2014-05-24 12:50:23 +000010144void AArch64TargetLowering::ReplaceNodeResults(
10145 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10146 switch (N->getOpcode()) {
10147 default:
10148 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010149 case ISD::BITCAST:
10150 ReplaceBITCASTResults(N, Results, DAG);
10151 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010152 case AArch64ISD::SADDV:
10153 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10154 return;
10155 case AArch64ISD::UADDV:
10156 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10157 return;
10158 case AArch64ISD::SMINV:
10159 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10160 return;
10161 case AArch64ISD::UMINV:
10162 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10163 return;
10164 case AArch64ISD::SMAXV:
10165 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10166 return;
10167 case AArch64ISD::UMAXV:
10168 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10169 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010170 case ISD::FP_TO_UINT:
10171 case ISD::FP_TO_SINT:
10172 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10173 // Let normal code take care of it by not adding anything to Results.
10174 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010175 case ISD::ATOMIC_CMP_SWAP:
10176 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10177 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010178 }
10179}
10180
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010181bool AArch64TargetLowering::useLoadStackGuardNode() const {
Tim Shene885d5e2016-04-19 19:40:37 +000010182 if (!Subtarget->isTargetAndroid())
10183 return true;
10184 return TargetLowering::useLoadStackGuardNode();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010185}
10186
Sanjay Patel1dd15592015-07-28 23:05:48 +000010187unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010188 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10189 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010190 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010191}
10192
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010193TargetLoweringBase::LegalizeTypeAction
10194AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10195 MVT SVT = VT.getSimpleVT();
10196 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10197 // v4i16, v2i32 instead of to promote.
10198 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10199 || SVT == MVT::v1f32)
10200 return TypeWidenVector;
10201
10202 return TargetLoweringBase::getPreferredVectorAction(VT);
10203}
10204
Robin Morisseted3d48f2014-09-03 21:29:59 +000010205// Loads and stores less than 128-bits are already atomic; ones above that
10206// are doomed anyway, so defer to the default libcall and blame the OS when
10207// things go wrong.
10208bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10209 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10210 return Size == 128;
10211}
10212
10213// Loads and stores less than 128-bits are already atomic; ones above that
10214// are doomed anyway, so defer to the default libcall and blame the OS when
10215// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010216TargetLowering::AtomicExpansionKind
10217AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010218 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010219 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010220}
10221
10222// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010223TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010224AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010225 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010226 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010227}
10228
Ahmed Bougacha52468672015-09-11 17:08:28 +000010229bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10230 AtomicCmpXchgInst *AI) const {
Tim Northovercdf15292016-04-14 17:03:29 +000010231 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10232 // implement cmpxchg without spilling. If the address being exchanged is also
10233 // on the stack and close enough to the spill slot, this can lead to a
10234 // situation where the monitor always gets cleared and the atomic operation
10235 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10236 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010237}
10238
Tim Northover3b0846e2014-05-24 12:50:23 +000010239Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10240 AtomicOrdering Ord) const {
10241 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10242 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010243 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010244
10245 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10246 // intrinsic must return {i64, i64} and we have to recombine them into a
10247 // single i128 here.
10248 if (ValTy->getPrimitiveSizeInBits() == 128) {
10249 Intrinsic::ID Int =
10250 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10251 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10252
10253 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10254 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10255
10256 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10257 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10258 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10259 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10260 return Builder.CreateOr(
10261 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10262 }
10263
10264 Type *Tys[] = { Addr->getType() };
10265 Intrinsic::ID Int =
10266 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10267 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10268
10269 return Builder.CreateTruncOrBitCast(
10270 Builder.CreateCall(Ldxr, Addr),
10271 cast<PointerType>(Addr->getType())->getElementType());
10272}
10273
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010274void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10275 IRBuilder<> &Builder) const {
10276 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10277 Builder.CreateCall(
10278 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10279}
10280
Tim Northover3b0846e2014-05-24 12:50:23 +000010281Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10282 Value *Val, Value *Addr,
10283 AtomicOrdering Ord) const {
10284 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010285 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010286
10287 // Since the intrinsics must have legal type, the i128 intrinsics take two
10288 // parameters: "i64, i64". We must marshal Val into the appropriate form
10289 // before the call.
10290 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10291 Intrinsic::ID Int =
10292 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10293 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10294 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10295
10296 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10297 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10298 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010299 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010300 }
10301
10302 Intrinsic::ID Int =
10303 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10304 Type *Tys[] = { Addr->getType() };
10305 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10306
David Blaikieff6409d2015-05-18 22:13:54 +000010307 return Builder.CreateCall(Stxr,
10308 {Builder.CreateZExtOrBitCast(
10309 Val, Stxr->getFunctionType()->getParamType(0)),
10310 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010311}
Tim Northover3c55cca2014-11-27 21:02:42 +000010312
10313bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10314 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10315 return Ty->isArrayTy();
10316}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010317
10318bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10319 EVT) const {
10320 return false;
10321}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010322
Tim Shen00127562016-04-08 21:26:31 +000010323Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010324 if (!Subtarget->isTargetAndroid())
Tim Shen00127562016-04-08 21:26:31 +000010325 return TargetLowering::getIRStackGuard(IRB);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010326
10327 // Android provides a fixed TLS slot for the stack cookie. See the definition
10328 // of TLS_SLOT_STACK_GUARD in
10329 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10330 const unsigned TlsOffset = 0x28;
10331 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10332 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010333 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010334 return IRB.CreatePointerCast(
10335 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10336 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10337}
10338
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010339Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10340 if (!Subtarget->isTargetAndroid())
10341 return TargetLowering::getSafeStackPointerLocation(IRB);
10342
10343 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10344 // definition of TLS_SLOT_SAFESTACK in
10345 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10346 const unsigned TlsOffset = 0x48;
10347 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10348 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010349 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010350 return IRB.CreatePointerCast(
10351 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10352 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10353}
Manman Rencbe4f942015-12-16 21:04:19 +000010354
10355void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10356 // Update IsSplitCSR in AArch64unctionInfo.
10357 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10358 AFI->setIsSplitCSR(true);
10359}
10360
10361void AArch64TargetLowering::insertCopiesSplitCSR(
10362 MachineBasicBlock *Entry,
10363 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10364 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10365 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10366 if (!IStart)
10367 return;
10368
10369 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10370 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010371 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010372 for (const MCPhysReg *I = IStart; *I; ++I) {
10373 const TargetRegisterClass *RC = nullptr;
10374 if (AArch64::GPR64RegClass.contains(*I))
10375 RC = &AArch64::GPR64RegClass;
10376 else if (AArch64::FPR64RegClass.contains(*I))
10377 RC = &AArch64::FPR64RegClass;
10378 else
10379 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10380
10381 unsigned NewVR = MRI->createVirtualRegister(RC);
10382 // Create copy from CSR to a virtual register.
10383 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10384 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10385 // nounwind. If we want to generalize this later, we may need to emit
10386 // CFI pseudo-instructions.
10387 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10388 Attribute::NoUnwind) &&
10389 "Function should be nounwind in insertCopiesSplitCSR!");
10390 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010391 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010392 .addReg(*I);
10393
Manman Ren4632e8e2016-01-15 20:13:28 +000010394 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010395 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010396 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10397 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010398 .addReg(NewVR);
10399 }
10400}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010401
10402bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10403 // Integer division on AArch64 is expensive. However, when aggressively
10404 // optimizing for code size, we prefer to use a div instruction, as it is
10405 // usually smaller than the alternative sequence.
10406 // The exception to this is vector division. Since AArch64 doesn't have vector
10407 // integer division, leaving the division as-is is a loss even in terms of
10408 // size, because it will have to be scalarized, while the alternative code
10409 // sequence can be performed in vector form.
10410 bool OptSize =
10411 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10412 return OptSize && !VT.isVector();
10413}