blob: 6d2a95129c3c1209f810711a15972caa390604c9 [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"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/Type.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/Target/TargetOptions.h"
35using namespace llvm;
36
37#define DEBUG_TYPE "aarch64-lower"
38
39STATISTIC(NumTailCalls, "Number of tail calls");
40STATISTIC(NumShiftInserts, "Number of vector shift inserts");
41
Alexey Samsonovf17f03e2014-08-19 18:40:39 +000042namespace {
Tim Northover3b0846e2014-05-24 12:50:23 +000043enum AlignMode {
44 StrictAlign,
45 NoStrictAlign
46};
Alexey Samsonovf17f03e2014-08-19 18:40:39 +000047}
Tim Northover3b0846e2014-05-24 12:50:23 +000048
49static cl::opt<AlignMode>
50Align(cl::desc("Load/store alignment support"),
51 cl::Hidden, cl::init(NoStrictAlign),
52 cl::values(
53 clEnumValN(StrictAlign, "aarch64-strict-align",
54 "Disallow all unaligned memory accesses"),
55 clEnumValN(NoStrictAlign, "aarch64-no-strict-align",
56 "Allow unaligned memory accesses"),
57 clEnumValEnd));
58
59// Place holder until extr generation is tested fully.
60static cl::opt<bool>
61EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
62 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
63 cl::init(true));
64
65static cl::opt<bool>
66EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000067 cl::desc("Allow AArch64 SLI/SRI formation"),
68 cl::init(false));
69
70// FIXME: The necessary dtprel relocations don't seem to be supported
71// well in the GNU bfd and gold linkers at the moment. Therefore, by
72// default, for now, fall back to GeneralDynamic code generation.
73cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
74 "aarch64-elf-ldtls-generation", cl::Hidden,
75 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
76 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000077
Eric Christopher905f12d2015-01-29 00:19:42 +000078AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
79 const AArch64Subtarget &STI)
80 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000081
82 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
83 // we have to make something up. Arbitrarily, choose ZeroOrOne.
84 setBooleanContents(ZeroOrOneBooleanContent);
85 // When comparing vectors the result sets the different elements in the
86 // vector to all-one or all-zero.
87 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89 // Set up the register classes.
90 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
91 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
92
93 if (Subtarget->hasFPARMv8()) {
94 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
95 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
96 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
97 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
98 }
99
100 if (Subtarget->hasNEON()) {
101 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
102 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
103 // Someone set us up the NEON.
104 addDRTypeForNEON(MVT::v2f32);
105 addDRTypeForNEON(MVT::v8i8);
106 addDRTypeForNEON(MVT::v4i16);
107 addDRTypeForNEON(MVT::v2i32);
108 addDRTypeForNEON(MVT::v1i64);
109 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000110 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000111
112 addQRTypeForNEON(MVT::v4f32);
113 addQRTypeForNEON(MVT::v2f64);
114 addQRTypeForNEON(MVT::v16i8);
115 addQRTypeForNEON(MVT::v8i16);
116 addQRTypeForNEON(MVT::v4i32);
117 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000118 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000119 }
120
121 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000122 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000123
124 // Provide all sorts of operation actions
125 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
126 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
127 setOperationAction(ISD::SETCC, MVT::i32, Custom);
128 setOperationAction(ISD::SETCC, MVT::i64, Custom);
129 setOperationAction(ISD::SETCC, MVT::f32, Custom);
130 setOperationAction(ISD::SETCC, MVT::f64, Custom);
131 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
132 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
133 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
134 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
135 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
136 setOperationAction(ISD::SELECT, MVT::i32, Custom);
137 setOperationAction(ISD::SELECT, MVT::i64, Custom);
138 setOperationAction(ISD::SELECT, MVT::f32, Custom);
139 setOperationAction(ISD::SELECT, MVT::f64, Custom);
140 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
141 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
142 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
143 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
144 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
145 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
146
147 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
148 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
149 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
150
151 setOperationAction(ISD::FREM, MVT::f32, Expand);
152 setOperationAction(ISD::FREM, MVT::f64, Expand);
153 setOperationAction(ISD::FREM, MVT::f80, Expand);
154
155 // Custom lowering hooks are needed for XOR
156 // to fold it into CSINC/CSINV.
157 setOperationAction(ISD::XOR, MVT::i32, Custom);
158 setOperationAction(ISD::XOR, MVT::i64, Custom);
159
160 // Virtually no operation on f128 is legal, but LLVM can't expand them when
161 // there's a valid register class, so we need custom operations in most cases.
162 setOperationAction(ISD::FABS, MVT::f128, Expand);
163 setOperationAction(ISD::FADD, MVT::f128, Custom);
164 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
165 setOperationAction(ISD::FCOS, MVT::f128, Expand);
166 setOperationAction(ISD::FDIV, MVT::f128, Custom);
167 setOperationAction(ISD::FMA, MVT::f128, Expand);
168 setOperationAction(ISD::FMUL, MVT::f128, Custom);
169 setOperationAction(ISD::FNEG, MVT::f128, Expand);
170 setOperationAction(ISD::FPOW, MVT::f128, Expand);
171 setOperationAction(ISD::FREM, MVT::f128, Expand);
172 setOperationAction(ISD::FRINT, MVT::f128, Expand);
173 setOperationAction(ISD::FSIN, MVT::f128, Expand);
174 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
175 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
176 setOperationAction(ISD::FSUB, MVT::f128, Custom);
177 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
178 setOperationAction(ISD::SETCC, MVT::f128, Custom);
179 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
180 setOperationAction(ISD::SELECT, MVT::f128, Custom);
181 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
182 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
183
184 // Lowering for many of the conversions is actually specified by the non-f128
185 // type. The LowerXXX function will be trivial when f128 isn't involved.
186 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
187 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
188 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
189 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
190 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
191 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
192 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
193 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
194 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
195 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
196 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
197 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
198 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
199 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
200
201 // Variable arguments.
202 setOperationAction(ISD::VASTART, MVT::Other, Custom);
203 setOperationAction(ISD::VAARG, MVT::Other, Custom);
204 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
205 setOperationAction(ISD::VAEND, MVT::Other, Expand);
206
207 // Variable-sized objects.
208 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
209 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
210 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
211
212 // Exception handling.
213 // FIXME: These are guesses. Has this been defined yet?
214 setExceptionPointerRegister(AArch64::X0);
215 setExceptionSelectorRegister(AArch64::X1);
216
217 // Constant pool entries
218 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
219
220 // BlockAddress
221 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
222
223 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
224 setOperationAction(ISD::ADDC, MVT::i32, Custom);
225 setOperationAction(ISD::ADDE, MVT::i32, Custom);
226 setOperationAction(ISD::SUBC, MVT::i32, Custom);
227 setOperationAction(ISD::SUBE, MVT::i32, Custom);
228 setOperationAction(ISD::ADDC, MVT::i64, Custom);
229 setOperationAction(ISD::ADDE, MVT::i64, Custom);
230 setOperationAction(ISD::SUBC, MVT::i64, Custom);
231 setOperationAction(ISD::SUBE, MVT::i64, Custom);
232
233 // AArch64 lacks both left-rotate and popcount instructions.
234 setOperationAction(ISD::ROTL, MVT::i32, Expand);
235 setOperationAction(ISD::ROTL, MVT::i64, Expand);
236
237 // AArch64 doesn't have {U|S}MUL_LOHI.
238 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
239 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
240
241
242 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
243 // counterparts, which AArch64 supports directly.
244 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
245 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
246 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
247 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
248
249 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
250 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
251
252 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
253 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
254 setOperationAction(ISD::SREM, MVT::i32, Expand);
255 setOperationAction(ISD::SREM, MVT::i64, Expand);
256 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
257 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
258 setOperationAction(ISD::UREM, MVT::i32, Expand);
259 setOperationAction(ISD::UREM, MVT::i64, Expand);
260
261 // Custom lower Add/Sub/Mul with overflow.
262 setOperationAction(ISD::SADDO, MVT::i32, Custom);
263 setOperationAction(ISD::SADDO, MVT::i64, Custom);
264 setOperationAction(ISD::UADDO, MVT::i32, Custom);
265 setOperationAction(ISD::UADDO, MVT::i64, Custom);
266 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
267 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
268 setOperationAction(ISD::USUBO, MVT::i32, Custom);
269 setOperationAction(ISD::USUBO, MVT::i64, Custom);
270 setOperationAction(ISD::SMULO, MVT::i32, Custom);
271 setOperationAction(ISD::SMULO, MVT::i64, Custom);
272 setOperationAction(ISD::UMULO, MVT::i32, Custom);
273 setOperationAction(ISD::UMULO, MVT::i64, Custom);
274
275 setOperationAction(ISD::FSIN, MVT::f32, Expand);
276 setOperationAction(ISD::FSIN, MVT::f64, Expand);
277 setOperationAction(ISD::FCOS, MVT::f32, Expand);
278 setOperationAction(ISD::FCOS, MVT::f64, Expand);
279 setOperationAction(ISD::FPOW, MVT::f32, Expand);
280 setOperationAction(ISD::FPOW, MVT::f64, Expand);
281 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
282 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
283
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000284 // f16 is a storage-only type, always promote it to f32.
285 setOperationAction(ISD::SETCC, MVT::f16, Promote);
286 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
287 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
288 setOperationAction(ISD::SELECT, MVT::f16, Promote);
289 setOperationAction(ISD::FADD, MVT::f16, Promote);
290 setOperationAction(ISD::FSUB, MVT::f16, Promote);
291 setOperationAction(ISD::FMUL, MVT::f16, Promote);
292 setOperationAction(ISD::FDIV, MVT::f16, Promote);
293 setOperationAction(ISD::FREM, MVT::f16, Promote);
294 setOperationAction(ISD::FMA, MVT::f16, Promote);
295 setOperationAction(ISD::FNEG, MVT::f16, Promote);
296 setOperationAction(ISD::FABS, MVT::f16, Promote);
297 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
298 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
299 setOperationAction(ISD::FCOS, MVT::f16, Promote);
300 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
301 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
302 setOperationAction(ISD::FPOW, MVT::f16, Promote);
303 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
304 setOperationAction(ISD::FRINT, MVT::f16, Promote);
305 setOperationAction(ISD::FSIN, MVT::f16, Promote);
306 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
307 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
308 setOperationAction(ISD::FEXP, MVT::f16, Promote);
309 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
310 setOperationAction(ISD::FLOG, MVT::f16, Promote);
311 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
312 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
313 setOperationAction(ISD::FROUND, MVT::f16, Promote);
314 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
315 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
316 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000317
Oliver Stannard89d15422014-08-27 16:16:04 +0000318 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
319 // known to be safe.
320 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
321 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
322 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
323 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
324 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
325 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
326 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
327 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
328 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
329 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
330 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
331 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
332
333 // Expand all other v4f16 operations.
334 // FIXME: We could generate better code by promoting some operations to
335 // a pair of v4f32s
336 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
337 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
338 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
339 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
340 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
341 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
342 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
343 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
344 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
345 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
346 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
347 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
348 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
349 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
350 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
351 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
352 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
353 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
354 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
355 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
356 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
357 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
358 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
359 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
360 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
361 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
362
363
364 // v8f16 is also a storage-only type, so expand it.
365 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
366 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
367 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
368 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
369 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
370 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
371 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
372 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
373 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
374 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
375 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
376 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
377 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
378 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
379 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
380 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
381 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
382 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
383 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
384 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
385 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
386 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
387 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
388 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
389 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
390 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
391 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
392 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
393 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
394 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
395 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
396
Tim Northover3b0846e2014-05-24 12:50:23 +0000397 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000398 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000399 setOperationAction(ISD::FFLOOR, Ty, Legal);
400 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
401 setOperationAction(ISD::FCEIL, Ty, Legal);
402 setOperationAction(ISD::FRINT, Ty, Legal);
403 setOperationAction(ISD::FTRUNC, Ty, Legal);
404 setOperationAction(ISD::FROUND, Ty, Legal);
405 }
406
407 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
408
409 if (Subtarget->isTargetMachO()) {
410 // For iOS, we don't want to the normal expansion of a libcall to
411 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
412 // traffic.
413 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
414 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
415 } else {
416 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
417 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
418 }
419
Juergen Ributzka23266502014-12-10 19:43:32 +0000420 // Make floating-point constants legal for the large code model, so they don't
421 // become loads from the constant pool.
422 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
423 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
424 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
425 }
426
Tim Northover3b0846e2014-05-24 12:50:23 +0000427 // AArch64 does not have floating-point extending loads, i1 sign-extending
428 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000429 for (MVT VT : MVT::fp_valuetypes()) {
430 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
431 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
432 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
433 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
434 }
435 for (MVT VT : MVT::integer_valuetypes())
436 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
437
Tim Northover3b0846e2014-05-24 12:50:23 +0000438 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
439 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
441 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
442 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
443 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
444 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000445
446 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
447 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
448
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 // Indexed loads and stores are supported.
450 for (unsigned im = (unsigned)ISD::PRE_INC;
451 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
452 setIndexedLoadAction(im, MVT::i8, Legal);
453 setIndexedLoadAction(im, MVT::i16, Legal);
454 setIndexedLoadAction(im, MVT::i32, Legal);
455 setIndexedLoadAction(im, MVT::i64, Legal);
456 setIndexedLoadAction(im, MVT::f64, Legal);
457 setIndexedLoadAction(im, MVT::f32, Legal);
458 setIndexedStoreAction(im, MVT::i8, Legal);
459 setIndexedStoreAction(im, MVT::i16, Legal);
460 setIndexedStoreAction(im, MVT::i32, Legal);
461 setIndexedStoreAction(im, MVT::i64, Legal);
462 setIndexedStoreAction(im, MVT::f64, Legal);
463 setIndexedStoreAction(im, MVT::f32, Legal);
464 }
465
466 // Trap.
467 setOperationAction(ISD::TRAP, MVT::Other, Legal);
468
469 // We combine OR nodes for bitfield operations.
470 setTargetDAGCombine(ISD::OR);
471
472 // Vector add and sub nodes may conceal a high-half opportunity.
473 // Also, try to fold ADD into CSINC/CSINV..
474 setTargetDAGCombine(ISD::ADD);
475 setTargetDAGCombine(ISD::SUB);
476
477 setTargetDAGCombine(ISD::XOR);
478 setTargetDAGCombine(ISD::SINT_TO_FP);
479 setTargetDAGCombine(ISD::UINT_TO_FP);
480
481 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
482
483 setTargetDAGCombine(ISD::ANY_EXTEND);
484 setTargetDAGCombine(ISD::ZERO_EXTEND);
485 setTargetDAGCombine(ISD::SIGN_EXTEND);
486 setTargetDAGCombine(ISD::BITCAST);
487 setTargetDAGCombine(ISD::CONCAT_VECTORS);
488 setTargetDAGCombine(ISD::STORE);
489
490 setTargetDAGCombine(ISD::MUL);
491
492 setTargetDAGCombine(ISD::SELECT);
493 setTargetDAGCombine(ISD::VSELECT);
494
495 setTargetDAGCombine(ISD::INTRINSIC_VOID);
496 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
497 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
498
499 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
500 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
501 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
502
503 setStackPointerRegisterToSaveRestore(AArch64::SP);
504
505 setSchedulingPreference(Sched::Hybrid);
506
507 // Enable TBZ/TBNZ
508 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000509 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000510
511 setMinFunctionAlignment(2);
512
513 RequireStrictAlign = (Align == StrictAlign);
514
515 setHasExtractBitsInsn(true);
516
517 if (Subtarget->hasNEON()) {
518 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
519 // silliness like this:
520 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
521 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
522 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
523 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
524 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
525 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
526 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
527 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
528 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
529 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
530 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
531 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
532 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
533 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
534 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
535 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
536 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
537 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
538 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
539 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
540 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
541 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
542 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
543 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
544 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
545
546 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
547 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
548 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
549 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
550 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
551
552 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
553
554 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
555 // elements smaller than i32, so promote the input to i32 first.
556 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
557 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
558 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
559 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000560 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
561 // -> v8f16 conversions.
562 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
564 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
565 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000566 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
567 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
569 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
570 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000571 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
572 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
573 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
574 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000575
576 // AArch64 doesn't have MUL.2d:
577 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000578 // Custom handling for some quad-vector types to detect MULL.
579 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
580 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
581 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
582
Tim Northover3b0846e2014-05-24 12:50:23 +0000583 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
584 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
585 // Likewise, narrowing and extending vector loads/stores aren't handled
586 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000587 for (MVT VT : MVT::vector_valuetypes()) {
588 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000589
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000590 setOperationAction(ISD::MULHS, VT, Expand);
591 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
592 setOperationAction(ISD::MULHU, VT, Expand);
593 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000594
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000595 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000596
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000597 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000598 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000599 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
600 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
601 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
602 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000603 }
604
605 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000606 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000607 setOperationAction(ISD::FFLOOR, Ty, Legal);
608 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
609 setOperationAction(ISD::FCEIL, Ty, Legal);
610 setOperationAction(ISD::FRINT, Ty, Legal);
611 setOperationAction(ISD::FTRUNC, Ty, Legal);
612 setOperationAction(ISD::FROUND, Ty, Legal);
613 }
614 }
James Molloyf089ab72014-08-06 10:42:18 +0000615
616 // Prefer likely predicted branches to selects on out-of-order cores.
617 if (Subtarget->isCortexA57())
618 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000619}
620
621void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000622 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000623 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
624 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
625
626 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
627 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000628 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000629 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
630 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
631
632 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
633 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
634 }
635
636 // Mark vector float intrinsics as expand.
637 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
638 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
639 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
640 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
641 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
642 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
643 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
644 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
645 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
646 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
647 }
648
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
650 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
651 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
652 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
653 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
654 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
655 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
656 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
657 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
658 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
659 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
660 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
661
662 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
663 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
664 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000665 for (MVT InnerVT : MVT::all_valuetypes())
666 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000667
668 // CNT supports only B element sizes.
669 if (VT != MVT::v8i8 && VT != MVT::v16i8)
670 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
671
672 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
673 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
674 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
675 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
676 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
677
678 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
679 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
680
681 if (Subtarget->isLittleEndian()) {
682 for (unsigned im = (unsigned)ISD::PRE_INC;
683 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
684 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
685 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
686 }
687 }
688}
689
690void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
691 addRegisterClass(VT, &AArch64::FPR64RegClass);
692 addTypeForNEON(VT, MVT::v2i32);
693}
694
695void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
696 addRegisterClass(VT, &AArch64::FPR128RegClass);
697 addTypeForNEON(VT, MVT::v4i32);
698}
699
700EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
701 if (!VT.isVector())
702 return MVT::i32;
703 return VT.changeVectorElementTypeToInteger();
704}
705
706/// computeKnownBitsForTargetNode - Determine which of the bits specified in
707/// Mask are known to be either zero or one and return them in the
708/// KnownZero/KnownOne bitsets.
709void AArch64TargetLowering::computeKnownBitsForTargetNode(
710 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
711 const SelectionDAG &DAG, unsigned Depth) const {
712 switch (Op.getOpcode()) {
713 default:
714 break;
715 case AArch64ISD::CSEL: {
716 APInt KnownZero2, KnownOne2;
717 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
718 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
719 KnownZero &= KnownZero2;
720 KnownOne &= KnownOne2;
721 break;
722 }
723 case ISD::INTRINSIC_W_CHAIN: {
724 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
725 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
726 switch (IntID) {
727 default: return;
728 case Intrinsic::aarch64_ldaxr:
729 case Intrinsic::aarch64_ldxr: {
730 unsigned BitWidth = KnownOne.getBitWidth();
731 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
732 unsigned MemBits = VT.getScalarType().getSizeInBits();
733 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
734 return;
735 }
736 }
737 break;
738 }
739 case ISD::INTRINSIC_WO_CHAIN:
740 case ISD::INTRINSIC_VOID: {
741 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
742 switch (IntNo) {
743 default:
744 break;
745 case Intrinsic::aarch64_neon_umaxv:
746 case Intrinsic::aarch64_neon_uminv: {
747 // Figure out the datatype of the vector operand. The UMINV instruction
748 // will zero extend the result, so we can mark as known zero all the
749 // bits larger than the element datatype. 32-bit or larget doesn't need
750 // this as those are legal types and will be handled by isel directly.
751 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
752 unsigned BitWidth = KnownZero.getBitWidth();
753 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
754 assert(BitWidth >= 8 && "Unexpected width!");
755 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
756 KnownZero |= Mask;
757 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
758 assert(BitWidth >= 16 && "Unexpected width!");
759 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
760 KnownZero |= Mask;
761 }
762 break;
763 } break;
764 }
765 }
766 }
767}
768
769MVT AArch64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
770 return MVT::i64;
771}
772
Tim Northover3b0846e2014-05-24 12:50:23 +0000773FastISel *
774AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
775 const TargetLibraryInfo *libInfo) const {
776 return AArch64::createFastISel(funcInfo, libInfo);
777}
778
779const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000780 switch ((AArch64ISD::NodeType)Opcode) {
781 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000782 case AArch64ISD::CALL: return "AArch64ISD::CALL";
783 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
784 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
785 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
786 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
787 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
788 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
789 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
790 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
791 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
792 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
793 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000794 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000795 case AArch64ISD::ADC: return "AArch64ISD::ADC";
796 case AArch64ISD::SBC: return "AArch64ISD::SBC";
797 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
798 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
799 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
800 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
801 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
802 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
803 case AArch64ISD::FMIN: return "AArch64ISD::FMIN";
804 case AArch64ISD::FMAX: return "AArch64ISD::FMAX";
805 case AArch64ISD::DUP: return "AArch64ISD::DUP";
806 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
807 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
808 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
809 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
810 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
811 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
812 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
813 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
814 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
815 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
816 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
817 case AArch64ISD::BICi: return "AArch64ISD::BICi";
818 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
819 case AArch64ISD::BSL: return "AArch64ISD::BSL";
820 case AArch64ISD::NEG: return "AArch64ISD::NEG";
821 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
822 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
823 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
824 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
825 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
826 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
827 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
828 case AArch64ISD::REV16: return "AArch64ISD::REV16";
829 case AArch64ISD::REV32: return "AArch64ISD::REV32";
830 case AArch64ISD::REV64: return "AArch64ISD::REV64";
831 case AArch64ISD::EXT: return "AArch64ISD::EXT";
832 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
833 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
834 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
835 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
836 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
837 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
838 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
839 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
840 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
841 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
842 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
843 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
844 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
845 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
846 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
847 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
848 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
849 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
850 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
851 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
852 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000853 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
854 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
855 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
856 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
857 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
858 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000859 case AArch64ISD::NOT: return "AArch64ISD::NOT";
860 case AArch64ISD::BIT: return "AArch64ISD::BIT";
861 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
862 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
863 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
864 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
865 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000866 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000867 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
868 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000869 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000870 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
871 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
872 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
873 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
874 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
875 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
876 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
877 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
878 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
879 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
880 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
881 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
882 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
883 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
884 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
885 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
886 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
887 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
888 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
889 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
890 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
891 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
892 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
893 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
894 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
895 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
896 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
897 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
898 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000899 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
900 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000901 }
Matthias Braund04893f2015-05-07 21:33:59 +0000902 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000903}
904
905MachineBasicBlock *
906AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
907 MachineBasicBlock *MBB) const {
908 // We materialise the F128CSEL pseudo-instruction as some control flow and a
909 // phi node:
910
911 // OrigBB:
912 // [... previous instrs leading to comparison ...]
913 // b.ne TrueBB
914 // b EndBB
915 // TrueBB:
916 // ; Fallthrough
917 // EndBB:
918 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
919
Tim Northover3b0846e2014-05-24 12:50:23 +0000920 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000921 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000922 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
923 DebugLoc DL = MI->getDebugLoc();
924 MachineFunction::iterator It = MBB;
925 ++It;
926
927 unsigned DestReg = MI->getOperand(0).getReg();
928 unsigned IfTrueReg = MI->getOperand(1).getReg();
929 unsigned IfFalseReg = MI->getOperand(2).getReg();
930 unsigned CondCode = MI->getOperand(3).getImm();
931 bool NZCVKilled = MI->getOperand(4).isKill();
932
933 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
934 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
935 MF->insert(It, TrueBB);
936 MF->insert(It, EndBB);
937
938 // Transfer rest of current basic-block to EndBB
939 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
940 MBB->end());
941 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
942
943 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
944 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
945 MBB->addSuccessor(TrueBB);
946 MBB->addSuccessor(EndBB);
947
948 // TrueBB falls through to the end.
949 TrueBB->addSuccessor(EndBB);
950
951 if (!NZCVKilled) {
952 TrueBB->addLiveIn(AArch64::NZCV);
953 EndBB->addLiveIn(AArch64::NZCV);
954 }
955
956 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
957 .addReg(IfTrueReg)
958 .addMBB(TrueBB)
959 .addReg(IfFalseReg)
960 .addMBB(MBB);
961
962 MI->eraseFromParent();
963 return EndBB;
964}
965
966MachineBasicBlock *
967AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
968 MachineBasicBlock *BB) const {
969 switch (MI->getOpcode()) {
970 default:
971#ifndef NDEBUG
972 MI->dump();
973#endif
Craig Topper35b2f752014-06-19 06:10:58 +0000974 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +0000975
976 case AArch64::F128CSEL:
977 return EmitF128CSEL(MI, BB);
978
979 case TargetOpcode::STACKMAP:
980 case TargetOpcode::PATCHPOINT:
981 return emitPatchPoint(MI, BB);
982 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000983}
984
985//===----------------------------------------------------------------------===//
986// AArch64 Lowering private implementation.
987//===----------------------------------------------------------------------===//
988
989//===----------------------------------------------------------------------===//
990// Lowering Code
991//===----------------------------------------------------------------------===//
992
993/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
994/// CC
995static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
996 switch (CC) {
997 default:
998 llvm_unreachable("Unknown condition code!");
999 case ISD::SETNE:
1000 return AArch64CC::NE;
1001 case ISD::SETEQ:
1002 return AArch64CC::EQ;
1003 case ISD::SETGT:
1004 return AArch64CC::GT;
1005 case ISD::SETGE:
1006 return AArch64CC::GE;
1007 case ISD::SETLT:
1008 return AArch64CC::LT;
1009 case ISD::SETLE:
1010 return AArch64CC::LE;
1011 case ISD::SETUGT:
1012 return AArch64CC::HI;
1013 case ISD::SETUGE:
1014 return AArch64CC::HS;
1015 case ISD::SETULT:
1016 return AArch64CC::LO;
1017 case ISD::SETULE:
1018 return AArch64CC::LS;
1019 }
1020}
1021
1022/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1023static void changeFPCCToAArch64CC(ISD::CondCode CC,
1024 AArch64CC::CondCode &CondCode,
1025 AArch64CC::CondCode &CondCode2) {
1026 CondCode2 = AArch64CC::AL;
1027 switch (CC) {
1028 default:
1029 llvm_unreachable("Unknown FP condition!");
1030 case ISD::SETEQ:
1031 case ISD::SETOEQ:
1032 CondCode = AArch64CC::EQ;
1033 break;
1034 case ISD::SETGT:
1035 case ISD::SETOGT:
1036 CondCode = AArch64CC::GT;
1037 break;
1038 case ISD::SETGE:
1039 case ISD::SETOGE:
1040 CondCode = AArch64CC::GE;
1041 break;
1042 case ISD::SETOLT:
1043 CondCode = AArch64CC::MI;
1044 break;
1045 case ISD::SETOLE:
1046 CondCode = AArch64CC::LS;
1047 break;
1048 case ISD::SETONE:
1049 CondCode = AArch64CC::MI;
1050 CondCode2 = AArch64CC::GT;
1051 break;
1052 case ISD::SETO:
1053 CondCode = AArch64CC::VC;
1054 break;
1055 case ISD::SETUO:
1056 CondCode = AArch64CC::VS;
1057 break;
1058 case ISD::SETUEQ:
1059 CondCode = AArch64CC::EQ;
1060 CondCode2 = AArch64CC::VS;
1061 break;
1062 case ISD::SETUGT:
1063 CondCode = AArch64CC::HI;
1064 break;
1065 case ISD::SETUGE:
1066 CondCode = AArch64CC::PL;
1067 break;
1068 case ISD::SETLT:
1069 case ISD::SETULT:
1070 CondCode = AArch64CC::LT;
1071 break;
1072 case ISD::SETLE:
1073 case ISD::SETULE:
1074 CondCode = AArch64CC::LE;
1075 break;
1076 case ISD::SETNE:
1077 case ISD::SETUNE:
1078 CondCode = AArch64CC::NE;
1079 break;
1080 }
1081}
1082
1083/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1084/// CC usable with the vector instructions. Fewer operations are available
1085/// without a real NZCV register, so we have to use less efficient combinations
1086/// to get the same effect.
1087static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1088 AArch64CC::CondCode &CondCode,
1089 AArch64CC::CondCode &CondCode2,
1090 bool &Invert) {
1091 Invert = false;
1092 switch (CC) {
1093 default:
1094 // Mostly the scalar mappings work fine.
1095 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1096 break;
1097 case ISD::SETUO:
1098 Invert = true; // Fallthrough
1099 case ISD::SETO:
1100 CondCode = AArch64CC::MI;
1101 CondCode2 = AArch64CC::GE;
1102 break;
1103 case ISD::SETUEQ:
1104 case ISD::SETULT:
1105 case ISD::SETULE:
1106 case ISD::SETUGT:
1107 case ISD::SETUGE:
1108 // All of the compare-mask comparisons are ordered, but we can switch
1109 // between the two by a double inversion. E.g. ULE == !OGT.
1110 Invert = true;
1111 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1112 break;
1113 }
1114}
1115
1116static bool isLegalArithImmed(uint64_t C) {
1117 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1118 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1119}
1120
1121static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1122 SDLoc dl, SelectionDAG &DAG) {
1123 EVT VT = LHS.getValueType();
1124
1125 if (VT.isFloatingPoint())
1126 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1127
1128 // The CMP instruction is just an alias for SUBS, and representing it as
1129 // SUBS means that it's possible to get CSE with subtract operations.
1130 // A later phase can perform the optimization of setting the destination
1131 // register to WZR/XZR if it ends up being unused.
1132 unsigned Opcode = AArch64ISD::SUBS;
1133
1134 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1135 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1136 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1137 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1138 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1139 // can be set differently by this operation. It comes down to whether
1140 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1141 // everything is fine. If not then the optimization is wrong. Thus general
1142 // comparisons are only valid if op2 != 0.
1143
1144 // So, finally, the only LLVM-native comparisons that don't mention C and V
1145 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1146 // the absence of information about op2.
1147 Opcode = AArch64ISD::ADDS;
1148 RHS = RHS.getOperand(1);
1149 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1150 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1151 !isUnsignedIntSetCC(CC)) {
1152 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1153 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1154 // of the signed comparisons.
1155 Opcode = AArch64ISD::ANDS;
1156 RHS = LHS.getOperand(1);
1157 LHS = LHS.getOperand(0);
1158 }
1159
1160 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1161 .getValue(1);
1162}
1163
1164static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1165 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
David Xuee978202014-08-28 04:59:53 +00001166 SDValue Cmp;
1167 AArch64CC::CondCode AArch64CC;
Tim Northover3b0846e2014-05-24 12:50:23 +00001168 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1169 EVT VT = RHS.getValueType();
1170 uint64_t C = RHSC->getZExtValue();
1171 if (!isLegalArithImmed(C)) {
1172 // Constant does not fit, try adjusting it by one?
1173 switch (CC) {
1174 default:
1175 break;
1176 case ISD::SETLT:
1177 case ISD::SETGE:
1178 if ((VT == MVT::i32 && C != 0x80000000 &&
1179 isLegalArithImmed((uint32_t)(C - 1))) ||
1180 (VT == MVT::i64 && C != 0x80000000ULL &&
1181 isLegalArithImmed(C - 1ULL))) {
1182 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1183 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001184 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001185 }
1186 break;
1187 case ISD::SETULT:
1188 case ISD::SETUGE:
1189 if ((VT == MVT::i32 && C != 0 &&
1190 isLegalArithImmed((uint32_t)(C - 1))) ||
1191 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1192 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1193 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001194 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001195 }
1196 break;
1197 case ISD::SETLE:
1198 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001199 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001200 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001201 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001202 isLegalArithImmed(C + 1ULL))) {
1203 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1204 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001205 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001206 }
1207 break;
1208 case ISD::SETULE:
1209 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001210 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001211 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001212 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001213 isLegalArithImmed(C + 1ULL))) {
1214 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1215 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001216 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001217 }
1218 break;
1219 }
1220 }
1221 }
David Xuee978202014-08-28 04:59:53 +00001222 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1223 // For the i8 operand, the largest immediate is 255, so this can be easily
1224 // encoded in the compare instruction. For the i16 operand, however, the
1225 // largest immediate cannot be encoded in the compare.
1226 // Therefore, use a sign extending load and cmn to avoid materializing the -1
1227 // constant. For example,
1228 // movz w1, #65535
1229 // ldrh w0, [x0, #0]
1230 // cmp w0, w1
1231 // >
1232 // ldrsh w0, [x0, #0]
1233 // cmn w0, #1
1234 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1235 // if and only if (sext LHS) == (sext RHS). The checks are in place to ensure
1236 // both the LHS and RHS are truely zero extended and to make sure the
1237 // transformation is profitable.
1238 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1239 if ((cast<ConstantSDNode>(RHS)->getZExtValue() >> 16 == 0) &&
1240 isa<LoadSDNode>(LHS)) {
1241 if (cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1242 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1243 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1244 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1245 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1246 SDValue SExt =
1247 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1248 DAG.getValueType(MVT::i16));
1249 Cmp = emitComparison(SExt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001250 DAG.getConstant(ValueofRHS, dl,
1251 RHS.getValueType()),
David Xuee978202014-08-28 04:59:53 +00001252 CC, dl, DAG);
1253 AArch64CC = changeIntCCToAArch64CC(CC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001254 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT::i32);
David Xuee978202014-08-28 04:59:53 +00001255 return Cmp;
1256 }
1257 }
1258 }
1259 }
1260 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1261 AArch64CC = changeIntCCToAArch64CC(CC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001262 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001263 return Cmp;
1264}
1265
1266static std::pair<SDValue, SDValue>
1267getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1268 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1269 "Unsupported value type");
1270 SDValue Value, Overflow;
1271 SDLoc DL(Op);
1272 SDValue LHS = Op.getOperand(0);
1273 SDValue RHS = Op.getOperand(1);
1274 unsigned Opc = 0;
1275 switch (Op.getOpcode()) {
1276 default:
1277 llvm_unreachable("Unknown overflow instruction!");
1278 case ISD::SADDO:
1279 Opc = AArch64ISD::ADDS;
1280 CC = AArch64CC::VS;
1281 break;
1282 case ISD::UADDO:
1283 Opc = AArch64ISD::ADDS;
1284 CC = AArch64CC::HS;
1285 break;
1286 case ISD::SSUBO:
1287 Opc = AArch64ISD::SUBS;
1288 CC = AArch64CC::VS;
1289 break;
1290 case ISD::USUBO:
1291 Opc = AArch64ISD::SUBS;
1292 CC = AArch64CC::LO;
1293 break;
1294 // Multiply needs a little bit extra work.
1295 case ISD::SMULO:
1296 case ISD::UMULO: {
1297 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001298 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001299 if (Op.getValueType() == MVT::i32) {
1300 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1301 // For a 32 bit multiply with overflow check we want the instruction
1302 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1303 // need to generate the following pattern:
1304 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1305 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1306 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1307 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1308 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001309 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001310 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1311 // operation. We need to clear out the upper 32 bits, because we used a
1312 // widening multiply that wrote all 64 bits. In the end this should be a
1313 // noop.
1314 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1315 if (IsSigned) {
1316 // The signed overflow check requires more than just a simple check for
1317 // any bit set in the upper 32 bits of the result. These bits could be
1318 // just the sign bits of a negative number. To perform the overflow
1319 // check we have to arithmetic shift right the 32nd bit of the result by
1320 // 31 bits. Then we compare the result to the upper 32 bits.
1321 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001322 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001323 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1324 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001325 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001326 // It is important that LowerBits is last, otherwise the arithmetic
1327 // shift will not be folded into the compare (SUBS).
1328 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1329 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1330 .getValue(1);
1331 } else {
1332 // The overflow check for unsigned multiply is easy. We only need to
1333 // check if any of the upper 32 bits are set. This can be done with a
1334 // CMP (shifted register). For that we need to generate the following
1335 // pattern:
1336 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1337 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001338 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001339 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1340 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001341 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1342 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001343 UpperBits).getValue(1);
1344 }
1345 break;
1346 }
1347 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1348 // For the 64 bit multiply
1349 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1350 if (IsSigned) {
1351 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1352 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001353 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001354 // It is important that LowerBits is last, otherwise the arithmetic
1355 // shift will not be folded into the compare (SUBS).
1356 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1357 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1358 .getValue(1);
1359 } else {
1360 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1361 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1362 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001363 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1364 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001365 UpperBits).getValue(1);
1366 }
1367 break;
1368 }
1369 } // switch (...)
1370
1371 if (Opc) {
1372 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1373
1374 // Emit the AArch64 operation with overflow check.
1375 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1376 Overflow = Value.getValue(1);
1377 }
1378 return std::make_pair(Value, Overflow);
1379}
1380
1381SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1382 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001383 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Tim Northover3b0846e2014-05-24 12:50:23 +00001384 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1385 SDLoc(Op)).first;
1386}
1387
1388static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1389 SDValue Sel = Op.getOperand(0);
1390 SDValue Other = Op.getOperand(1);
1391
1392 // If neither operand is a SELECT_CC, give up.
1393 if (Sel.getOpcode() != ISD::SELECT_CC)
1394 std::swap(Sel, Other);
1395 if (Sel.getOpcode() != ISD::SELECT_CC)
1396 return Op;
1397
1398 // The folding we want to perform is:
1399 // (xor x, (select_cc a, b, cc, 0, -1) )
1400 // -->
1401 // (csel x, (xor x, -1), cc ...)
1402 //
1403 // The latter will get matched to a CSINV instruction.
1404
1405 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1406 SDValue LHS = Sel.getOperand(0);
1407 SDValue RHS = Sel.getOperand(1);
1408 SDValue TVal = Sel.getOperand(2);
1409 SDValue FVal = Sel.getOperand(3);
1410 SDLoc dl(Sel);
1411
1412 // FIXME: This could be generalized to non-integer comparisons.
1413 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1414 return Op;
1415
1416 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1417 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1418
1419 // The the values aren't constants, this isn't the pattern we're looking for.
1420 if (!CFVal || !CTVal)
1421 return Op;
1422
1423 // We can commute the SELECT_CC by inverting the condition. This
1424 // might be needed to make this fit into a CSINV pattern.
1425 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1426 std::swap(TVal, FVal);
1427 std::swap(CTVal, CFVal);
1428 CC = ISD::getSetCCInverse(CC, true);
1429 }
1430
1431 // If the constants line up, perform the transform!
1432 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1433 SDValue CCVal;
1434 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1435
1436 FVal = Other;
1437 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001438 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001439
1440 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1441 CCVal, Cmp);
1442 }
1443
1444 return Op;
1445}
1446
1447static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1448 EVT VT = Op.getValueType();
1449
1450 // Let legalize expand this if it isn't a legal type yet.
1451 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1452 return SDValue();
1453
1454 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1455
1456 unsigned Opc;
1457 bool ExtraOp = false;
1458 switch (Op.getOpcode()) {
1459 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001460 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001461 case ISD::ADDC:
1462 Opc = AArch64ISD::ADDS;
1463 break;
1464 case ISD::SUBC:
1465 Opc = AArch64ISD::SUBS;
1466 break;
1467 case ISD::ADDE:
1468 Opc = AArch64ISD::ADCS;
1469 ExtraOp = true;
1470 break;
1471 case ISD::SUBE:
1472 Opc = AArch64ISD::SBCS;
1473 ExtraOp = true;
1474 break;
1475 }
1476
1477 if (!ExtraOp)
1478 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1479 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1480 Op.getOperand(2));
1481}
1482
1483static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1484 // Let legalize expand this if it isn't a legal type yet.
1485 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1486 return SDValue();
1487
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001488 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001489 AArch64CC::CondCode CC;
1490 // The actual operation that sets the overflow or carry flag.
1491 SDValue Value, Overflow;
1492 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1493
1494 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001495 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1496 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001497
1498 // We use an inverted condition, because the conditional select is inverted
1499 // too. This will allow it to be selected to a single instruction:
1500 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001501 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1502 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001503 CCVal, Overflow);
1504
1505 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001506 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001507}
1508
1509// Prefetch operands are:
1510// 1: Address to prefetch
1511// 2: bool isWrite
1512// 3: int locality (0 = no locality ... 3 = extreme locality)
1513// 4: bool isDataCache
1514static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1515 SDLoc DL(Op);
1516 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1517 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001518 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001519
1520 bool IsStream = !Locality;
1521 // When the locality number is set
1522 if (Locality) {
1523 // The front-end should have filtered out the out-of-range values
1524 assert(Locality <= 3 && "Prefetch locality out-of-range");
1525 // The locality degree is the opposite of the cache speed.
1526 // Put the number the other way around.
1527 // The encoding starts at 0 for level 1
1528 Locality = 3 - Locality;
1529 }
1530
1531 // built the mask value encoding the expected behavior.
1532 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001533 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001534 (Locality << 1) | // Cache level bits
1535 (unsigned)IsStream; // Stream bit
1536 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001537 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001538}
1539
1540SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1541 SelectionDAG &DAG) const {
1542 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1543
1544 RTLIB::Libcall LC;
1545 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1546
1547 return LowerF128Call(Op, DAG, LC);
1548}
1549
1550SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1551 SelectionDAG &DAG) const {
1552 if (Op.getOperand(0).getValueType() != MVT::f128) {
1553 // It's legal except when f128 is involved
1554 return Op;
1555 }
1556
1557 RTLIB::Libcall LC;
1558 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1559
1560 // FP_ROUND node has a second operand indicating whether it is known to be
1561 // precise. That doesn't take part in the LibCall so we can't directly use
1562 // LowerF128Call.
1563 SDValue SrcVal = Op.getOperand(0);
1564 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1565 /*isSigned*/ false, SDLoc(Op)).first;
1566}
1567
1568static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1569 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1570 // Any additional optimization in this function should be recorded
1571 // in the cost tables.
1572 EVT InVT = Op.getOperand(0).getValueType();
1573 EVT VT = Op.getValueType();
1574
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001575 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001576 SDLoc dl(Op);
1577 SDValue Cv =
1578 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1579 Op.getOperand(0));
1580 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001581 }
1582
1583 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001584 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001585 MVT ExtVT =
1586 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1587 VT.getVectorNumElements());
1588 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001589 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1590 }
1591
1592 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001593 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001594}
1595
1596SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1597 SelectionDAG &DAG) const {
1598 if (Op.getOperand(0).getValueType().isVector())
1599 return LowerVectorFP_TO_INT(Op, DAG);
1600
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001601 // f16 conversions are promoted to f32.
1602 if (Op.getOperand(0).getValueType() == MVT::f16) {
1603 SDLoc dl(Op);
1604 return DAG.getNode(
1605 Op.getOpcode(), dl, Op.getValueType(),
1606 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1607 }
1608
Tim Northover3b0846e2014-05-24 12:50:23 +00001609 if (Op.getOperand(0).getValueType() != MVT::f128) {
1610 // It's legal except when f128 is involved
1611 return Op;
1612 }
1613
1614 RTLIB::Libcall LC;
1615 if (Op.getOpcode() == ISD::FP_TO_SINT)
1616 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1617 else
1618 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1619
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001620 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Tim Northover3b0846e2014-05-24 12:50:23 +00001621 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1622 SDLoc(Op)).first;
1623}
1624
1625static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1626 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1627 // Any additional optimization in this function should be recorded
1628 // in the cost tables.
1629 EVT VT = Op.getValueType();
1630 SDLoc dl(Op);
1631 SDValue In = Op.getOperand(0);
1632 EVT InVT = In.getValueType();
1633
Tim Northoveref0d7602014-06-15 09:27:06 +00001634 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1635 MVT CastVT =
1636 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1637 InVT.getVectorNumElements());
1638 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001639 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001640 }
1641
Tim Northoveref0d7602014-06-15 09:27:06 +00001642 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1643 unsigned CastOpc =
1644 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1645 EVT CastVT = VT.changeVectorElementTypeToInteger();
1646 In = DAG.getNode(CastOpc, dl, CastVT, In);
1647 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00001648 }
1649
Tim Northoveref0d7602014-06-15 09:27:06 +00001650 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001651}
1652
1653SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1654 SelectionDAG &DAG) const {
1655 if (Op.getValueType().isVector())
1656 return LowerVectorINT_TO_FP(Op, DAG);
1657
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001658 // f16 conversions are promoted to f32.
1659 if (Op.getValueType() == MVT::f16) {
1660 SDLoc dl(Op);
1661 return DAG.getNode(
1662 ISD::FP_ROUND, dl, MVT::f16,
1663 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001664 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001665 }
1666
Tim Northover3b0846e2014-05-24 12:50:23 +00001667 // i128 conversions are libcalls.
1668 if (Op.getOperand(0).getValueType() == MVT::i128)
1669 return SDValue();
1670
1671 // Other conversions are legal, unless it's to the completely software-based
1672 // fp128.
1673 if (Op.getValueType() != MVT::f128)
1674 return Op;
1675
1676 RTLIB::Libcall LC;
1677 if (Op.getOpcode() == ISD::SINT_TO_FP)
1678 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1679 else
1680 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1681
1682 return LowerF128Call(Op, DAG, LC);
1683}
1684
1685SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1686 SelectionDAG &DAG) const {
1687 // For iOS, we want to call an alternative entry point: __sincos_stret,
1688 // which returns the values in two S / D registers.
1689 SDLoc dl(Op);
1690 SDValue Arg = Op.getOperand(0);
1691 EVT ArgVT = Arg.getValueType();
1692 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1693
1694 ArgListTy Args;
1695 ArgListEntry Entry;
1696
1697 Entry.Node = Arg;
1698 Entry.Ty = ArgTy;
1699 Entry.isSExt = false;
1700 Entry.isZExt = false;
1701 Args.push_back(Entry);
1702
1703 const char *LibcallName =
1704 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1705 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1706
Reid Kleckner343c3952014-11-20 23:51:47 +00001707 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00001708 TargetLowering::CallLoweringInfo CLI(DAG);
1709 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00001710 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00001711
1712 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1713 return CallResult.first;
1714}
1715
Tim Northoverf8bfe212014-07-18 13:07:05 +00001716static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1717 if (Op.getValueType() != MVT::f16)
1718 return SDValue();
1719
1720 assert(Op.getOperand(0).getValueType() == MVT::i16);
1721 SDLoc DL(Op);
1722
1723 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1724 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1725 return SDValue(
1726 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001727 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00001728 0);
1729}
1730
Chad Rosierd9d0f862014-10-08 02:31:24 +00001731static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1732 if (OrigVT.getSizeInBits() >= 64)
1733 return OrigVT;
1734
1735 assert(OrigVT.isSimple() && "Expecting a simple value type");
1736
1737 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1738 switch (OrigSimpleTy) {
1739 default: llvm_unreachable("Unexpected Vector Type");
1740 case MVT::v2i8:
1741 case MVT::v2i16:
1742 return MVT::v2i32;
1743 case MVT::v4i8:
1744 return MVT::v4i16;
1745 }
1746}
1747
1748static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
1749 const EVT &OrigTy,
1750 const EVT &ExtTy,
1751 unsigned ExtOpcode) {
1752 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
1753 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
1754 // 64-bits we need to insert a new extension so that it will be 64-bits.
1755 assert(ExtTy.is128BitVector() && "Unexpected extension size");
1756 if (OrigTy.getSizeInBits() >= 64)
1757 return N;
1758
1759 // Must extend size to at least 64 bits to be used as an operand for VMULL.
1760 EVT NewVT = getExtensionTo64Bits(OrigTy);
1761
1762 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
1763}
1764
1765static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
1766 bool isSigned) {
1767 EVT VT = N->getValueType(0);
1768
1769 if (N->getOpcode() != ISD::BUILD_VECTOR)
1770 return false;
1771
1772 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1773 SDNode *Elt = N->getOperand(i).getNode();
1774 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
1775 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1776 unsigned HalfSize = EltSize / 2;
1777 if (isSigned) {
1778 if (!isIntN(HalfSize, C->getSExtValue()))
1779 return false;
1780 } else {
1781 if (!isUIntN(HalfSize, C->getZExtValue()))
1782 return false;
1783 }
1784 continue;
1785 }
1786 return false;
1787 }
1788
1789 return true;
1790}
1791
1792static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
1793 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
1794 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
1795 N->getOperand(0)->getValueType(0),
1796 N->getValueType(0),
1797 N->getOpcode());
1798
1799 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
1800 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001801 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00001802 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
1803 unsigned NumElts = VT.getVectorNumElements();
1804 MVT TruncVT = MVT::getIntegerVT(EltSize);
1805 SmallVector<SDValue, 8> Ops;
1806 for (unsigned i = 0; i != NumElts; ++i) {
1807 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
1808 const APInt &CInt = C->getAPIntValue();
1809 // Element types smaller than 32 bits are not legal, so use i32 elements.
1810 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001811 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00001812 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001813 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00001814 MVT::getVectorVT(TruncVT, NumElts), Ops);
1815}
1816
1817static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
1818 if (N->getOpcode() == ISD::SIGN_EXTEND)
1819 return true;
1820 if (isExtendedBUILD_VECTOR(N, DAG, true))
1821 return true;
1822 return false;
1823}
1824
1825static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
1826 if (N->getOpcode() == ISD::ZERO_EXTEND)
1827 return true;
1828 if (isExtendedBUILD_VECTOR(N, DAG, false))
1829 return true;
1830 return false;
1831}
1832
1833static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
1834 unsigned Opcode = N->getOpcode();
1835 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1836 SDNode *N0 = N->getOperand(0).getNode();
1837 SDNode *N1 = N->getOperand(1).getNode();
1838 return N0->hasOneUse() && N1->hasOneUse() &&
1839 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
1840 }
1841 return false;
1842}
1843
1844static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
1845 unsigned Opcode = N->getOpcode();
1846 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1847 SDNode *N0 = N->getOperand(0).getNode();
1848 SDNode *N1 = N->getOperand(1).getNode();
1849 return N0->hasOneUse() && N1->hasOneUse() &&
1850 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
1851 }
1852 return false;
1853}
1854
1855static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
1856 // Multiplications are only custom-lowered for 128-bit vectors so that
1857 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
1858 EVT VT = Op.getValueType();
1859 assert(VT.is128BitVector() && VT.isInteger() &&
1860 "unexpected type for custom-lowering ISD::MUL");
1861 SDNode *N0 = Op.getOperand(0).getNode();
1862 SDNode *N1 = Op.getOperand(1).getNode();
1863 unsigned NewOpc = 0;
1864 bool isMLA = false;
1865 bool isN0SExt = isSignExtended(N0, DAG);
1866 bool isN1SExt = isSignExtended(N1, DAG);
1867 if (isN0SExt && isN1SExt)
1868 NewOpc = AArch64ISD::SMULL;
1869 else {
1870 bool isN0ZExt = isZeroExtended(N0, DAG);
1871 bool isN1ZExt = isZeroExtended(N1, DAG);
1872 if (isN0ZExt && isN1ZExt)
1873 NewOpc = AArch64ISD::UMULL;
1874 else if (isN1SExt || isN1ZExt) {
1875 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
1876 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
1877 if (isN1SExt && isAddSubSExt(N0, DAG)) {
1878 NewOpc = AArch64ISD::SMULL;
1879 isMLA = true;
1880 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
1881 NewOpc = AArch64ISD::UMULL;
1882 isMLA = true;
1883 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
1884 std::swap(N0, N1);
1885 NewOpc = AArch64ISD::UMULL;
1886 isMLA = true;
1887 }
1888 }
1889
1890 if (!NewOpc) {
1891 if (VT == MVT::v2i64)
1892 // Fall through to expand this. It is not legal.
1893 return SDValue();
1894 else
1895 // Other vector multiplications are legal.
1896 return Op;
1897 }
1898 }
1899
1900 // Legalize to a S/UMULL instruction
1901 SDLoc DL(Op);
1902 SDValue Op0;
1903 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
1904 if (!isMLA) {
1905 Op0 = skipExtensionForVectorMULL(N0, DAG);
1906 assert(Op0.getValueType().is64BitVector() &&
1907 Op1.getValueType().is64BitVector() &&
1908 "unexpected types for extended operands to VMULL");
1909 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
1910 }
1911 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
1912 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
1913 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
1914 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
1915 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
1916 EVT Op1VT = Op1.getValueType();
1917 return DAG.getNode(N0->getOpcode(), DL, VT,
1918 DAG.getNode(NewOpc, DL, VT,
1919 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
1920 DAG.getNode(NewOpc, DL, VT,
1921 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
1922}
Tim Northoverf8bfe212014-07-18 13:07:05 +00001923
Tim Northover3b0846e2014-05-24 12:50:23 +00001924SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
1925 SelectionDAG &DAG) const {
1926 switch (Op.getOpcode()) {
1927 default:
1928 llvm_unreachable("unimplemented operand");
1929 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00001930 case ISD::BITCAST:
1931 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00001932 case ISD::GlobalAddress:
1933 return LowerGlobalAddress(Op, DAG);
1934 case ISD::GlobalTLSAddress:
1935 return LowerGlobalTLSAddress(Op, DAG);
1936 case ISD::SETCC:
1937 return LowerSETCC(Op, DAG);
1938 case ISD::BR_CC:
1939 return LowerBR_CC(Op, DAG);
1940 case ISD::SELECT:
1941 return LowerSELECT(Op, DAG);
1942 case ISD::SELECT_CC:
1943 return LowerSELECT_CC(Op, DAG);
1944 case ISD::JumpTable:
1945 return LowerJumpTable(Op, DAG);
1946 case ISD::ConstantPool:
1947 return LowerConstantPool(Op, DAG);
1948 case ISD::BlockAddress:
1949 return LowerBlockAddress(Op, DAG);
1950 case ISD::VASTART:
1951 return LowerVASTART(Op, DAG);
1952 case ISD::VACOPY:
1953 return LowerVACOPY(Op, DAG);
1954 case ISD::VAARG:
1955 return LowerVAARG(Op, DAG);
1956 case ISD::ADDC:
1957 case ISD::ADDE:
1958 case ISD::SUBC:
1959 case ISD::SUBE:
1960 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1961 case ISD::SADDO:
1962 case ISD::UADDO:
1963 case ISD::SSUBO:
1964 case ISD::USUBO:
1965 case ISD::SMULO:
1966 case ISD::UMULO:
1967 return LowerXALUO(Op, DAG);
1968 case ISD::FADD:
1969 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1970 case ISD::FSUB:
1971 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1972 case ISD::FMUL:
1973 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1974 case ISD::FDIV:
1975 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1976 case ISD::FP_ROUND:
1977 return LowerFP_ROUND(Op, DAG);
1978 case ISD::FP_EXTEND:
1979 return LowerFP_EXTEND(Op, DAG);
1980 case ISD::FRAMEADDR:
1981 return LowerFRAMEADDR(Op, DAG);
1982 case ISD::RETURNADDR:
1983 return LowerRETURNADDR(Op, DAG);
1984 case ISD::INSERT_VECTOR_ELT:
1985 return LowerINSERT_VECTOR_ELT(Op, DAG);
1986 case ISD::EXTRACT_VECTOR_ELT:
1987 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1988 case ISD::BUILD_VECTOR:
1989 return LowerBUILD_VECTOR(Op, DAG);
1990 case ISD::VECTOR_SHUFFLE:
1991 return LowerVECTOR_SHUFFLE(Op, DAG);
1992 case ISD::EXTRACT_SUBVECTOR:
1993 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1994 case ISD::SRA:
1995 case ISD::SRL:
1996 case ISD::SHL:
1997 return LowerVectorSRA_SRL_SHL(Op, DAG);
1998 case ISD::SHL_PARTS:
1999 return LowerShiftLeftParts(Op, DAG);
2000 case ISD::SRL_PARTS:
2001 case ISD::SRA_PARTS:
2002 return LowerShiftRightParts(Op, DAG);
2003 case ISD::CTPOP:
2004 return LowerCTPOP(Op, DAG);
2005 case ISD::FCOPYSIGN:
2006 return LowerFCOPYSIGN(Op, DAG);
2007 case ISD::AND:
2008 return LowerVectorAND(Op, DAG);
2009 case ISD::OR:
2010 return LowerVectorOR(Op, DAG);
2011 case ISD::XOR:
2012 return LowerXOR(Op, DAG);
2013 case ISD::PREFETCH:
2014 return LowerPREFETCH(Op, DAG);
2015 case ISD::SINT_TO_FP:
2016 case ISD::UINT_TO_FP:
2017 return LowerINT_TO_FP(Op, DAG);
2018 case ISD::FP_TO_SINT:
2019 case ISD::FP_TO_UINT:
2020 return LowerFP_TO_INT(Op, DAG);
2021 case ISD::FSINCOS:
2022 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002023 case ISD::MUL:
2024 return LowerMUL(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002025 }
2026}
2027
2028/// getFunctionAlignment - Return the Log2 alignment of this function.
2029unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2030 return 2;
2031}
2032
2033//===----------------------------------------------------------------------===//
2034// Calling Convention Implementation
2035//===----------------------------------------------------------------------===//
2036
2037#include "AArch64GenCallingConv.inc"
2038
Robin Morisset039781e2014-08-29 21:53:01 +00002039/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002040CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2041 bool IsVarArg) const {
2042 switch (CC) {
2043 default:
2044 llvm_unreachable("Unsupported calling convention.");
2045 case CallingConv::WebKit_JS:
2046 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002047 case CallingConv::GHC:
2048 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002049 case CallingConv::C:
2050 case CallingConv::Fast:
2051 if (!Subtarget->isTargetDarwin())
2052 return CC_AArch64_AAPCS;
2053 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2054 }
2055}
2056
2057SDValue AArch64TargetLowering::LowerFormalArguments(
2058 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2059 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2060 SmallVectorImpl<SDValue> &InVals) const {
2061 MachineFunction &MF = DAG.getMachineFunction();
2062 MachineFrameInfo *MFI = MF.getFrameInfo();
2063
2064 // Assign locations to all of the incoming arguments.
2065 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002066 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2067 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002068
2069 // At this point, Ins[].VT may already be promoted to i32. To correctly
2070 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2071 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2072 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2073 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2074 // LocVT.
2075 unsigned NumArgs = Ins.size();
2076 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2077 unsigned CurArgIdx = 0;
2078 for (unsigned i = 0; i != NumArgs; ++i) {
2079 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002080 if (Ins[i].isOrigArg()) {
2081 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2082 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002083
Andrew Trick05938a52015-02-16 18:10:47 +00002084 // Get type of the original argument.
2085 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
2086 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2087 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2088 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2089 ValVT = MVT::i8;
2090 else if (ActualMVT == MVT::i16)
2091 ValVT = MVT::i16;
2092 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002093 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2094 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002095 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002096 assert(!Res && "Call operand has unhandled type");
2097 (void)Res;
2098 }
2099 assert(ArgLocs.size() == Ins.size());
2100 SmallVector<SDValue, 16> ArgValues;
2101 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2102 CCValAssign &VA = ArgLocs[i];
2103
2104 if (Ins[i].Flags.isByVal()) {
2105 // Byval is used for HFAs in the PCS, but the system should work in a
2106 // non-compliant manner for larger structs.
2107 EVT PtrTy = getPointerTy();
2108 int Size = Ins[i].Flags.getByValSize();
2109 unsigned NumRegs = (Size + 7) / 8;
2110
2111 // FIXME: This works on big-endian for composite byvals, which are the common
2112 // case. It should also work for fundamental types too.
2113 unsigned FrameIdx =
2114 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2115 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
2116 InVals.push_back(FrameIdxN);
2117
2118 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002119 }
2120
2121 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002122 // Arguments stored in registers.
2123 EVT RegVT = VA.getLocVT();
2124
2125 SDValue ArgValue;
2126 const TargetRegisterClass *RC;
2127
2128 if (RegVT == MVT::i32)
2129 RC = &AArch64::GPR32RegClass;
2130 else if (RegVT == MVT::i64)
2131 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002132 else if (RegVT == MVT::f16)
2133 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002134 else if (RegVT == MVT::f32)
2135 RC = &AArch64::FPR32RegClass;
2136 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2137 RC = &AArch64::FPR64RegClass;
2138 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2139 RC = &AArch64::FPR128RegClass;
2140 else
2141 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2142
2143 // Transform the arguments in physical registers into virtual ones.
2144 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2145 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2146
2147 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2148 // to 64 bits. Insert an assert[sz]ext to capture this, then
2149 // truncate to the right size.
2150 switch (VA.getLocInfo()) {
2151 default:
2152 llvm_unreachable("Unknown loc info!");
2153 case CCValAssign::Full:
2154 break;
2155 case CCValAssign::BCvt:
2156 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2157 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002158 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002159 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002160 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002161 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2162 // nodes after our lowering.
2163 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002164 break;
2165 }
2166
2167 InVals.push_back(ArgValue);
2168
2169 } else { // VA.isRegLoc()
2170 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2171 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002172 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002173
2174 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002175 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2176 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002177 BEAlign = 8 - ArgSize;
2178
2179 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2180
2181 // Create load nodes to retrieve arguments from the stack.
2182 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2183 SDValue ArgValue;
2184
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002185 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002186 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002187 MVT MemVT = VA.getValVT();
2188
Tim Northover47e003c2014-05-26 17:21:53 +00002189 switch (VA.getLocInfo()) {
2190 default:
2191 break;
Tim Northover6890add2014-06-03 13:54:53 +00002192 case CCValAssign::BCvt:
2193 MemVT = VA.getLocVT();
2194 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002195 case CCValAssign::SExt:
2196 ExtType = ISD::SEXTLOAD;
2197 break;
2198 case CCValAssign::ZExt:
2199 ExtType = ISD::ZEXTLOAD;
2200 break;
2201 case CCValAssign::AExt:
2202 ExtType = ISD::EXTLOAD;
2203 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002204 }
2205
Tim Northover6890add2014-06-03 13:54:53 +00002206 ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
Tim Northover47e003c2014-05-26 17:21:53 +00002207 MachinePointerInfo::getFixedStack(FI),
Benjamin Kramer2e52f022014-10-04 22:44:29 +00002208 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002209
Tim Northover3b0846e2014-05-24 12:50:23 +00002210 InVals.push_back(ArgValue);
2211 }
2212 }
2213
2214 // varargs
2215 if (isVarArg) {
2216 if (!Subtarget->isTargetDarwin()) {
2217 // The AAPCS variadic function ABI is identical to the non-variadic
2218 // one. As a result there may be more arguments in registers and we should
2219 // save them for future reference.
2220 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2221 }
2222
2223 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2224 // This will point to the next argument passed via stack.
2225 unsigned StackOffset = CCInfo.getNextStackOffset();
2226 // We currently pass all varargs at 8-byte alignment.
2227 StackOffset = ((StackOffset + 7) & ~7);
2228 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2229 }
2230
2231 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2232 unsigned StackArgSize = CCInfo.getNextStackOffset();
2233 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2234 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2235 // This is a non-standard ABI so by fiat I say we're allowed to make full
2236 // use of the stack area to be popped, which must be aligned to 16 bytes in
2237 // any case:
2238 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2239
2240 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2241 // a multiple of 16.
2242 FuncInfo->setArgumentStackToRestore(StackArgSize);
2243
2244 // This realignment carries over to the available bytes below. Our own
2245 // callers will guarantee the space is free by giving an aligned value to
2246 // CALLSEQ_START.
2247 }
2248 // Even if we're not expected to free up the space, it's useful to know how
2249 // much is there while considering tail calls (because we can reuse it).
2250 FuncInfo->setBytesInStackArgArea(StackArgSize);
2251
2252 return Chain;
2253}
2254
2255void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2256 SelectionDAG &DAG, SDLoc DL,
2257 SDValue &Chain) const {
2258 MachineFunction &MF = DAG.getMachineFunction();
2259 MachineFrameInfo *MFI = MF.getFrameInfo();
2260 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2261
2262 SmallVector<SDValue, 8> MemOps;
2263
2264 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2265 AArch64::X3, AArch64::X4, AArch64::X5,
2266 AArch64::X6, AArch64::X7 };
2267 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002268 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002269
2270 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2271 int GPRIdx = 0;
2272 if (GPRSaveSize != 0) {
2273 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2274
2275 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
2276
2277 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2278 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2279 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2280 SDValue Store =
2281 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2282 MachinePointerInfo::getStack(i * 8), false, false, 0);
2283 MemOps.push_back(Store);
2284 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002285 DAG.getConstant(8, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002286 }
2287 }
2288 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2289 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2290
2291 if (Subtarget->hasFPARMv8()) {
2292 static const MCPhysReg FPRArgRegs[] = {
2293 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2294 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2295 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002296 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002297
2298 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2299 int FPRIdx = 0;
2300 if (FPRSaveSize != 0) {
2301 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2302
2303 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
2304
2305 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2306 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2307 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2308
2309 SDValue Store =
2310 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2311 MachinePointerInfo::getStack(i * 16), false, false, 0);
2312 MemOps.push_back(Store);
2313 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002314 DAG.getConstant(16, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002315 }
2316 }
2317 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2318 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2319 }
2320
2321 if (!MemOps.empty()) {
2322 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2323 }
2324}
2325
2326/// LowerCallResult - Lower the result values of a call into the
2327/// appropriate copies out of appropriate physical registers.
2328SDValue AArch64TargetLowering::LowerCallResult(
2329 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2330 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2331 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2332 SDValue ThisVal) const {
2333 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2334 ? RetCC_AArch64_WebKit_JS
2335 : RetCC_AArch64_AAPCS;
2336 // Assign locations to each value returned by this call.
2337 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002338 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2339 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002340 CCInfo.AnalyzeCallResult(Ins, RetCC);
2341
2342 // Copy all of the result registers out of their specified physreg.
2343 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2344 CCValAssign VA = RVLocs[i];
2345
2346 // Pass 'this' value directly from the argument to return value, to avoid
2347 // reg unit interference
2348 if (i == 0 && isThisReturn) {
2349 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2350 "unexpected return calling convention register assignment");
2351 InVals.push_back(ThisVal);
2352 continue;
2353 }
2354
2355 SDValue Val =
2356 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2357 Chain = Val.getValue(1);
2358 InFlag = Val.getValue(2);
2359
2360 switch (VA.getLocInfo()) {
2361 default:
2362 llvm_unreachable("Unknown loc info!");
2363 case CCValAssign::Full:
2364 break;
2365 case CCValAssign::BCvt:
2366 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2367 break;
2368 }
2369
2370 InVals.push_back(Val);
2371 }
2372
2373 return Chain;
2374}
2375
2376bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2377 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2378 bool isCalleeStructRet, bool isCallerStructRet,
2379 const SmallVectorImpl<ISD::OutputArg> &Outs,
2380 const SmallVectorImpl<SDValue> &OutVals,
2381 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2382 // For CallingConv::C this function knows whether the ABI needs
2383 // changing. That's not true for other conventions so they will have to opt in
2384 // manually.
2385 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2386 return false;
2387
2388 const MachineFunction &MF = DAG.getMachineFunction();
2389 const Function *CallerF = MF.getFunction();
2390 CallingConv::ID CallerCC = CallerF->getCallingConv();
2391 bool CCMatch = CallerCC == CalleeCC;
2392
2393 // Byval parameters hand the function a pointer directly into the stack area
2394 // we want to reuse during a tail call. Working around this *is* possible (see
2395 // X86) but less efficient and uglier in LowerCall.
2396 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2397 e = CallerF->arg_end();
2398 i != e; ++i)
2399 if (i->hasByValAttr())
2400 return false;
2401
2402 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2403 if (IsTailCallConvention(CalleeCC) && CCMatch)
2404 return true;
2405 return false;
2406 }
2407
Oliver Stannard12993dd2014-08-18 12:42:15 +00002408 // Externally-defined functions with weak linkage should not be
2409 // tail-called on AArch64 when the OS does not support dynamic
2410 // pre-emption of symbols, as the AAELF spec requires normal calls
2411 // to undefined weak functions to be replaced with a NOP or jump to the
2412 // next instruction. The behaviour of branch instructions in this
2413 // situation (as used for tail calls) is implementation-defined, so we
2414 // cannot rely on the linker replacing the tail call with a return.
2415 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2416 const GlobalValue *GV = G->getGlobal();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002417 const Triple TT(getTargetMachine().getTargetTriple());
2418 if (GV->hasExternalWeakLinkage() &&
2419 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002420 return false;
2421 }
2422
Tim Northover3b0846e2014-05-24 12:50:23 +00002423 // Now we search for cases where we can use a tail call without changing the
2424 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2425 // concept.
2426
2427 // I want anyone implementing a new calling convention to think long and hard
2428 // about this assert.
2429 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2430 "Unexpected variadic calling convention");
2431
2432 if (isVarArg && !Outs.empty()) {
2433 // At least two cases here: if caller is fastcc then we can't have any
2434 // memory arguments (we'd be expected to clean up the stack afterwards). If
2435 // caller is C then we could potentially use its argument area.
2436
2437 // FIXME: for now we take the most conservative of these in both cases:
2438 // disallow all variadic memory operands.
2439 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002440 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2441 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002442
2443 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2444 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2445 if (!ArgLocs[i].isRegLoc())
2446 return false;
2447 }
2448
2449 // If the calling conventions do not match, then we'd better make sure the
2450 // results are returned in the same way as what the caller expects.
2451 if (!CCMatch) {
2452 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002453 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2454 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002455 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2456
2457 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002458 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2459 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002460 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2461
2462 if (RVLocs1.size() != RVLocs2.size())
2463 return false;
2464 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2465 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2466 return false;
2467 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2468 return false;
2469 if (RVLocs1[i].isRegLoc()) {
2470 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2471 return false;
2472 } else {
2473 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2474 return false;
2475 }
2476 }
2477 }
2478
2479 // Nothing more to check if the callee is taking no arguments
2480 if (Outs.empty())
2481 return true;
2482
2483 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002484 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2485 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002486
2487 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2488
2489 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2490
2491 // If the stack arguments for this call would fit into our own save area then
2492 // the call can be made tail.
2493 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2494}
2495
2496SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2497 SelectionDAG &DAG,
2498 MachineFrameInfo *MFI,
2499 int ClobberedFI) const {
2500 SmallVector<SDValue, 8> ArgChains;
2501 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2502 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2503
2504 // Include the original chain at the beginning of the list. When this is
2505 // used by target LowerCall hooks, this helps legalize find the
2506 // CALLSEQ_BEGIN node.
2507 ArgChains.push_back(Chain);
2508
2509 // Add a chain value for each stack argument corresponding
2510 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2511 UE = DAG.getEntryNode().getNode()->use_end();
2512 U != UE; ++U)
2513 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2514 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2515 if (FI->getIndex() < 0) {
2516 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2517 int64_t InLastByte = InFirstByte;
2518 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2519
2520 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2521 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2522 ArgChains.push_back(SDValue(L, 1));
2523 }
2524
2525 // Build a tokenfactor for all the chains.
2526 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2527}
2528
2529bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2530 bool TailCallOpt) const {
2531 return CallCC == CallingConv::Fast && TailCallOpt;
2532}
2533
2534bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2535 return CallCC == CallingConv::Fast;
2536}
2537
2538/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2539/// and add input and output parameter nodes.
2540SDValue
2541AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2542 SmallVectorImpl<SDValue> &InVals) const {
2543 SelectionDAG &DAG = CLI.DAG;
2544 SDLoc &DL = CLI.DL;
2545 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2546 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2547 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2548 SDValue Chain = CLI.Chain;
2549 SDValue Callee = CLI.Callee;
2550 bool &IsTailCall = CLI.IsTailCall;
2551 CallingConv::ID CallConv = CLI.CallConv;
2552 bool IsVarArg = CLI.IsVarArg;
2553
2554 MachineFunction &MF = DAG.getMachineFunction();
2555 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2556 bool IsThisReturn = false;
2557
2558 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2559 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2560 bool IsSibCall = false;
2561
2562 if (IsTailCall) {
2563 // Check if it's really possible to do a tail call.
2564 IsTailCall = isEligibleForTailCallOptimization(
2565 Callee, CallConv, IsVarArg, IsStructRet,
2566 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2567 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2568 report_fatal_error("failed to perform tail call elimination on a call "
2569 "site marked musttail");
2570
2571 // A sibling call is one where we're under the usual C ABI and not planning
2572 // to change that but can still do a tail call:
2573 if (!TailCallOpt && IsTailCall)
2574 IsSibCall = true;
2575
2576 if (IsTailCall)
2577 ++NumTailCalls;
2578 }
2579
2580 // Analyze operands of the call, assigning locations to each operand.
2581 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002582 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2583 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002584
2585 if (IsVarArg) {
2586 // Handle fixed and variable vector arguments differently.
2587 // Variable vector arguments always go into memory.
2588 unsigned NumArgs = Outs.size();
2589
2590 for (unsigned i = 0; i != NumArgs; ++i) {
2591 MVT ArgVT = Outs[i].VT;
2592 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2593 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2594 /*IsVarArg=*/ !Outs[i].IsFixed);
2595 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2596 assert(!Res && "Call operand has unhandled type");
2597 (void)Res;
2598 }
2599 } else {
2600 // At this point, Outs[].VT may already be promoted to i32. To correctly
2601 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2602 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2603 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2604 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2605 // LocVT.
2606 unsigned NumArgs = Outs.size();
2607 for (unsigned i = 0; i != NumArgs; ++i) {
2608 MVT ValVT = Outs[i].VT;
2609 // Get type of the original argument.
2610 EVT ActualVT = getValueType(CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2611 /*AllowUnknown*/ true);
2612 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2613 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2614 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002615 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002616 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002617 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002618 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002619
2620 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002621 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002622 assert(!Res && "Call operand has unhandled type");
2623 (void)Res;
2624 }
2625 }
2626
2627 // Get a count of how many bytes are to be pushed on the stack.
2628 unsigned NumBytes = CCInfo.getNextStackOffset();
2629
2630 if (IsSibCall) {
2631 // Since we're not changing the ABI to make this a tail call, the memory
2632 // operands are already available in the caller's incoming argument space.
2633 NumBytes = 0;
2634 }
2635
2636 // FPDiff is the byte offset of the call's argument area from the callee's.
2637 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2638 // by this amount for a tail call. In a sibling call it must be 0 because the
2639 // caller will deallocate the entire stack and the callee still expects its
2640 // arguments to begin at SP+0. Completely unused for non-tail calls.
2641 int FPDiff = 0;
2642
2643 if (IsTailCall && !IsSibCall) {
2644 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2645
2646 // Since callee will pop argument stack as a tail call, we must keep the
2647 // popped size 16-byte aligned.
2648 NumBytes = RoundUpToAlignment(NumBytes, 16);
2649
2650 // FPDiff will be negative if this tail call requires more space than we
2651 // would automatically have in our incoming argument space. Positive if we
2652 // can actually shrink the stack.
2653 FPDiff = NumReusableBytes - NumBytes;
2654
2655 // The stack pointer must be 16-byte aligned at all times it's used for a
2656 // memory operation, which in practice means at *all* times and in
2657 // particular across call boundaries. Therefore our own arguments started at
2658 // a 16-byte aligned SP and the delta applied for the tail call should
2659 // satisfy the same constraint.
2660 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2661 }
2662
2663 // Adjust the stack pointer for the new arguments...
2664 // These operations are automatically eliminated by the prolog/epilog pass
2665 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002666 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2667 true),
2668 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002669
2670 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy());
2671
2672 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2673 SmallVector<SDValue, 8> MemOpChains;
2674
2675 // Walk the register/memloc assignments, inserting copies/loads.
2676 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2677 ++i, ++realArgIdx) {
2678 CCValAssign &VA = ArgLocs[i];
2679 SDValue Arg = OutVals[realArgIdx];
2680 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2681
2682 // Promote the value if needed.
2683 switch (VA.getLocInfo()) {
2684 default:
2685 llvm_unreachable("Unknown loc info!");
2686 case CCValAssign::Full:
2687 break;
2688 case CCValAssign::SExt:
2689 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2690 break;
2691 case CCValAssign::ZExt:
2692 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2693 break;
2694 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00002695 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2696 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2697 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2698 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2699 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002700 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2701 break;
2702 case CCValAssign::BCvt:
2703 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2704 break;
2705 case CCValAssign::FPExt:
2706 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2707 break;
2708 }
2709
2710 if (VA.isRegLoc()) {
2711 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2712 assert(VA.getLocVT() == MVT::i64 &&
2713 "unexpected calling convention register assignment");
2714 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2715 "unexpected use of 'returned'");
2716 IsThisReturn = true;
2717 }
2718 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2719 } else {
2720 assert(VA.isMemLoc());
2721
2722 SDValue DstAddr;
2723 MachinePointerInfo DstInfo;
2724
2725 // FIXME: This works on big-endian for composite byvals, which are the
2726 // common case. It should also work for fundamental types too.
2727 uint32_t BEAlign = 0;
2728 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00002729 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00002730 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00002731 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
2732 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002733 if (OpSize < 8)
2734 BEAlign = 8 - OpSize;
2735 }
2736 unsigned LocMemOffset = VA.getLocMemOffset();
2737 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002738 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002739 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2740
2741 if (IsTailCall) {
2742 Offset = Offset + FPDiff;
2743 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2744
2745 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
2746 DstInfo = MachinePointerInfo::getFixedStack(FI);
2747
2748 // Make sure any stack arguments overlapping with where we're storing
2749 // are loaded before this eventual operation. Otherwise they'll be
2750 // clobbered.
2751 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2752 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002753 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002754
2755 DstAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2756 DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2757 }
2758
2759 if (Outs[i].Flags.isByVal()) {
2760 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002761 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00002762 SDValue Cpy = DAG.getMemcpy(
2763 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00002764 /*isVol = */ false, /*AlwaysInline = */ false,
2765 /*isTailCall = */ false,
2766 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00002767
2768 MemOpChains.push_back(Cpy);
2769 } else {
2770 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2771 // promoted to a legal register type i32, we should truncate Arg back to
2772 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00002773 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
2774 VA.getValVT() == MVT::i16)
2775 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00002776
2777 SDValue Store =
2778 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
2779 MemOpChains.push_back(Store);
2780 }
2781 }
2782 }
2783
2784 if (!MemOpChains.empty())
2785 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2786
2787 // Build a sequence of copy-to-reg nodes chained together with token chain
2788 // and flag operands which copy the outgoing args into the appropriate regs.
2789 SDValue InFlag;
2790 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2791 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2792 RegsToPass[i].second, InFlag);
2793 InFlag = Chain.getValue(1);
2794 }
2795
2796 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2797 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2798 // node so that legalize doesn't hack it.
2799 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2800 Subtarget->isTargetMachO()) {
2801 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2802 const GlobalValue *GV = G->getGlobal();
2803 bool InternalLinkage = GV->hasInternalLinkage();
2804 if (InternalLinkage)
2805 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2806 else {
2807 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2808 AArch64II::MO_GOT);
2809 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2810 }
2811 } else if (ExternalSymbolSDNode *S =
2812 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2813 const char *Sym = S->getSymbol();
2814 Callee =
2815 DAG.getTargetExternalSymbol(Sym, getPointerTy(), AArch64II::MO_GOT);
2816 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2817 }
2818 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2819 const GlobalValue *GV = G->getGlobal();
2820 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2821 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2822 const char *Sym = S->getSymbol();
2823 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2824 }
2825
2826 // We don't usually want to end the call-sequence here because we would tidy
2827 // the frame up *after* the call, however in the ABI-changing tail-call case
2828 // we've carefully laid out the parameters so that when sp is reset they'll be
2829 // in the correct location.
2830 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002831 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
2832 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002833 InFlag = Chain.getValue(1);
2834 }
2835
2836 std::vector<SDValue> Ops;
2837 Ops.push_back(Chain);
2838 Ops.push_back(Callee);
2839
2840 if (IsTailCall) {
2841 // Each tail call may have to adjust the stack by a different amount, so
2842 // this information must travel along with the operation for eventual
2843 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002844 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00002845 }
2846
2847 // Add argument registers to the end of the list so that they are known live
2848 // into the call.
2849 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2850 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2851 RegsToPass[i].second.getValueType()));
2852
2853 // Add a register mask operand representing the call-preserved registers.
2854 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00002855 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002856 if (IsThisReturn) {
2857 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00002858 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00002859 if (!Mask) {
2860 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00002861 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00002862 }
2863 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00002864 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00002865
2866 assert(Mask && "Missing call preserved mask for calling convention");
2867 Ops.push_back(DAG.getRegisterMask(Mask));
2868
2869 if (InFlag.getNode())
2870 Ops.push_back(InFlag);
2871
2872 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2873
2874 // If we're doing a tall call, use a TC_RETURN here rather than an
2875 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00002876 if (IsTailCall) {
2877 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00002878 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00002879 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002880
2881 // Returns a chain and a flag for retval copy to use.
2882 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
2883 InFlag = Chain.getValue(1);
2884
2885 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
2886 ? RoundUpToAlignment(NumBytes, 16)
2887 : 0;
2888
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002889 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
2890 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00002891 InFlag, DL);
2892 if (!Ins.empty())
2893 InFlag = Chain.getValue(1);
2894
2895 // Handle result values, copying them out of physregs into vregs that we
2896 // return.
2897 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2898 InVals, IsThisReturn,
2899 IsThisReturn ? OutVals[0] : SDValue());
2900}
2901
2902bool AArch64TargetLowering::CanLowerReturn(
2903 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2904 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2905 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2906 ? RetCC_AArch64_WebKit_JS
2907 : RetCC_AArch64_AAPCS;
2908 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002909 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00002910 return CCInfo.CheckReturn(Outs, RetCC);
2911}
2912
2913SDValue
2914AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2915 bool isVarArg,
2916 const SmallVectorImpl<ISD::OutputArg> &Outs,
2917 const SmallVectorImpl<SDValue> &OutVals,
2918 SDLoc DL, SelectionDAG &DAG) const {
2919 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2920 ? RetCC_AArch64_WebKit_JS
2921 : RetCC_AArch64_AAPCS;
2922 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002923 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2924 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002925 CCInfo.AnalyzeReturn(Outs, RetCC);
2926
2927 // Copy the result values into the output registers.
2928 SDValue Flag;
2929 SmallVector<SDValue, 4> RetOps(1, Chain);
2930 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2931 ++i, ++realRVLocIdx) {
2932 CCValAssign &VA = RVLocs[i];
2933 assert(VA.isRegLoc() && "Can only return in registers!");
2934 SDValue Arg = OutVals[realRVLocIdx];
2935
2936 switch (VA.getLocInfo()) {
2937 default:
2938 llvm_unreachable("Unknown loc info!");
2939 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00002940 if (Outs[i].ArgVT == MVT::i1) {
2941 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
2942 // value. This is strictly redundant on Darwin (which uses "zeroext
2943 // i1"), but will be optimised out before ISel.
2944 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2945 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2946 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002947 break;
2948 case CCValAssign::BCvt:
2949 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2950 break;
2951 }
2952
2953 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2954 Flag = Chain.getValue(1);
2955 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2956 }
2957
2958 RetOps[0] = Chain; // Update chain.
2959
2960 // Add the flag if we have it.
2961 if (Flag.getNode())
2962 RetOps.push_back(Flag);
2963
2964 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2965}
2966
2967//===----------------------------------------------------------------------===//
2968// Other Lowering Code
2969//===----------------------------------------------------------------------===//
2970
2971SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
2972 SelectionDAG &DAG) const {
2973 EVT PtrVT = getPointerTy();
2974 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00002975 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2976 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00002977 unsigned char OpFlags =
2978 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2979
2980 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2981 "unexpected offset in global node");
2982
2983 // This also catched the large code model case for Darwin.
2984 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2985 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2986 // FIXME: Once remat is capable of dealing with instructions with register
2987 // operands, expand this into two nodes instead of using a wrapper node.
2988 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
2989 }
2990
Asiri Rathnayake369c0302014-09-10 13:54:38 +00002991 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
2992 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2993 "use of MO_CONSTPOOL only supported on small model");
2994 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
2995 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2996 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2997 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
2998 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2999 SDValue GlobalAddr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3000 MachinePointerInfo::getConstantPool(),
3001 /*isVolatile=*/ false,
3002 /*isNonTemporal=*/ true,
3003 /*isInvariant=*/ true, 8);
3004 if (GN->getOffset() != 0)
3005 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003006 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003007 return GlobalAddr;
3008 }
3009
Tim Northover3b0846e2014-05-24 12:50:23 +00003010 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3011 const unsigned char MO_NC = AArch64II::MO_NC;
3012 return DAG.getNode(
3013 AArch64ISD::WrapperLarge, DL, PtrVT,
3014 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3015 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3016 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3017 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3018 } else {
3019 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3020 // the only correct model on Darwin.
3021 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3022 OpFlags | AArch64II::MO_PAGE);
3023 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3024 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3025
3026 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3027 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3028 }
3029}
3030
3031/// \brief Convert a TLS address reference into the correct sequence of loads
3032/// and calls to compute the variable's address (for Darwin, currently) and
3033/// return an SDValue containing the final node.
3034
3035/// Darwin only has one TLS scheme which must be capable of dealing with the
3036/// fully general situation, in the worst case. This means:
3037/// + "extern __thread" declaration.
3038/// + Defined in a possibly unknown dynamic library.
3039///
3040/// The general system is that each __thread variable has a [3 x i64] descriptor
3041/// which contains information used by the runtime to calculate the address. The
3042/// only part of this the compiler needs to know about is the first xword, which
3043/// contains a function pointer that must be called with the address of the
3044/// entire descriptor in "x0".
3045///
3046/// Since this descriptor may be in a different unit, in general even the
3047/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3048/// is:
3049/// adrp x0, _var@TLVPPAGE
3050/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3051/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3052/// ; the function pointer
3053/// blr x1 ; Uses descriptor address in x0
3054/// ; Address of _var is now in x0.
3055///
3056/// If the address of _var's descriptor *is* known to the linker, then it can
3057/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3058/// a slight efficiency gain.
3059SDValue
3060AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3061 SelectionDAG &DAG) const {
3062 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3063
3064 SDLoc DL(Op);
3065 MVT PtrVT = getPointerTy();
3066 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3067
3068 SDValue TLVPAddr =
3069 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3070 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3071
3072 // The first entry in the descriptor is a function pointer that we must call
3073 // to obtain the address of the variable.
3074 SDValue Chain = DAG.getEntryNode();
3075 SDValue FuncTLVGet =
3076 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
3077 false, true, true, 8);
3078 Chain = FuncTLVGet.getValue(1);
3079
3080 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3081 MFI->setAdjustsStack(true);
3082
3083 // TLS calls preserve all registers except those that absolutely must be
3084 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3085 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003086 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003087 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003088
3089 // Finally, we can make the call. This is just a degenerate version of a
3090 // normal AArch64 call node: x0 takes the address of the descriptor, and
3091 // returns the address of the variable in this thread.
3092 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3093 Chain =
3094 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3095 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3096 DAG.getRegisterMask(Mask), Chain.getValue(1));
3097 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3098}
3099
3100/// When accessing thread-local variables under either the general-dynamic or
3101/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3102/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003103/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003104///
Kristof Beylsaea84612015-03-04 09:12:08 +00003105/// The sequence is:
3106/// adrp x0, :tlsdesc:var
3107/// ldr x1, [x0, #:tlsdesc_lo12:var]
3108/// add x0, x0, #:tlsdesc_lo12:var
3109/// .tlsdesccall var
3110/// blr x1
3111/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003112///
Kristof Beylsaea84612015-03-04 09:12:08 +00003113/// The above sequence must be produced unscheduled, to enable the linker to
3114/// optimize/relax this sequence.
3115/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3116/// above sequence, and expanded really late in the compilation flow, to ensure
3117/// the sequence is produced as per above.
3118SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3119 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003120 EVT PtrVT = getPointerTy();
3121
Kristof Beylsaea84612015-03-04 09:12:08 +00003122 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003123 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003124
3125 SmallVector<SDValue, 2> Ops;
3126 Ops.push_back(Chain);
3127 Ops.push_back(SymAddr);
3128
3129 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3130 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003131
3132 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3133}
3134
3135SDValue
3136AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3137 SelectionDAG &DAG) const {
3138 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3139 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3140 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003141 // Different choices can be made for the maximum size of the TLS area for a
3142 // module. For the small address model, the default TLS size is 16MiB and the
3143 // maximum TLS size is 4GiB.
3144 // FIXME: add -mtls-size command line option and make it control the 16MiB
3145 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003146 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3147
3148 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Kristof Beylsaea84612015-03-04 09:12:08 +00003149 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3150 if (Model == TLSModel::LocalDynamic)
3151 Model = TLSModel::GeneralDynamic;
3152 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003153
3154 SDValue TPOff;
3155 EVT PtrVT = getPointerTy();
3156 SDLoc DL(Op);
3157 const GlobalValue *GV = GA->getGlobal();
3158
3159 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3160
3161 if (Model == TLSModel::LocalExec) {
3162 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003163 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003164 SDValue LoVar = DAG.getTargetGlobalAddress(
3165 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003166 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003167
Kristof Beylsaea84612015-03-04 09:12:08 +00003168 SDValue TPWithOff_lo =
3169 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003170 HiVar,
3171 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003172 0);
3173 SDValue TPWithOff =
3174 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003175 LoVar,
3176 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003177 0);
3178 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003179 } else if (Model == TLSModel::InitialExec) {
3180 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3181 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3182 } else if (Model == TLSModel::LocalDynamic) {
3183 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3184 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3185 // the beginning of the module's TLS region, followed by a DTPREL offset
3186 // calculation.
3187
3188 // These accesses will need deduplicating if there's more than one.
3189 AArch64FunctionInfo *MFI =
3190 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3191 MFI->incNumLocalDynamicTLSAccesses();
3192
Tim Northover3b0846e2014-05-24 12:50:23 +00003193 // The call needs a relocation too for linker relaxation. It doesn't make
3194 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3195 // the address.
3196 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3197 AArch64II::MO_TLS);
3198
3199 // Now we can calculate the offset from TPIDR_EL0 to this module's
3200 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003201 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003202
3203 // Now use :dtprel_whatever: operations to calculate this variable's offset
3204 // in its thread-storage area.
3205 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003206 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003207 SDValue LoVar = DAG.getTargetGlobalAddress(
3208 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003209 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3210
Kristof Beylsaea84612015-03-04 09:12:08 +00003211 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003212 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003213 0);
3214 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003215 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003216 0);
3217 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003218 // The call needs a relocation too for linker relaxation. It doesn't make
3219 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3220 // the address.
3221 SDValue SymAddr =
3222 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3223
3224 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003225 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003226 } else
3227 llvm_unreachable("Unsupported ELF TLS access model");
3228
3229 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3230}
3231
3232SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3233 SelectionDAG &DAG) const {
3234 if (Subtarget->isTargetDarwin())
3235 return LowerDarwinGlobalTLSAddress(Op, DAG);
3236 else if (Subtarget->isTargetELF())
3237 return LowerELFGlobalTLSAddress(Op, DAG);
3238
3239 llvm_unreachable("Unexpected platform trying to use TLS");
3240}
3241SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3242 SDValue Chain = Op.getOperand(0);
3243 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3244 SDValue LHS = Op.getOperand(2);
3245 SDValue RHS = Op.getOperand(3);
3246 SDValue Dest = Op.getOperand(4);
3247 SDLoc dl(Op);
3248
3249 // Handle f128 first, since lowering it will result in comparing the return
3250 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3251 // is expecting to deal with.
3252 if (LHS.getValueType() == MVT::f128) {
3253 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3254
3255 // If softenSetCCOperands returned a scalar, we need to compare the result
3256 // against zero to select between true and false values.
3257 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003258 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003259 CC = ISD::SETNE;
3260 }
3261 }
3262
3263 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3264 // instruction.
3265 unsigned Opc = LHS.getOpcode();
3266 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3267 cast<ConstantSDNode>(RHS)->isOne() &&
3268 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3269 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3270 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3271 "Unexpected condition code.");
3272 // Only lower legal XALUO ops.
3273 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3274 return SDValue();
3275
3276 // The actual operation with overflow check.
3277 AArch64CC::CondCode OFCC;
3278 SDValue Value, Overflow;
3279 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3280
3281 if (CC == ISD::SETNE)
3282 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003283 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003284
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003285 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3286 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003287 }
3288
3289 if (LHS.getValueType().isInteger()) {
3290 assert((LHS.getValueType() == RHS.getValueType()) &&
3291 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3292
3293 // If the RHS of the comparison is zero, we can potentially fold this
3294 // to a specialized branch.
3295 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3296 if (RHSC && RHSC->getZExtValue() == 0) {
3297 if (CC == ISD::SETEQ) {
3298 // See if we can use a TBZ to fold in an AND as well.
3299 // TBZ has a smaller branch displacement than CBZ. If the offset is
3300 // out of bounds, a late MI-layer pass rewrites branches.
3301 // 403.gcc is an example that hits this case.
3302 if (LHS.getOpcode() == ISD::AND &&
3303 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3304 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3305 SDValue Test = LHS.getOperand(0);
3306 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003307 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003308 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3309 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003310 }
3311
3312 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3313 } else if (CC == ISD::SETNE) {
3314 // See if we can use a TBZ to fold in an AND as well.
3315 // TBZ has a smaller branch displacement than CBZ. If the offset is
3316 // out of bounds, a late MI-layer pass rewrites branches.
3317 // 403.gcc is an example that hits this case.
3318 if (LHS.getOpcode() == ISD::AND &&
3319 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3320 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3321 SDValue Test = LHS.getOperand(0);
3322 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003323 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003324 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3325 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003326 }
3327
3328 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003329 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3330 // Don't combine AND since emitComparison converts the AND to an ANDS
3331 // (a.k.a. TST) and the test in the test bit and branch instruction
3332 // becomes redundant. This would also increase register pressure.
3333 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3334 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003335 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003336 }
3337 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003338 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3339 LHS.getOpcode() != ISD::AND) {
3340 // Don't combine AND since emitComparison converts the AND to an ANDS
3341 // (a.k.a. TST) and the test in the test bit and branch instruction
3342 // becomes redundant. This would also increase register pressure.
3343 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3344 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003345 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003346 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003347
3348 SDValue CCVal;
3349 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3350 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3351 Cmp);
3352 }
3353
3354 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3355
3356 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3357 // clean. Some of them require two branches to implement.
3358 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3359 AArch64CC::CondCode CC1, CC2;
3360 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003361 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003362 SDValue BR1 =
3363 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3364 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003365 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003366 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3367 Cmp);
3368 }
3369
3370 return BR1;
3371}
3372
3373SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3374 SelectionDAG &DAG) const {
3375 EVT VT = Op.getValueType();
3376 SDLoc DL(Op);
3377
3378 SDValue In1 = Op.getOperand(0);
3379 SDValue In2 = Op.getOperand(1);
3380 EVT SrcVT = In2.getValueType();
3381 if (SrcVT != VT) {
3382 if (SrcVT == MVT::f32 && VT == MVT::f64)
3383 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3384 else if (SrcVT == MVT::f64 && VT == MVT::f32)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003385 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2,
3386 DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003387 else
3388 // FIXME: Src type is different, bail out for now. Can VT really be a
3389 // vector type?
3390 return SDValue();
3391 }
3392
3393 EVT VecVT;
3394 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003395 uint64_t EltMask;
3396 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003397 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3398 EltVT = MVT::i32;
3399 VecVT = MVT::v4i32;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003400 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003401
3402 if (!VT.isVector()) {
3403 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3404 DAG.getUNDEF(VecVT), In1);
3405 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3406 DAG.getUNDEF(VecVT), In2);
3407 } else {
3408 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3409 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3410 }
3411 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3412 EltVT = MVT::i64;
3413 VecVT = MVT::v2i64;
3414
3415 // We want to materialize a mask with the the high bit set, but the AdvSIMD
3416 // immediate moves cannot materialize that in a single instruction for
3417 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003418 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003419
3420 if (!VT.isVector()) {
3421 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3422 DAG.getUNDEF(VecVT), In1);
3423 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3424 DAG.getUNDEF(VecVT), In2);
3425 } else {
3426 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3427 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3428 }
3429 } else {
3430 llvm_unreachable("Invalid type for copysign!");
3431 }
3432
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003433 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003434
3435 // If we couldn't materialize the mask above, then the mask vector will be
3436 // the zero vector, and we need to negate it here.
3437 if (VT == MVT::f64 || VT == MVT::v2f64) {
3438 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3439 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3440 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3441 }
3442
3443 SDValue Sel =
3444 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3445
3446 if (VT == MVT::f32)
3447 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3448 else if (VT == MVT::f64)
3449 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3450 else
3451 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3452}
3453
3454SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003455 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3456 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003457 return SDValue();
3458
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003459 if (!Subtarget->hasNEON())
3460 return SDValue();
3461
Tim Northover3b0846e2014-05-24 12:50:23 +00003462 // While there is no integer popcount instruction, it can
3463 // be more efficiently lowered to the following sequence that uses
3464 // AdvSIMD registers/instructions as long as the copies to/from
3465 // the AdvSIMD registers are cheap.
3466 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3467 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3468 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3469 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3470 SDValue Val = Op.getOperand(0);
3471 SDLoc DL(Op);
3472 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003473
Hao Liue0335d72015-01-30 02:13:53 +00003474 if (VT == MVT::i32)
3475 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3476 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003477
Hao Liue0335d72015-01-30 02:13:53 +00003478 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003479 SDValue UaddLV = DAG.getNode(
3480 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003481 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003482
3483 if (VT == MVT::i64)
3484 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3485 return UaddLV;
3486}
3487
3488SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3489
3490 if (Op.getValueType().isVector())
3491 return LowerVSETCC(Op, DAG);
3492
3493 SDValue LHS = Op.getOperand(0);
3494 SDValue RHS = Op.getOperand(1);
3495 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3496 SDLoc dl(Op);
3497
3498 // We chose ZeroOrOneBooleanContents, so use zero and one.
3499 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003500 SDValue TVal = DAG.getConstant(1, dl, VT);
3501 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003502
3503 // Handle f128 first, since one possible outcome is a normal integer
3504 // comparison which gets picked up by the next if statement.
3505 if (LHS.getValueType() == MVT::f128) {
3506 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3507
3508 // If softenSetCCOperands returned a scalar, use it.
3509 if (!RHS.getNode()) {
3510 assert(LHS.getValueType() == Op.getValueType() &&
3511 "Unexpected setcc expansion!");
3512 return LHS;
3513 }
3514 }
3515
3516 if (LHS.getValueType().isInteger()) {
3517 SDValue CCVal;
3518 SDValue Cmp =
3519 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3520
3521 // Note that we inverted the condition above, so we reverse the order of
3522 // the true and false operands here. This will allow the setcc to be
3523 // matched to a single CSINC instruction.
3524 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3525 }
3526
3527 // Now we know we're dealing with FP values.
3528 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3529
3530 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3531 // and do the comparison.
3532 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3533
3534 AArch64CC::CondCode CC1, CC2;
3535 changeFPCCToAArch64CC(CC, CC1, CC2);
3536 if (CC2 == AArch64CC::AL) {
3537 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003538 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003539
3540 // Note that we inverted the condition above, so we reverse the order of
3541 // the true and false operands here. This will allow the setcc to be
3542 // matched to a single CSINC instruction.
3543 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3544 } else {
3545 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3546 // totally clean. Some of them require two CSELs to implement. As is in
3547 // this case, we emit the first CSEL and then emit a second using the output
3548 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3549
3550 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003551 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003552 SDValue CS1 =
3553 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3554
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003555 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003556 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3557 }
3558}
3559
3560/// A SELECT_CC operation is really some kind of max or min if both values being
3561/// compared are, in some sense, equal to the results in either case. However,
3562/// it is permissible to compare f32 values and produce directly extended f64
3563/// values.
3564///
3565/// Extending the comparison operands would also be allowed, but is less likely
3566/// to happen in practice since their use is right here. Note that truncate
3567/// operations would *not* be semantically equivalent.
3568static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3569 if (Cmp == Result)
3570 return true;
3571
3572 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3573 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3574 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3575 Result.getValueType() == MVT::f64) {
3576 bool Lossy;
3577 APFloat CmpVal = CCmp->getValueAPF();
3578 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3579 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3580 }
3581
3582 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3583}
3584
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003585SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3586 SDValue RHS, SDValue TVal,
3587 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003588 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003589 // Handle f128 first, because it will result in a comparison of some RTLIB
3590 // call result against zero.
3591 if (LHS.getValueType() == MVT::f128) {
3592 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3593
3594 // If softenSetCCOperands returned a scalar, we need to compare the result
3595 // against zero to select between true and false values.
3596 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003597 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003598 CC = ISD::SETNE;
3599 }
3600 }
3601
3602 // Handle integers first.
3603 if (LHS.getValueType().isInteger()) {
3604 assert((LHS.getValueType() == RHS.getValueType()) &&
3605 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3606
3607 unsigned Opcode = AArch64ISD::CSEL;
3608
3609 // If both the TVal and the FVal are constants, see if we can swap them in
3610 // order to for a CSINV or CSINC out of them.
3611 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3612 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3613
3614 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3615 std::swap(TVal, FVal);
3616 std::swap(CTVal, CFVal);
3617 CC = ISD::getSetCCInverse(CC, true);
3618 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3619 std::swap(TVal, FVal);
3620 std::swap(CTVal, CFVal);
3621 CC = ISD::getSetCCInverse(CC, true);
3622 } else if (TVal.getOpcode() == ISD::XOR) {
3623 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3624 // with a CSINV rather than a CSEL.
3625 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3626
3627 if (CVal && CVal->isAllOnesValue()) {
3628 std::swap(TVal, FVal);
3629 std::swap(CTVal, CFVal);
3630 CC = ISD::getSetCCInverse(CC, true);
3631 }
3632 } else if (TVal.getOpcode() == ISD::SUB) {
3633 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3634 // that we can match with a CSNEG rather than a CSEL.
3635 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3636
3637 if (CVal && CVal->isNullValue()) {
3638 std::swap(TVal, FVal);
3639 std::swap(CTVal, CFVal);
3640 CC = ISD::getSetCCInverse(CC, true);
3641 }
3642 } else if (CTVal && CFVal) {
3643 const int64_t TrueVal = CTVal->getSExtValue();
3644 const int64_t FalseVal = CFVal->getSExtValue();
3645 bool Swap = false;
3646
3647 // If both TVal and FVal are constants, see if FVal is the
3648 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3649 // instead of a CSEL in that case.
3650 if (TrueVal == ~FalseVal) {
3651 Opcode = AArch64ISD::CSINV;
3652 } else if (TrueVal == -FalseVal) {
3653 Opcode = AArch64ISD::CSNEG;
3654 } else if (TVal.getValueType() == MVT::i32) {
3655 // If our operands are only 32-bit wide, make sure we use 32-bit
3656 // arithmetic for the check whether we can use CSINC. This ensures that
3657 // the addition in the check will wrap around properly in case there is
3658 // an overflow (which would not be the case if we do the check with
3659 // 64-bit arithmetic).
3660 const uint32_t TrueVal32 = CTVal->getZExtValue();
3661 const uint32_t FalseVal32 = CFVal->getZExtValue();
3662
3663 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3664 Opcode = AArch64ISD::CSINC;
3665
3666 if (TrueVal32 > FalseVal32) {
3667 Swap = true;
3668 }
3669 }
3670 // 64-bit check whether we can use CSINC.
3671 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3672 Opcode = AArch64ISD::CSINC;
3673
3674 if (TrueVal > FalseVal) {
3675 Swap = true;
3676 }
3677 }
3678
3679 // Swap TVal and FVal if necessary.
3680 if (Swap) {
3681 std::swap(TVal, FVal);
3682 std::swap(CTVal, CFVal);
3683 CC = ISD::getSetCCInverse(CC, true);
3684 }
3685
3686 if (Opcode != AArch64ISD::CSEL) {
3687 // Drop FVal since we can get its value by simply inverting/negating
3688 // TVal.
3689 FVal = TVal;
3690 }
3691 }
3692
3693 SDValue CCVal;
3694 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3695
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003696 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003697 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3698 }
3699
3700 // Now we know we're dealing with FP values.
3701 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3702 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003703 EVT VT = TVal.getValueType();
Silviu Baranga780a3b32015-05-13 14:03:18 +00003704
3705 // Try to match this select into a max/min operation, which have dedicated
3706 // opcode in the instruction set.
3707 // FIXME: This is not correct in the presence of NaNs, so we only enable this
3708 // in no-NaNs mode.
3709 if (getTargetMachine().Options.NoNaNsFPMath) {
3710 SDValue MinMaxLHS = TVal, MinMaxRHS = FVal;
3711 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxRHS) &&
3712 selectCCOpsAreFMaxCompatible(RHS, MinMaxLHS)) {
3713 CC = ISD::getSetCCSwappedOperands(CC);
3714 std::swap(MinMaxLHS, MinMaxRHS);
3715 }
3716
3717 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxLHS) &&
3718 selectCCOpsAreFMaxCompatible(RHS, MinMaxRHS)) {
3719 switch (CC) {
3720 default:
3721 break;
3722 case ISD::SETGT:
3723 case ISD::SETGE:
3724 case ISD::SETUGT:
3725 case ISD::SETUGE:
3726 case ISD::SETOGT:
3727 case ISD::SETOGE:
3728 return DAG.getNode(AArch64ISD::FMAX, dl, VT, MinMaxLHS, MinMaxRHS);
3729 break;
3730 case ISD::SETLT:
3731 case ISD::SETLE:
3732 case ISD::SETULT:
3733 case ISD::SETULE:
3734 case ISD::SETOLT:
3735 case ISD::SETOLE:
3736 return DAG.getNode(AArch64ISD::FMIN, dl, VT, MinMaxLHS, MinMaxRHS);
3737 break;
3738 }
3739 }
3740 }
3741
3742 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3743 // and do the comparison.
Tim Northover3b0846e2014-05-24 12:50:23 +00003744 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3745
3746 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3747 // clean. Some of them require two CSELs to implement.
3748 AArch64CC::CondCode CC1, CC2;
3749 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003750 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003751 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3752
3753 // If we need a second CSEL, emit it, using the output of the first as the
3754 // RHS. We're effectively OR'ing the two CC's together.
3755 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003756 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003757 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3758 }
3759
3760 // Otherwise, return the output of the first CSEL.
3761 return CS1;
3762}
3763
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003764SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3765 SelectionDAG &DAG) const {
3766 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3767 SDValue LHS = Op.getOperand(0);
3768 SDValue RHS = Op.getOperand(1);
3769 SDValue TVal = Op.getOperand(2);
3770 SDValue FVal = Op.getOperand(3);
3771 SDLoc DL(Op);
3772 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3773}
3774
3775SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3776 SelectionDAG &DAG) const {
3777 SDValue CCVal = Op->getOperand(0);
3778 SDValue TVal = Op->getOperand(1);
3779 SDValue FVal = Op->getOperand(2);
3780 SDLoc DL(Op);
3781
3782 unsigned Opc = CCVal.getOpcode();
3783 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3784 // instruction.
3785 if (CCVal.getResNo() == 1 &&
3786 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3787 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3788 // Only lower legal XALUO ops.
3789 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
3790 return SDValue();
3791
3792 AArch64CC::CondCode OFCC;
3793 SDValue Value, Overflow;
3794 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003795 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003796
3797 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3798 CCVal, Overflow);
3799 }
3800
3801 // Lower it the same way as we would lower a SELECT_CC node.
3802 ISD::CondCode CC;
3803 SDValue LHS, RHS;
3804 if (CCVal.getOpcode() == ISD::SETCC) {
3805 LHS = CCVal.getOperand(0);
3806 RHS = CCVal.getOperand(1);
3807 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
3808 } else {
3809 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003810 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003811 CC = ISD::SETNE;
3812 }
3813 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3814}
3815
Tim Northover3b0846e2014-05-24 12:50:23 +00003816SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
3817 SelectionDAG &DAG) const {
3818 // Jump table entries as PC relative offsets. No additional tweaking
3819 // is necessary here. Just get the address of the jump table.
3820 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3821 EVT PtrVT = getPointerTy();
3822 SDLoc DL(Op);
3823
3824 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3825 !Subtarget->isTargetMachO()) {
3826 const unsigned char MO_NC = AArch64II::MO_NC;
3827 return DAG.getNode(
3828 AArch64ISD::WrapperLarge, DL, PtrVT,
3829 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
3830 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
3831 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
3832 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3833 AArch64II::MO_G0 | MO_NC));
3834 }
3835
3836 SDValue Hi =
3837 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
3838 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3839 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3840 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3841 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3842}
3843
3844SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
3845 SelectionDAG &DAG) const {
3846 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3847 EVT PtrVT = getPointerTy();
3848 SDLoc DL(Op);
3849
3850 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3851 // Use the GOT for the large code model on iOS.
3852 if (Subtarget->isTargetMachO()) {
3853 SDValue GotAddr = DAG.getTargetConstantPool(
3854 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3855 AArch64II::MO_GOT);
3856 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3857 }
3858
3859 const unsigned char MO_NC = AArch64II::MO_NC;
3860 return DAG.getNode(
3861 AArch64ISD::WrapperLarge, DL, PtrVT,
3862 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3863 CP->getOffset(), AArch64II::MO_G3),
3864 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3865 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
3866 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3867 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
3868 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3869 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
3870 } else {
3871 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3872 // ELF, the only valid one on Darwin.
3873 SDValue Hi =
3874 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3875 CP->getOffset(), AArch64II::MO_PAGE);
3876 SDValue Lo = DAG.getTargetConstantPool(
3877 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3878 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3879
3880 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3881 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3882 }
3883}
3884
3885SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
3886 SelectionDAG &DAG) const {
3887 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3888 EVT PtrVT = getPointerTy();
3889 SDLoc DL(Op);
3890 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3891 !Subtarget->isTargetMachO()) {
3892 const unsigned char MO_NC = AArch64II::MO_NC;
3893 return DAG.getNode(
3894 AArch64ISD::WrapperLarge, DL, PtrVT,
3895 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
3896 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3897 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3898 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3899 } else {
3900 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
3901 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
3902 AArch64II::MO_NC);
3903 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3904 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3905 }
3906}
3907
3908SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3909 SelectionDAG &DAG) const {
3910 AArch64FunctionInfo *FuncInfo =
3911 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3912
3913 SDLoc DL(Op);
3914 SDValue FR =
3915 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3916 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3917 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3918 MachinePointerInfo(SV), false, false, 0);
3919}
3920
3921SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3922 SelectionDAG &DAG) const {
3923 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3924 // Standard, section B.3.
3925 MachineFunction &MF = DAG.getMachineFunction();
3926 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3927 SDLoc DL(Op);
3928
3929 SDValue Chain = Op.getOperand(0);
3930 SDValue VAList = Op.getOperand(1);
3931 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3932 SmallVector<SDValue, 4> MemOps;
3933
3934 // void *__stack at offset 0
3935 SDValue Stack =
3936 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3937 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3938 MachinePointerInfo(SV), false, false, 8));
3939
3940 // void *__gr_top at offset 8
3941 int GPRSize = FuncInfo->getVarArgsGPRSize();
3942 if (GPRSize > 0) {
3943 SDValue GRTop, GRTopAddr;
3944
3945 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003946 DAG.getConstant(8, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003947
3948 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3949 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003950 DAG.getConstant(GPRSize, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003951
3952 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3953 MachinePointerInfo(SV, 8), false, false, 8));
3954 }
3955
3956 // void *__vr_top at offset 16
3957 int FPRSize = FuncInfo->getVarArgsFPRSize();
3958 if (FPRSize > 0) {
3959 SDValue VRTop, VRTopAddr;
3960 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003961 DAG.getConstant(16, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003962
3963 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3964 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003965 DAG.getConstant(FPRSize, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003966
3967 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3968 MachinePointerInfo(SV, 16), false, false, 8));
3969 }
3970
3971 // int __gr_offs at offset 24
3972 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003973 DAG.getConstant(24, DL, getPointerTy()));
3974 MemOps.push_back(DAG.getStore(Chain, DL,
3975 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00003976 GROffsAddr, MachinePointerInfo(SV, 24), false,
3977 false, 4));
3978
3979 // int __vr_offs at offset 28
3980 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003981 DAG.getConstant(28, DL, getPointerTy()));
3982 MemOps.push_back(DAG.getStore(Chain, DL,
3983 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00003984 VROffsAddr, MachinePointerInfo(SV, 28), false,
3985 false, 4));
3986
3987 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3988}
3989
3990SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
3991 SelectionDAG &DAG) const {
3992 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3993 : LowerAAPCS_VASTART(Op, DAG);
3994}
3995
3996SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
3997 SelectionDAG &DAG) const {
3998 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3999 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004000 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004001 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4002 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4003 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4004
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004005 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4006 Op.getOperand(2),
4007 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004008 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004009 MachinePointerInfo(SrcSV));
4010}
4011
4012SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4013 assert(Subtarget->isTargetDarwin() &&
4014 "automatic va_arg instruction only works on Darwin");
4015
4016 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4017 EVT VT = Op.getValueType();
4018 SDLoc DL(Op);
4019 SDValue Chain = Op.getOperand(0);
4020 SDValue Addr = Op.getOperand(1);
4021 unsigned Align = Op.getConstantOperandVal(3);
4022
4023 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
4024 MachinePointerInfo(V), false, false, false, 0);
4025 Chain = VAList.getValue(1);
4026
4027 if (Align > 8) {
4028 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4029 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004030 DAG.getConstant(Align - 1, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004031 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004032 DAG.getConstant(-(int64_t)Align, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004033 }
4034
4035 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4036 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
4037
4038 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4039 // up to 64 bits. At the very least, we have to increase the striding of the
4040 // vaargs list to match this, and for FP values we need to introduce
4041 // FP_ROUND nodes as well.
4042 if (VT.isInteger() && !VT.isVector())
4043 ArgSize = 8;
4044 bool NeedFPTrunc = false;
4045 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4046 ArgSize = 8;
4047 NeedFPTrunc = true;
4048 }
4049
4050 // Increment the pointer, VAList, to the next vaarg
4051 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004052 DAG.getConstant(ArgSize, DL, getPointerTy()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004053 // Store the incremented VAList to the legalized pointer
4054 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4055 false, false, 0);
4056
4057 // Load the actual argument out of the pointer VAList
4058 if (NeedFPTrunc) {
4059 // Load the value as an f64.
4060 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4061 MachinePointerInfo(), false, false, false, 0);
4062 // Round the value down to an f32.
4063 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004064 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004065 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4066 // Merge the rounded value with the chain output of the load.
4067 return DAG.getMergeValues(Ops, DL);
4068 }
4069
4070 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4071 false, false, 0);
4072}
4073
4074SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4075 SelectionDAG &DAG) const {
4076 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4077 MFI->setFrameAddressIsTaken(true);
4078
4079 EVT VT = Op.getValueType();
4080 SDLoc DL(Op);
4081 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4082 SDValue FrameAddr =
4083 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4084 while (Depth--)
4085 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4086 MachinePointerInfo(), false, false, false, 0);
4087 return FrameAddr;
4088}
4089
4090// FIXME? Maybe this could be a TableGen attribute on some registers and
4091// this table could be generated automatically from RegInfo.
4092unsigned AArch64TargetLowering::getRegisterByName(const char* RegName,
4093 EVT VT) const {
4094 unsigned Reg = StringSwitch<unsigned>(RegName)
4095 .Case("sp", AArch64::SP)
4096 .Default(0);
4097 if (Reg)
4098 return Reg;
4099 report_fatal_error("Invalid register name global variable");
4100}
4101
4102SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4103 SelectionDAG &DAG) const {
4104 MachineFunction &MF = DAG.getMachineFunction();
4105 MachineFrameInfo *MFI = MF.getFrameInfo();
4106 MFI->setReturnAddressIsTaken(true);
4107
4108 EVT VT = Op.getValueType();
4109 SDLoc DL(Op);
4110 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4111 if (Depth) {
4112 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004113 SDValue Offset = DAG.getConstant(8, DL, getPointerTy());
Tim Northover3b0846e2014-05-24 12:50:23 +00004114 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4115 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4116 MachinePointerInfo(), false, false, false, 0);
4117 }
4118
4119 // Return LR, which contains the return address. Mark it an implicit live-in.
4120 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4121 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4122}
4123
4124/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4125/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4126SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4127 SelectionDAG &DAG) const {
4128 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4129 EVT VT = Op.getValueType();
4130 unsigned VTBits = VT.getSizeInBits();
4131 SDLoc dl(Op);
4132 SDValue ShOpLo = Op.getOperand(0);
4133 SDValue ShOpHi = Op.getOperand(1);
4134 SDValue ShAmt = Op.getOperand(2);
4135 SDValue ARMcc;
4136 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4137
4138 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4139
4140 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004141 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004142 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4143 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004144 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004145 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4146
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004147 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00004148 ISD::SETGE, dl, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004149 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004150
4151 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4152 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4153 SDValue Lo =
4154 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4155
4156 // AArch64 shifts larger than the register width are wrapped rather than
4157 // clamped, so we can't just emit "hi >> x".
4158 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4159 SDValue TrueValHi = Opc == ISD::SRA
4160 ? DAG.getNode(Opc, dl, VT, ShOpHi,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004161 DAG.getConstant(VTBits - 1, dl,
4162 MVT::i64))
4163 : DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004164 SDValue Hi =
4165 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4166
4167 SDValue Ops[2] = { Lo, Hi };
4168 return DAG.getMergeValues(Ops, dl);
4169}
4170
4171/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4172/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4173SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4174 SelectionDAG &DAG) const {
4175 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4176 EVT VT = Op.getValueType();
4177 unsigned VTBits = VT.getSizeInBits();
4178 SDLoc dl(Op);
4179 SDValue ShOpLo = Op.getOperand(0);
4180 SDValue ShOpHi = Op.getOperand(1);
4181 SDValue ShAmt = Op.getOperand(2);
4182 SDValue ARMcc;
4183
4184 assert(Op.getOpcode() == ISD::SHL_PARTS);
4185 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004186 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004187 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4188 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004189 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004190 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4191 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4192
4193 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4194
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004195 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00004196 ISD::SETGE, dl, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004197 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004198 SDValue Hi =
4199 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4200
4201 // AArch64 shifts of larger than register sizes are wrapped rather than
4202 // clamped, so we can't just emit "lo << a" if a is too big.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004203 SDValue TrueValLo = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004204 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4205 SDValue Lo =
4206 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4207
4208 SDValue Ops[2] = { Lo, Hi };
4209 return DAG.getMergeValues(Ops, dl);
4210}
4211
4212bool AArch64TargetLowering::isOffsetFoldingLegal(
4213 const GlobalAddressSDNode *GA) const {
4214 // The AArch64 target doesn't support folding offsets into global addresses.
4215 return false;
4216}
4217
4218bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4219 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4220 // FIXME: We should be able to handle f128 as well with a clever lowering.
4221 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4222 return true;
4223
4224 if (VT == MVT::f64)
4225 return AArch64_AM::getFP64Imm(Imm) != -1;
4226 else if (VT == MVT::f32)
4227 return AArch64_AM::getFP32Imm(Imm) != -1;
4228 return false;
4229}
4230
4231//===----------------------------------------------------------------------===//
4232// AArch64 Optimization Hooks
4233//===----------------------------------------------------------------------===//
4234
4235//===----------------------------------------------------------------------===//
4236// AArch64 Inline Assembly Support
4237//===----------------------------------------------------------------------===//
4238
4239// Table of Constraints
4240// TODO: This is the current set of constraints supported by ARM for the
4241// compiler, not all of them may make sense, e.g. S may be difficult to support.
4242//
4243// r - A general register
4244// w - An FP/SIMD register of some size in the range v0-v31
4245// x - An FP/SIMD register of some size in the range v0-v15
4246// I - Constant that can be used with an ADD instruction
4247// J - Constant that can be used with a SUB instruction
4248// K - Constant that can be used with a 32-bit logical instruction
4249// L - Constant that can be used with a 64-bit logical instruction
4250// M - Constant that can be used as a 32-bit MOV immediate
4251// N - Constant that can be used as a 64-bit MOV immediate
4252// Q - A memory reference with base register and no offset
4253// S - A symbolic address
4254// Y - Floating point constant zero
4255// Z - Integer constant zero
4256//
4257// Note that general register operands will be output using their 64-bit x
4258// register name, whatever the size of the variable, unless the asm operand
4259// is prefixed by the %w modifier. Floating-point and SIMD register operands
4260// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4261// %q modifier.
4262
4263/// getConstraintType - Given a constraint letter, return the type of
4264/// constraint it is for this target.
4265AArch64TargetLowering::ConstraintType
4266AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
4267 if (Constraint.size() == 1) {
4268 switch (Constraint[0]) {
4269 default:
4270 break;
4271 case 'z':
4272 return C_Other;
4273 case 'x':
4274 case 'w':
4275 return C_RegisterClass;
4276 // An address with a single base register. Due to the way we
4277 // currently handle addresses it is the same as 'r'.
4278 case 'Q':
4279 return C_Memory;
4280 }
4281 }
4282 return TargetLowering::getConstraintType(Constraint);
4283}
4284
4285/// Examine constraint type and operand type and determine a weight value.
4286/// This object must already have been set up with the operand type
4287/// and the current alternative constraint selected.
4288TargetLowering::ConstraintWeight
4289AArch64TargetLowering::getSingleConstraintMatchWeight(
4290 AsmOperandInfo &info, const char *constraint) const {
4291 ConstraintWeight weight = CW_Invalid;
4292 Value *CallOperandVal = info.CallOperandVal;
4293 // If we don't have a value, we can't do a match,
4294 // but allow it at the lowest weight.
4295 if (!CallOperandVal)
4296 return CW_Default;
4297 Type *type = CallOperandVal->getType();
4298 // Look at the constraint type.
4299 switch (*constraint) {
4300 default:
4301 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4302 break;
4303 case 'x':
4304 case 'w':
4305 if (type->isFloatingPointTy() || type->isVectorTy())
4306 weight = CW_Register;
4307 break;
4308 case 'z':
4309 weight = CW_Constant;
4310 break;
4311 }
4312 return weight;
4313}
4314
4315std::pair<unsigned, const TargetRegisterClass *>
4316AArch64TargetLowering::getRegForInlineAsmConstraint(
Eric Christopher11e4df72015-02-26 22:38:43 +00004317 const TargetRegisterInfo *TRI, const std::string &Constraint,
4318 MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004319 if (Constraint.size() == 1) {
4320 switch (Constraint[0]) {
4321 case 'r':
4322 if (VT.getSizeInBits() == 64)
4323 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4324 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4325 case 'w':
4326 if (VT == MVT::f32)
4327 return std::make_pair(0U, &AArch64::FPR32RegClass);
4328 if (VT.getSizeInBits() == 64)
4329 return std::make_pair(0U, &AArch64::FPR64RegClass);
4330 if (VT.getSizeInBits() == 128)
4331 return std::make_pair(0U, &AArch64::FPR128RegClass);
4332 break;
4333 // The instructions that this constraint is designed for can
4334 // only take 128-bit registers so just use that regclass.
4335 case 'x':
4336 if (VT.getSizeInBits() == 128)
4337 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4338 break;
4339 }
4340 }
4341 if (StringRef("{cc}").equals_lower(Constraint))
4342 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4343
4344 // Use the default implementation in TargetLowering to convert the register
4345 // constraint into a member of a register class.
4346 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004347 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004348
4349 // Not found as a standard register?
4350 if (!Res.second) {
4351 unsigned Size = Constraint.size();
4352 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4353 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4354 const std::string Reg =
4355 std::string(&Constraint[2], &Constraint[Size - 1]);
4356 int RegNo = atoi(Reg.c_str());
4357 if (RegNo >= 0 && RegNo <= 31) {
4358 // v0 - v31 are aliases of q0 - q31.
4359 // By default we'll emit v0-v31 for this unless there's a modifier where
4360 // we'll emit the correct register as well.
4361 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4362 Res.second = &AArch64::FPR128RegClass;
4363 }
4364 }
4365 }
4366
4367 return Res;
4368}
4369
4370/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4371/// vector. If it is invalid, don't add anything to Ops.
4372void AArch64TargetLowering::LowerAsmOperandForConstraint(
4373 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4374 SelectionDAG &DAG) const {
4375 SDValue Result;
4376
4377 // Currently only support length 1 constraints.
4378 if (Constraint.length() != 1)
4379 return;
4380
4381 char ConstraintLetter = Constraint[0];
4382 switch (ConstraintLetter) {
4383 default:
4384 break;
4385
4386 // This set of constraints deal with valid constants for various instructions.
4387 // Validate and return a target constant for them if we can.
4388 case 'z': {
4389 // 'z' maps to xzr or wzr so it needs an input of 0.
4390 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4391 if (!C || C->getZExtValue() != 0)
4392 return;
4393
4394 if (Op.getValueType() == MVT::i64)
4395 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4396 else
4397 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4398 break;
4399 }
4400
4401 case 'I':
4402 case 'J':
4403 case 'K':
4404 case 'L':
4405 case 'M':
4406 case 'N':
4407 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4408 if (!C)
4409 return;
4410
4411 // Grab the value and do some validation.
4412 uint64_t CVal = C->getZExtValue();
4413 switch (ConstraintLetter) {
4414 // The I constraint applies only to simple ADD or SUB immediate operands:
4415 // i.e. 0 to 4095 with optional shift by 12
4416 // The J constraint applies only to ADD or SUB immediates that would be
4417 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4418 // instruction [or vice versa], in other words -1 to -4095 with optional
4419 // left shift by 12.
4420 case 'I':
4421 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4422 break;
4423 return;
4424 case 'J': {
4425 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004426 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4427 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004428 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004429 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004430 return;
4431 }
4432 // The K and L constraints apply *only* to logical immediates, including
4433 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4434 // been removed and MOV should be used). So these constraints have to
4435 // distinguish between bit patterns that are valid 32-bit or 64-bit
4436 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4437 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4438 // versa.
4439 case 'K':
4440 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4441 break;
4442 return;
4443 case 'L':
4444 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4445 break;
4446 return;
4447 // The M and N constraints are a superset of K and L respectively, for use
4448 // with the MOV (immediate) alias. As well as the logical immediates they
4449 // also match 32 or 64-bit immediates that can be loaded either using a
4450 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4451 // (M) or 64-bit 0x1234000000000000 (N) etc.
4452 // As a note some of this code is liberally stolen from the asm parser.
4453 case 'M': {
4454 if (!isUInt<32>(CVal))
4455 return;
4456 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4457 break;
4458 if ((CVal & 0xFFFF) == CVal)
4459 break;
4460 if ((CVal & 0xFFFF0000ULL) == CVal)
4461 break;
4462 uint64_t NCVal = ~(uint32_t)CVal;
4463 if ((NCVal & 0xFFFFULL) == NCVal)
4464 break;
4465 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4466 break;
4467 return;
4468 }
4469 case 'N': {
4470 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4471 break;
4472 if ((CVal & 0xFFFFULL) == CVal)
4473 break;
4474 if ((CVal & 0xFFFF0000ULL) == CVal)
4475 break;
4476 if ((CVal & 0xFFFF00000000ULL) == CVal)
4477 break;
4478 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4479 break;
4480 uint64_t NCVal = ~CVal;
4481 if ((NCVal & 0xFFFFULL) == NCVal)
4482 break;
4483 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4484 break;
4485 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4486 break;
4487 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4488 break;
4489 return;
4490 }
4491 default:
4492 return;
4493 }
4494
4495 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004496 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004497 break;
4498 }
4499
4500 if (Result.getNode()) {
4501 Ops.push_back(Result);
4502 return;
4503 }
4504
4505 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4506}
4507
4508//===----------------------------------------------------------------------===//
4509// AArch64 Advanced SIMD Support
4510//===----------------------------------------------------------------------===//
4511
4512/// WidenVector - Given a value in the V64 register class, produce the
4513/// equivalent value in the V128 register class.
4514static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4515 EVT VT = V64Reg.getValueType();
4516 unsigned NarrowSize = VT.getVectorNumElements();
4517 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4518 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4519 SDLoc DL(V64Reg);
4520
4521 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004522 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004523}
4524
4525/// getExtFactor - Determine the adjustment factor for the position when
4526/// generating an "extract from vector registers" instruction.
4527static unsigned getExtFactor(SDValue &V) {
4528 EVT EltType = V.getValueType().getVectorElementType();
4529 return EltType.getSizeInBits() / 8;
4530}
4531
4532/// NarrowVector - Given a value in the V128 register class, produce the
4533/// equivalent value in the V64 register class.
4534static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4535 EVT VT = V128Reg.getValueType();
4536 unsigned WideSize = VT.getVectorNumElements();
4537 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4538 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4539 SDLoc DL(V128Reg);
4540
4541 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4542}
4543
4544// Gather data to see if the operation can be modelled as a
4545// shuffle in combination with VEXTs.
4546SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4547 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004548 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004549 SDLoc dl(Op);
4550 EVT VT = Op.getValueType();
4551 unsigned NumElts = VT.getVectorNumElements();
4552
Tim Northover7324e842014-07-24 15:39:55 +00004553 struct ShuffleSourceInfo {
4554 SDValue Vec;
4555 unsigned MinElt;
4556 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004557
Tim Northover7324e842014-07-24 15:39:55 +00004558 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4559 // be compatible with the shuffle we intend to construct. As a result
4560 // ShuffleVec will be some sliding window into the original Vec.
4561 SDValue ShuffleVec;
4562
4563 // Code should guarantee that element i in Vec starts at element "WindowBase
4564 // + i * WindowScale in ShuffleVec".
4565 int WindowBase;
4566 int WindowScale;
4567
4568 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4569 ShuffleSourceInfo(SDValue Vec)
4570 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4571 WindowScale(1) {}
4572 };
4573
4574 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4575 // node.
4576 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004577 for (unsigned i = 0; i < NumElts; ++i) {
4578 SDValue V = Op.getOperand(i);
4579 if (V.getOpcode() == ISD::UNDEF)
4580 continue;
4581 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4582 // A shuffle can only come from building a vector from various
4583 // elements of other vectors.
4584 return SDValue();
4585 }
4586
Tim Northover7324e842014-07-24 15:39:55 +00004587 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004588 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004589 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4590 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004591 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004592
Tim Northover7324e842014-07-24 15:39:55 +00004593 // Update the minimum and maximum lane number seen.
4594 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4595 Source->MinElt = std::min(Source->MinElt, EltNo);
4596 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004597 }
4598
4599 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004600 // are involved.
4601 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004602 return SDValue();
4603
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004604 // Find out the smallest element size among result and two sources, and use
4605 // it as element size to build the shuffle_vector.
4606 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004607 for (auto &Source : Sources) {
4608 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004609 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4610 SmallestEltTy = SrcEltTy;
4611 }
4612 }
4613 unsigned ResMultiplier =
4614 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004615 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4616 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00004617
Tim Northover7324e842014-07-24 15:39:55 +00004618 // If the source vector is too wide or too narrow, we may nevertheless be able
4619 // to construct a compatible shuffle either by concatenating it with UNDEF or
4620 // extracting a suitable range of elements.
4621 for (auto &Src : Sources) {
4622 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004623
Tim Northover7324e842014-07-24 15:39:55 +00004624 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00004625 continue;
Tim Northover7324e842014-07-24 15:39:55 +00004626
4627 // This stage of the search produces a source with the same element type as
4628 // the original, but with a total width matching the BUILD_VECTOR output.
4629 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00004630 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4631 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00004632
4633 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4634 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004635 // We can pad out the smaller vector for free, so if it's part of a
4636 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00004637 Src.ShuffleVec =
4638 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4639 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004640 continue;
4641 }
4642
Tim Northover7324e842014-07-24 15:39:55 +00004643 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004644
James Molloyf497d552014-10-17 17:06:31 +00004645 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004646 // Span too large for a VEXT to cope
4647 return SDValue();
4648 }
4649
James Molloyf497d552014-10-17 17:06:31 +00004650 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004651 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00004652 Src.ShuffleVec =
4653 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004654 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00004655 Src.WindowBase = -NumSrcElts;
4656 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004657 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00004658 Src.ShuffleVec =
4659 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004660 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004661 } else {
4662 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00004663 SDValue VEXTSrc1 =
4664 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004665 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004666 SDValue VEXTSrc2 =
4667 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004668 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004669 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4670
4671 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004672 VEXTSrc2,
4673 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00004674 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004675 }
4676 }
4677
Tim Northover7324e842014-07-24 15:39:55 +00004678 // Another possible incompatibility occurs from the vector element types. We
4679 // can fix this by bitcasting the source vectors to the same type we intend
4680 // for the shuffle.
4681 for (auto &Src : Sources) {
4682 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4683 if (SrcEltTy == SmallestEltTy)
4684 continue;
4685 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4686 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4687 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4688 Src.WindowBase *= Src.WindowScale;
4689 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004690
Tim Northover7324e842014-07-24 15:39:55 +00004691 // Final sanity check before we try to actually produce a shuffle.
4692 DEBUG(
4693 for (auto Src : Sources)
4694 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4695 );
4696
4697 // The stars all align, our next step is to produce the mask for the shuffle.
4698 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4699 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004700 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004701 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00004702 if (Entry.getOpcode() == ISD::UNDEF)
4703 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00004704
Tim Northover7324e842014-07-24 15:39:55 +00004705 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4706 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4707
4708 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4709 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4710 // segment.
4711 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4712 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4713 VT.getVectorElementType().getSizeInBits());
4714 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4715
4716 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4717 // starting at the appropriate offset.
4718 int *LaneMask = &Mask[i * ResMultiplier];
4719
4720 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4721 ExtractBase += NumElts * (Src - Sources.begin());
4722 for (int j = 0; j < LanesDefined; ++j)
4723 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00004724 }
4725
4726 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00004727 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4728 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004729
Tim Northover7324e842014-07-24 15:39:55 +00004730 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4731 for (unsigned i = 0; i < Sources.size(); ++i)
4732 ShuffleOps[i] = Sources[i].ShuffleVec;
4733
4734 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4735 ShuffleOps[1], &Mask[0]);
4736 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00004737}
4738
4739// check if an EXT instruction can handle the shuffle mask when the
4740// vector sources of the shuffle are the same.
4741static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4742 unsigned NumElts = VT.getVectorNumElements();
4743
4744 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4745 if (M[0] < 0)
4746 return false;
4747
4748 Imm = M[0];
4749
4750 // If this is a VEXT shuffle, the immediate value is the index of the first
4751 // element. The other shuffle indices must be the successive elements after
4752 // the first one.
4753 unsigned ExpectedElt = Imm;
4754 for (unsigned i = 1; i < NumElts; ++i) {
4755 // Increment the expected index. If it wraps around, just follow it
4756 // back to index zero and keep going.
4757 ++ExpectedElt;
4758 if (ExpectedElt == NumElts)
4759 ExpectedElt = 0;
4760
4761 if (M[i] < 0)
4762 continue; // ignore UNDEF indices
4763 if (ExpectedElt != static_cast<unsigned>(M[i]))
4764 return false;
4765 }
4766
4767 return true;
4768}
4769
4770// check if an EXT instruction can handle the shuffle mask when the
4771// vector sources of the shuffle are different.
4772static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4773 unsigned &Imm) {
4774 // Look for the first non-undef element.
4775 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4776 [](int Elt) {return Elt >= 0;});
4777
4778 // Benefit form APInt to handle overflow when calculating expected element.
4779 unsigned NumElts = VT.getVectorNumElements();
4780 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4781 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4782 // The following shuffle indices must be the successive elements after the
4783 // first real element.
4784 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4785 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4786 if (FirstWrongElt != M.end())
4787 return false;
4788
4789 // The index of an EXT is the first element if it is not UNDEF.
4790 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4791 // value of the first element. E.g.
4792 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4793 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4794 // ExpectedElt is the last mask index plus 1.
4795 Imm = ExpectedElt.getZExtValue();
4796
4797 // There are two difference cases requiring to reverse input vectors.
4798 // For example, for vector <4 x i32> we have the following cases,
4799 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
4800 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
4801 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
4802 // to reverse two input vectors.
4803 if (Imm < NumElts)
4804 ReverseEXT = true;
4805 else
4806 Imm -= NumElts;
4807
4808 return true;
4809}
4810
4811/// isREVMask - Check if a vector shuffle corresponds to a REV
4812/// instruction with the specified blocksize. (The order of the elements
4813/// within each block of the vector is reversed.)
4814static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4815 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4816 "Only possible block sizes for REV are: 16, 32, 64");
4817
4818 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4819 if (EltSz == 64)
4820 return false;
4821
4822 unsigned NumElts = VT.getVectorNumElements();
4823 unsigned BlockElts = M[0] + 1;
4824 // If the first shuffle index is UNDEF, be optimistic.
4825 if (M[0] < 0)
4826 BlockElts = BlockSize / EltSz;
4827
4828 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4829 return false;
4830
4831 for (unsigned i = 0; i < NumElts; ++i) {
4832 if (M[i] < 0)
4833 continue; // ignore UNDEF indices
4834 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4835 return false;
4836 }
4837
4838 return true;
4839}
4840
4841static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4842 unsigned NumElts = VT.getVectorNumElements();
4843 WhichResult = (M[0] == 0 ? 0 : 1);
4844 unsigned Idx = WhichResult * NumElts / 2;
4845 for (unsigned i = 0; i != NumElts; i += 2) {
4846 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4847 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4848 return false;
4849 Idx += 1;
4850 }
4851
4852 return true;
4853}
4854
4855static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4856 unsigned NumElts = VT.getVectorNumElements();
4857 WhichResult = (M[0] == 0 ? 0 : 1);
4858 for (unsigned i = 0; i != NumElts; ++i) {
4859 if (M[i] < 0)
4860 continue; // ignore UNDEF indices
4861 if ((unsigned)M[i] != 2 * i + WhichResult)
4862 return false;
4863 }
4864
4865 return true;
4866}
4867
4868static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4869 unsigned NumElts = VT.getVectorNumElements();
4870 WhichResult = (M[0] == 0 ? 0 : 1);
4871 for (unsigned i = 0; i < NumElts; i += 2) {
4872 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4873 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4874 return false;
4875 }
4876 return true;
4877}
4878
4879/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4880/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4881/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4882static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4883 unsigned NumElts = VT.getVectorNumElements();
4884 WhichResult = (M[0] == 0 ? 0 : 1);
4885 unsigned Idx = WhichResult * NumElts / 2;
4886 for (unsigned i = 0; i != NumElts; i += 2) {
4887 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4888 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4889 return false;
4890 Idx += 1;
4891 }
4892
4893 return true;
4894}
4895
4896/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4897/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4898/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4899static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4900 unsigned Half = VT.getVectorNumElements() / 2;
4901 WhichResult = (M[0] == 0 ? 0 : 1);
4902 for (unsigned j = 0; j != 2; ++j) {
4903 unsigned Idx = WhichResult;
4904 for (unsigned i = 0; i != Half; ++i) {
4905 int MIdx = M[i + j * Half];
4906 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4907 return false;
4908 Idx += 2;
4909 }
4910 }
4911
4912 return true;
4913}
4914
4915/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4916/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4917/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4918static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4919 unsigned NumElts = VT.getVectorNumElements();
4920 WhichResult = (M[0] == 0 ? 0 : 1);
4921 for (unsigned i = 0; i < NumElts; i += 2) {
4922 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4923 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4924 return false;
4925 }
4926 return true;
4927}
4928
4929static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4930 bool &DstIsLeft, int &Anomaly) {
4931 if (M.size() != static_cast<size_t>(NumInputElements))
4932 return false;
4933
4934 int NumLHSMatch = 0, NumRHSMatch = 0;
4935 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4936
4937 for (int i = 0; i < NumInputElements; ++i) {
4938 if (M[i] == -1) {
4939 ++NumLHSMatch;
4940 ++NumRHSMatch;
4941 continue;
4942 }
4943
4944 if (M[i] == i)
4945 ++NumLHSMatch;
4946 else
4947 LastLHSMismatch = i;
4948
4949 if (M[i] == i + NumInputElements)
4950 ++NumRHSMatch;
4951 else
4952 LastRHSMismatch = i;
4953 }
4954
4955 if (NumLHSMatch == NumInputElements - 1) {
4956 DstIsLeft = true;
4957 Anomaly = LastLHSMismatch;
4958 return true;
4959 } else if (NumRHSMatch == NumInputElements - 1) {
4960 DstIsLeft = false;
4961 Anomaly = LastRHSMismatch;
4962 return true;
4963 }
4964
4965 return false;
4966}
4967
4968static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4969 if (VT.getSizeInBits() != 128)
4970 return false;
4971
4972 unsigned NumElts = VT.getVectorNumElements();
4973
4974 for (int I = 0, E = NumElts / 2; I != E; I++) {
4975 if (Mask[I] != I)
4976 return false;
4977 }
4978
4979 int Offset = NumElts / 2;
4980 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4981 if (Mask[I] != I + SplitLHS * Offset)
4982 return false;
4983 }
4984
4985 return true;
4986}
4987
4988static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4989 SDLoc DL(Op);
4990 EVT VT = Op.getValueType();
4991 SDValue V0 = Op.getOperand(0);
4992 SDValue V1 = Op.getOperand(1);
4993 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4994
4995 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4996 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4997 return SDValue();
4998
4999 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5000
5001 if (!isConcatMask(Mask, VT, SplitV0))
5002 return SDValue();
5003
5004 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5005 VT.getVectorNumElements() / 2);
5006 if (SplitV0) {
5007 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005008 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005009 }
5010 if (V1.getValueType().getSizeInBits() == 128) {
5011 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005012 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005013 }
5014 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5015}
5016
5017/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5018/// the specified operations to build the shuffle.
5019static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5020 SDValue RHS, SelectionDAG &DAG,
5021 SDLoc dl) {
5022 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5023 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5024 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5025
5026 enum {
5027 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5028 OP_VREV,
5029 OP_VDUP0,
5030 OP_VDUP1,
5031 OP_VDUP2,
5032 OP_VDUP3,
5033 OP_VEXT1,
5034 OP_VEXT2,
5035 OP_VEXT3,
5036 OP_VUZPL, // VUZP, left result
5037 OP_VUZPR, // VUZP, right result
5038 OP_VZIPL, // VZIP, left result
5039 OP_VZIPR, // VZIP, right result
5040 OP_VTRNL, // VTRN, left result
5041 OP_VTRNR // VTRN, right result
5042 };
5043
5044 if (OpNum == OP_COPY) {
5045 if (LHSID == (1 * 9 + 2) * 9 + 3)
5046 return LHS;
5047 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5048 return RHS;
5049 }
5050
5051 SDValue OpLHS, OpRHS;
5052 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5053 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5054 EVT VT = OpLHS.getValueType();
5055
5056 switch (OpNum) {
5057 default:
5058 llvm_unreachable("Unknown shuffle opcode!");
5059 case OP_VREV:
5060 // VREV divides the vector in half and swaps within the half.
5061 if (VT.getVectorElementType() == MVT::i32 ||
5062 VT.getVectorElementType() == MVT::f32)
5063 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5064 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005065 if (VT.getVectorElementType() == MVT::i16 ||
5066 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005067 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5068 // vrev <4 x i8> -> REV16
5069 assert(VT.getVectorElementType() == MVT::i8);
5070 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5071 case OP_VDUP0:
5072 case OP_VDUP1:
5073 case OP_VDUP2:
5074 case OP_VDUP3: {
5075 EVT EltTy = VT.getVectorElementType();
5076 unsigned Opcode;
5077 if (EltTy == MVT::i8)
5078 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005079 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005080 Opcode = AArch64ISD::DUPLANE16;
5081 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5082 Opcode = AArch64ISD::DUPLANE32;
5083 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5084 Opcode = AArch64ISD::DUPLANE64;
5085 else
5086 llvm_unreachable("Invalid vector element type?");
5087
5088 if (VT.getSizeInBits() == 64)
5089 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005090 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005091 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5092 }
5093 case OP_VEXT1:
5094 case OP_VEXT2:
5095 case OP_VEXT3: {
5096 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5097 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005098 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005099 }
5100 case OP_VUZPL:
5101 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5102 OpRHS);
5103 case OP_VUZPR:
5104 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5105 OpRHS);
5106 case OP_VZIPL:
5107 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5108 OpRHS);
5109 case OP_VZIPR:
5110 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5111 OpRHS);
5112 case OP_VTRNL:
5113 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5114 OpRHS);
5115 case OP_VTRNR:
5116 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5117 OpRHS);
5118 }
5119}
5120
5121static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5122 SelectionDAG &DAG) {
5123 // Check to see if we can use the TBL instruction.
5124 SDValue V1 = Op.getOperand(0);
5125 SDValue V2 = Op.getOperand(1);
5126 SDLoc DL(Op);
5127
5128 EVT EltVT = Op.getValueType().getVectorElementType();
5129 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5130
5131 SmallVector<SDValue, 8> TBLMask;
5132 for (int Val : ShuffleMask) {
5133 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5134 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005135 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005136 }
5137 }
5138
5139 MVT IndexVT = MVT::v8i8;
5140 unsigned IndexLen = 8;
5141 if (Op.getValueType().getSizeInBits() == 128) {
5142 IndexVT = MVT::v16i8;
5143 IndexLen = 16;
5144 }
5145
5146 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5147 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5148
5149 SDValue Shuffle;
5150 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5151 if (IndexLen == 8)
5152 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5153 Shuffle = DAG.getNode(
5154 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005155 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005156 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5157 makeArrayRef(TBLMask.data(), IndexLen)));
5158 } else {
5159 if (IndexLen == 8) {
5160 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5161 Shuffle = DAG.getNode(
5162 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005163 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005164 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5165 makeArrayRef(TBLMask.data(), IndexLen)));
5166 } else {
5167 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5168 // cannot currently represent the register constraints on the input
5169 // table registers.
5170 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5171 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5172 // &TBLMask[0], IndexLen));
5173 Shuffle = DAG.getNode(
5174 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005175 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5176 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005177 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5178 makeArrayRef(TBLMask.data(), IndexLen)));
5179 }
5180 }
5181 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5182}
5183
5184static unsigned getDUPLANEOp(EVT EltType) {
5185 if (EltType == MVT::i8)
5186 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005187 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005188 return AArch64ISD::DUPLANE16;
5189 if (EltType == MVT::i32 || EltType == MVT::f32)
5190 return AArch64ISD::DUPLANE32;
5191 if (EltType == MVT::i64 || EltType == MVT::f64)
5192 return AArch64ISD::DUPLANE64;
5193
5194 llvm_unreachable("Invalid vector element type?");
5195}
5196
5197SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5198 SelectionDAG &DAG) const {
5199 SDLoc dl(Op);
5200 EVT VT = Op.getValueType();
5201
5202 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5203
5204 // Convert shuffles that are directly supported on NEON to target-specific
5205 // DAG nodes, instead of keeping them as shuffles and matching them again
5206 // during code selection. This is more efficient and avoids the possibility
5207 // of inconsistencies between legalization and selection.
5208 ArrayRef<int> ShuffleMask = SVN->getMask();
5209
5210 SDValue V1 = Op.getOperand(0);
5211 SDValue V2 = Op.getOperand(1);
5212
5213 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5214 V1.getValueType().getSimpleVT())) {
5215 int Lane = SVN->getSplatIndex();
5216 // If this is undef splat, generate it via "just" vdup, if possible.
5217 if (Lane == -1)
5218 Lane = 0;
5219
5220 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5221 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5222 V1.getOperand(0));
5223 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5224 // constant. If so, we can just reference the lane's definition directly.
5225 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5226 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5227 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5228
5229 // Otherwise, duplicate from the lane of the input vector.
5230 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5231
5232 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5233 // to make a vector of the same size as this SHUFFLE. We can ignore the
5234 // extract entirely, and canonicalise the concat using WidenVector.
5235 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5236 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5237 V1 = V1.getOperand(0);
5238 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5239 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5240 Lane -= Idx * VT.getVectorNumElements() / 2;
5241 V1 = WidenVector(V1.getOperand(Idx), DAG);
5242 } else if (VT.getSizeInBits() == 64)
5243 V1 = WidenVector(V1, DAG);
5244
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005245 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005246 }
5247
5248 if (isREVMask(ShuffleMask, VT, 64))
5249 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5250 if (isREVMask(ShuffleMask, VT, 32))
5251 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5252 if (isREVMask(ShuffleMask, VT, 16))
5253 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5254
5255 bool ReverseEXT = false;
5256 unsigned Imm;
5257 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5258 if (ReverseEXT)
5259 std::swap(V1, V2);
5260 Imm *= getExtFactor(V1);
5261 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005262 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005263 } else if (V2->getOpcode() == ISD::UNDEF &&
5264 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5265 Imm *= getExtFactor(V1);
5266 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005267 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005268 }
5269
5270 unsigned WhichResult;
5271 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5272 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5273 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5274 }
5275 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5276 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5277 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5278 }
5279 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5280 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5281 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5282 }
5283
5284 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5285 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5286 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5287 }
5288 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5289 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5290 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5291 }
5292 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5293 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5294 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5295 }
5296
5297 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5298 if (Concat.getNode())
5299 return Concat;
5300
5301 bool DstIsLeft;
5302 int Anomaly;
5303 int NumInputElements = V1.getValueType().getVectorNumElements();
5304 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5305 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005306 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005307
5308 SDValue SrcVec = V1;
5309 int SrcLane = ShuffleMask[Anomaly];
5310 if (SrcLane >= NumInputElements) {
5311 SrcVec = V2;
5312 SrcLane -= VT.getVectorNumElements();
5313 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005314 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005315
5316 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005317
5318 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005319 ScalarVT = MVT::i32;
5320
5321 return DAG.getNode(
5322 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5323 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5324 DstLaneV);
5325 }
5326
5327 // If the shuffle is not directly supported and it has 4 elements, use
5328 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5329 unsigned NumElts = VT.getVectorNumElements();
5330 if (NumElts == 4) {
5331 unsigned PFIndexes[4];
5332 for (unsigned i = 0; i != 4; ++i) {
5333 if (ShuffleMask[i] < 0)
5334 PFIndexes[i] = 8;
5335 else
5336 PFIndexes[i] = ShuffleMask[i];
5337 }
5338
5339 // Compute the index in the perfect shuffle table.
5340 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5341 PFIndexes[2] * 9 + PFIndexes[3];
5342 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5343 unsigned Cost = (PFEntry >> 30);
5344
5345 if (Cost <= 4)
5346 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5347 }
5348
5349 return GenerateTBL(Op, ShuffleMask, DAG);
5350}
5351
5352static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5353 APInt &UndefBits) {
5354 EVT VT = BVN->getValueType(0);
5355 APInt SplatBits, SplatUndef;
5356 unsigned SplatBitSize;
5357 bool HasAnyUndefs;
5358 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5359 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5360
5361 for (unsigned i = 0; i < NumSplats; ++i) {
5362 CnstBits <<= SplatBitSize;
5363 UndefBits <<= SplatBitSize;
5364 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5365 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5366 }
5367
5368 return true;
5369 }
5370
5371 return false;
5372}
5373
5374SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5375 SelectionDAG &DAG) const {
5376 BuildVectorSDNode *BVN =
5377 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5378 SDValue LHS = Op.getOperand(0);
5379 SDLoc dl(Op);
5380 EVT VT = Op.getValueType();
5381
5382 if (!BVN)
5383 return Op;
5384
5385 APInt CnstBits(VT.getSizeInBits(), 0);
5386 APInt UndefBits(VT.getSizeInBits(), 0);
5387 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5388 // We only have BIC vector immediate instruction, which is and-not.
5389 CnstBits = ~CnstBits;
5390
5391 // We make use of a little bit of goto ickiness in order to avoid having to
5392 // duplicate the immediate matching logic for the undef toggled case.
5393 bool SecondTry = false;
5394 AttemptModImm:
5395
5396 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5397 CnstBits = CnstBits.zextOrTrunc(64);
5398 uint64_t CnstVal = CnstBits.getZExtValue();
5399
5400 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5401 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5402 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5403 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005404 DAG.getConstant(CnstVal, dl, MVT::i32),
5405 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005406 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005407 }
5408
5409 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5410 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5411 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5412 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005413 DAG.getConstant(CnstVal, dl, MVT::i32),
5414 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005415 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005416 }
5417
5418 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5419 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5420 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5421 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005422 DAG.getConstant(CnstVal, dl, MVT::i32),
5423 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005424 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005425 }
5426
5427 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5428 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5429 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5430 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005431 DAG.getConstant(CnstVal, dl, MVT::i32),
5432 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005433 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005434 }
5435
5436 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5437 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5438 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5439 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005440 DAG.getConstant(CnstVal, dl, MVT::i32),
5441 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005442 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005443 }
5444
5445 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5446 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5447 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5448 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005449 DAG.getConstant(CnstVal, dl, MVT::i32),
5450 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005451 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005452 }
5453 }
5454
5455 if (SecondTry)
5456 goto FailedModImm;
5457 SecondTry = true;
5458 CnstBits = ~UndefBits;
5459 goto AttemptModImm;
5460 }
5461
5462// We can always fall back to a non-immediate AND.
5463FailedModImm:
5464 return Op;
5465}
5466
5467// Specialized code to quickly find if PotentialBVec is a BuildVector that
5468// consists of only the same constant int value, returned in reference arg
5469// ConstVal
5470static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5471 uint64_t &ConstVal) {
5472 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5473 if (!Bvec)
5474 return false;
5475 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5476 if (!FirstElt)
5477 return false;
5478 EVT VT = Bvec->getValueType(0);
5479 unsigned NumElts = VT.getVectorNumElements();
5480 for (unsigned i = 1; i < NumElts; ++i)
5481 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5482 return false;
5483 ConstVal = FirstElt->getZExtValue();
5484 return true;
5485}
5486
5487static unsigned getIntrinsicID(const SDNode *N) {
5488 unsigned Opcode = N->getOpcode();
5489 switch (Opcode) {
5490 default:
5491 return Intrinsic::not_intrinsic;
5492 case ISD::INTRINSIC_WO_CHAIN: {
5493 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5494 if (IID < Intrinsic::num_intrinsics)
5495 return IID;
5496 return Intrinsic::not_intrinsic;
5497 }
5498 }
5499}
5500
5501// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5502// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5503// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5504// Also, logical shift right -> sri, with the same structure.
5505static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5506 EVT VT = N->getValueType(0);
5507
5508 if (!VT.isVector())
5509 return SDValue();
5510
5511 SDLoc DL(N);
5512
5513 // Is the first op an AND?
5514 const SDValue And = N->getOperand(0);
5515 if (And.getOpcode() != ISD::AND)
5516 return SDValue();
5517
5518 // Is the second op an shl or lshr?
5519 SDValue Shift = N->getOperand(1);
5520 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5521 // or AArch64ISD::VLSHR vector, #shift
5522 unsigned ShiftOpc = Shift.getOpcode();
5523 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5524 return SDValue();
5525 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5526
5527 // Is the shift amount constant?
5528 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5529 if (!C2node)
5530 return SDValue();
5531
5532 // Is the and mask vector all constant?
5533 uint64_t C1;
5534 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5535 return SDValue();
5536
5537 // Is C1 == ~C2, taking into account how much one can shift elements of a
5538 // particular size?
5539 uint64_t C2 = C2node->getZExtValue();
5540 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5541 if (C2 > ElemSizeInBits)
5542 return SDValue();
5543 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5544 if ((C1 & ElemMask) != (~C2 & ElemMask))
5545 return SDValue();
5546
5547 SDValue X = And.getOperand(0);
5548 SDValue Y = Shift.getOperand(0);
5549
5550 unsigned Intrin =
5551 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5552 SDValue ResultSLI =
5553 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005554 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5555 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005556
5557 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5558 DEBUG(N->dump(&DAG));
5559 DEBUG(dbgs() << "into: \n");
5560 DEBUG(ResultSLI->dump(&DAG));
5561
5562 ++NumShiftInserts;
5563 return ResultSLI;
5564}
5565
5566SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5567 SelectionDAG &DAG) const {
5568 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5569 if (EnableAArch64SlrGeneration) {
5570 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5571 if (Res.getNode())
5572 return Res;
5573 }
5574
5575 BuildVectorSDNode *BVN =
5576 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5577 SDValue LHS = Op.getOperand(1);
5578 SDLoc dl(Op);
5579 EVT VT = Op.getValueType();
5580
5581 // OR commutes, so try swapping the operands.
5582 if (!BVN) {
5583 LHS = Op.getOperand(0);
5584 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5585 }
5586 if (!BVN)
5587 return Op;
5588
5589 APInt CnstBits(VT.getSizeInBits(), 0);
5590 APInt UndefBits(VT.getSizeInBits(), 0);
5591 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5592 // We make use of a little bit of goto ickiness in order to avoid having to
5593 // duplicate the immediate matching logic for the undef toggled case.
5594 bool SecondTry = false;
5595 AttemptModImm:
5596
5597 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5598 CnstBits = CnstBits.zextOrTrunc(64);
5599 uint64_t CnstVal = CnstBits.getZExtValue();
5600
5601 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5602 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5603 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5604 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005605 DAG.getConstant(CnstVal, dl, MVT::i32),
5606 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005607 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005608 }
5609
5610 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5611 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5612 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5613 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005614 DAG.getConstant(CnstVal, dl, MVT::i32),
5615 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005616 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005617 }
5618
5619 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5620 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5621 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5622 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005623 DAG.getConstant(CnstVal, dl, MVT::i32),
5624 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005625 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005626 }
5627
5628 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5629 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5630 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5631 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005632 DAG.getConstant(CnstVal, dl, MVT::i32),
5633 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005634 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005635 }
5636
5637 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5638 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5639 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5640 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005641 DAG.getConstant(CnstVal, dl, MVT::i32),
5642 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005643 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005644 }
5645
5646 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5647 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5648 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5649 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005650 DAG.getConstant(CnstVal, dl, MVT::i32),
5651 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005652 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005653 }
5654 }
5655
5656 if (SecondTry)
5657 goto FailedModImm;
5658 SecondTry = true;
5659 CnstBits = UndefBits;
5660 goto AttemptModImm;
5661 }
5662
5663// We can always fall back to a non-immediate OR.
5664FailedModImm:
5665 return Op;
5666}
5667
Kevin Qin4473c192014-07-07 02:45:40 +00005668// Normalize the operands of BUILD_VECTOR. The value of constant operands will
5669// be truncated to fit element width.
5670static SDValue NormalizeBuildVector(SDValue Op,
5671 SelectionDAG &DAG) {
5672 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005673 SDLoc dl(Op);
5674 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00005675 EVT EltTy= VT.getVectorElementType();
5676
5677 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5678 return Op;
5679
5680 SmallVector<SDValue, 16> Ops;
5681 for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5682 SDValue Lane = Op.getOperand(I);
5683 if (Lane.getOpcode() == ISD::Constant) {
5684 APInt LowBits(EltTy.getSizeInBits(),
5685 cast<ConstantSDNode>(Lane)->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005686 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00005687 }
5688 Ops.push_back(Lane);
5689 }
5690 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5691}
5692
5693SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5694 SelectionDAG &DAG) const {
5695 SDLoc dl(Op);
5696 EVT VT = Op.getValueType();
5697 Op = NormalizeBuildVector(Op, DAG);
5698 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00005699
5700 APInt CnstBits(VT.getSizeInBits(), 0);
5701 APInt UndefBits(VT.getSizeInBits(), 0);
5702 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5703 // We make use of a little bit of goto ickiness in order to avoid having to
5704 // duplicate the immediate matching logic for the undef toggled case.
5705 bool SecondTry = false;
5706 AttemptModImm:
5707
5708 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5709 CnstBits = CnstBits.zextOrTrunc(64);
5710 uint64_t CnstVal = CnstBits.getZExtValue();
5711
5712 // Certain magic vector constants (used to express things like NOT
5713 // and NEG) are passed through unmodified. This allows codegen patterns
5714 // for these operations to match. Special-purpose patterns will lower
5715 // these immediates to MOVIs if it proves necessary.
5716 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5717 return Op;
5718
5719 // The many faces of MOVI...
5720 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5721 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5722 if (VT.getSizeInBits() == 128) {
5723 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005724 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005725 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005726 }
5727
5728 // Support the V64 version via subregister insertion.
5729 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005730 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005731 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005732 }
5733
5734 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5735 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5736 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5737 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005738 DAG.getConstant(CnstVal, dl, MVT::i32),
5739 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005740 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005741 }
5742
5743 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5744 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5745 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5746 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005747 DAG.getConstant(CnstVal, dl, MVT::i32),
5748 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005749 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005750 }
5751
5752 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5753 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5754 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5755 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005756 DAG.getConstant(CnstVal, dl, MVT::i32),
5757 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005758 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005759 }
5760
5761 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5762 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5763 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5764 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005765 DAG.getConstant(CnstVal, dl, MVT::i32),
5766 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005767 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005768 }
5769
5770 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5771 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5772 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5773 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005774 DAG.getConstant(CnstVal, dl, MVT::i32),
5775 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005776 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005777 }
5778
5779 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5780 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5781 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5782 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005783 DAG.getConstant(CnstVal, dl, MVT::i32),
5784 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005785 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005786 }
5787
5788 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5789 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5790 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5791 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005792 DAG.getConstant(CnstVal, dl, MVT::i32),
5793 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005794 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005795 }
5796
5797 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5798 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5799 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5800 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005801 DAG.getConstant(CnstVal, dl, MVT::i32),
5802 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005803 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005804 }
5805
5806 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
5807 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
5808 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5809 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005810 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005811 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005812 }
5813
5814 // The few faces of FMOV...
5815 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
5816 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
5817 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5818 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005819 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005820 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005821 }
5822
5823 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
5824 VT.getSizeInBits() == 128) {
5825 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
5826 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005827 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005828 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005829 }
5830
5831 // The many faces of MVNI...
5832 CnstVal = ~CnstVal;
5833 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5834 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5835 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5836 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005837 DAG.getConstant(CnstVal, dl, MVT::i32),
5838 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005839 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005840 }
5841
5842 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5843 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5844 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5845 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005846 DAG.getConstant(CnstVal, dl, MVT::i32),
5847 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005848 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005849 }
5850
5851 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5852 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5853 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5854 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005855 DAG.getConstant(CnstVal, dl, MVT::i32),
5856 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005857 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005858 }
5859
5860 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5861 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5862 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5863 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005864 DAG.getConstant(CnstVal, dl, MVT::i32),
5865 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005866 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005867 }
5868
5869 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5870 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5871 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5872 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005873 DAG.getConstant(CnstVal, dl, MVT::i32),
5874 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005875 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005876 }
5877
5878 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5879 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5880 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5881 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005882 DAG.getConstant(CnstVal, dl, MVT::i32),
5883 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005884 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005885 }
5886
5887 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5888 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5889 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5890 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005891 DAG.getConstant(CnstVal, dl, MVT::i32),
5892 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005893 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005894 }
5895
5896 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5897 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5898 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5899 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005900 DAG.getConstant(CnstVal, dl, MVT::i32),
5901 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005902 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005903 }
5904 }
5905
5906 if (SecondTry)
5907 goto FailedModImm;
5908 SecondTry = true;
5909 CnstBits = UndefBits;
5910 goto AttemptModImm;
5911 }
5912FailedModImm:
5913
5914 // Scan through the operands to find some interesting properties we can
5915 // exploit:
5916 // 1) If only one value is used, we can use a DUP, or
5917 // 2) if only the low element is not undef, we can just insert that, or
5918 // 3) if only one constant value is used (w/ some non-constant lanes),
5919 // we can splat the constant value into the whole vector then fill
5920 // in the non-constant lanes.
5921 // 4) FIXME: If different constant values are used, but we can intelligently
5922 // select the values we'll be overwriting for the non-constant
5923 // lanes such that we can directly materialize the vector
5924 // some other way (MOVI, e.g.), we can be sneaky.
5925 unsigned NumElts = VT.getVectorNumElements();
5926 bool isOnlyLowElement = true;
5927 bool usesOnlyOneValue = true;
5928 bool usesOnlyOneConstantValue = true;
5929 bool isConstant = true;
5930 unsigned NumConstantLanes = 0;
5931 SDValue Value;
5932 SDValue ConstantValue;
5933 for (unsigned i = 0; i < NumElts; ++i) {
5934 SDValue V = Op.getOperand(i);
5935 if (V.getOpcode() == ISD::UNDEF)
5936 continue;
5937 if (i > 0)
5938 isOnlyLowElement = false;
5939 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5940 isConstant = false;
5941
5942 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5943 ++NumConstantLanes;
5944 if (!ConstantValue.getNode())
5945 ConstantValue = V;
5946 else if (ConstantValue != V)
5947 usesOnlyOneConstantValue = false;
5948 }
5949
5950 if (!Value.getNode())
5951 Value = V;
5952 else if (V != Value)
5953 usesOnlyOneValue = false;
5954 }
5955
5956 if (!Value.getNode())
5957 return DAG.getUNDEF(VT);
5958
5959 if (isOnlyLowElement)
5960 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5961
5962 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5963 // i32 and try again.
5964 if (usesOnlyOneValue) {
5965 if (!isConstant) {
5966 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5967 Value.getValueType() != VT)
5968 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
5969
5970 // This is actually a DUPLANExx operation, which keeps everything vectory.
5971
5972 // DUPLANE works on 128-bit vectors, widen it if necessary.
5973 SDValue Lane = Value.getOperand(1);
5974 Value = Value.getOperand(0);
5975 if (Value.getValueType().getSizeInBits() == 64)
5976 Value = WidenVector(Value, DAG);
5977
5978 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5979 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5980 }
5981
5982 if (VT.getVectorElementType().isFloatingPoint()) {
5983 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00005984 EVT EltTy = VT.getVectorElementType();
5985 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
5986 "Unsupported floating-point vector type");
5987 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005988 for (unsigned i = 0; i < NumElts; ++i)
5989 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5990 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5991 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5992 Val = LowerBUILD_VECTOR(Val, DAG);
5993 if (Val.getNode())
5994 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5995 }
5996 }
5997
5998 // If there was only one constant value used and for more than one lane,
5999 // start by splatting that value, then replace the non-constant lanes. This
6000 // is better than the default, which will perform a separate initialization
6001 // for each lane.
6002 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6003 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6004 // Now insert the non-constant lanes.
6005 for (unsigned i = 0; i < NumElts; ++i) {
6006 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006007 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006008 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6009 // Note that type legalization likely mucked about with the VT of the
6010 // source operand, so we may have to convert it here before inserting.
6011 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6012 }
6013 }
6014 return Val;
6015 }
6016
6017 // If all elements are constants and the case above didn't get hit, fall back
6018 // to the default expansion, which will generate a load from the constant
6019 // pool.
6020 if (isConstant)
6021 return SDValue();
6022
6023 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6024 if (NumElts >= 4) {
6025 SDValue shuffle = ReconstructShuffle(Op, DAG);
6026 if (shuffle != SDValue())
6027 return shuffle;
6028 }
6029
6030 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6031 // know the default expansion would otherwise fall back on something even
6032 // worse. For a vector with one or two non-undef values, that's
6033 // scalar_to_vector for the elements followed by a shuffle (provided the
6034 // shuffle is valid for the target) and materialization element by element
6035 // on the stack followed by a load for everything else.
6036 if (!isConstant && !usesOnlyOneValue) {
6037 SDValue Vec = DAG.getUNDEF(VT);
6038 SDValue Op0 = Op.getOperand(0);
6039 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6040 unsigned i = 0;
6041 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6042 // a) Avoid a RMW dependency on the full vector register, and
6043 // b) Allow the register coalescer to fold away the copy if the
6044 // value is already in an S or D register.
6045 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
6046 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6047 MachineSDNode *N =
6048 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006049 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006050 Vec = SDValue(N, 0);
6051 ++i;
6052 }
6053 for (; i < NumElts; ++i) {
6054 SDValue V = Op.getOperand(i);
6055 if (V.getOpcode() == ISD::UNDEF)
6056 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006057 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006058 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6059 }
6060 return Vec;
6061 }
6062
6063 // Just use the default expansion. We failed to find a better alternative.
6064 return SDValue();
6065}
6066
6067SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6068 SelectionDAG &DAG) const {
6069 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6070
Tim Northovere4b8e132014-07-15 10:00:26 +00006071 // Check for non-constant or out of range lane.
6072 EVT VT = Op.getOperand(0).getValueType();
6073 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6074 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006075 return SDValue();
6076
Tim Northover3b0846e2014-05-24 12:50:23 +00006077
6078 // Insertion/extraction are legal for V128 types.
6079 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006080 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6081 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006082 return Op;
6083
6084 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006085 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006086 return SDValue();
6087
6088 // For V64 types, we perform insertion by expanding the value
6089 // to a V128 type and perform the insertion on that.
6090 SDLoc DL(Op);
6091 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6092 EVT WideTy = WideVec.getValueType();
6093
6094 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6095 Op.getOperand(1), Op.getOperand(2));
6096 // Re-narrow the resultant vector.
6097 return NarrowVector(Node, DAG);
6098}
6099
6100SDValue
6101AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6102 SelectionDAG &DAG) const {
6103 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6104
Tim Northovere4b8e132014-07-15 10:00:26 +00006105 // Check for non-constant or out of range lane.
6106 EVT VT = Op.getOperand(0).getValueType();
6107 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6108 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006109 return SDValue();
6110
Tim Northover3b0846e2014-05-24 12:50:23 +00006111
6112 // Insertion/extraction are legal for V128 types.
6113 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006114 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6115 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006116 return Op;
6117
6118 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006119 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006120 return SDValue();
6121
6122 // For V64 types, we perform extraction by expanding the value
6123 // to a V128 type and perform the extraction on that.
6124 SDLoc DL(Op);
6125 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6126 EVT WideTy = WideVec.getValueType();
6127
6128 EVT ExtrTy = WideTy.getVectorElementType();
6129 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6130 ExtrTy = MVT::i32;
6131
6132 // For extractions, we just return the result directly.
6133 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6134 Op.getOperand(1));
6135}
6136
6137SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6138 SelectionDAG &DAG) const {
6139 EVT VT = Op.getOperand(0).getValueType();
6140 SDLoc dl(Op);
6141 // Just in case...
6142 if (!VT.isVector())
6143 return SDValue();
6144
6145 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6146 if (!Cst)
6147 return SDValue();
6148 unsigned Val = Cst->getZExtValue();
6149
6150 unsigned Size = Op.getValueType().getSizeInBits();
6151 if (Val == 0) {
6152 switch (Size) {
6153 case 8:
6154 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6155 Op.getOperand(0));
6156 case 16:
6157 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6158 Op.getOperand(0));
6159 case 32:
6160 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6161 Op.getOperand(0));
6162 case 64:
6163 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6164 Op.getOperand(0));
6165 default:
6166 llvm_unreachable("Unexpected vector type in extract_subvector!");
6167 }
6168 }
6169 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6170 // that directly.
6171 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6172 return Op;
6173
6174 return SDValue();
6175}
6176
6177bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6178 EVT VT) const {
6179 if (VT.getVectorNumElements() == 4 &&
6180 (VT.is128BitVector() || VT.is64BitVector())) {
6181 unsigned PFIndexes[4];
6182 for (unsigned i = 0; i != 4; ++i) {
6183 if (M[i] < 0)
6184 PFIndexes[i] = 8;
6185 else
6186 PFIndexes[i] = M[i];
6187 }
6188
6189 // Compute the index in the perfect shuffle table.
6190 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6191 PFIndexes[2] * 9 + PFIndexes[3];
6192 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6193 unsigned Cost = (PFEntry >> 30);
6194
6195 if (Cost <= 4)
6196 return true;
6197 }
6198
6199 bool DummyBool;
6200 int DummyInt;
6201 unsigned DummyUnsigned;
6202
6203 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6204 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6205 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6206 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6207 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6208 isZIPMask(M, VT, DummyUnsigned) ||
6209 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6210 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6211 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6212 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6213 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6214}
6215
6216/// getVShiftImm - Check if this is a valid build_vector for the immediate
6217/// operand of a vector shift operation, where all the elements of the
6218/// build_vector must have the same constant integer value.
6219static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6220 // Ignore bit_converts.
6221 while (Op.getOpcode() == ISD::BITCAST)
6222 Op = Op.getOperand(0);
6223 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6224 APInt SplatBits, SplatUndef;
6225 unsigned SplatBitSize;
6226 bool HasAnyUndefs;
6227 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6228 HasAnyUndefs, ElementBits) ||
6229 SplatBitSize > ElementBits)
6230 return false;
6231 Cnt = SplatBits.getSExtValue();
6232 return true;
6233}
6234
6235/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6236/// operand of a vector shift left operation. That value must be in the range:
6237/// 0 <= Value < ElementBits for a left shift; or
6238/// 0 <= Value <= ElementBits for a long left shift.
6239static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6240 assert(VT.isVector() && "vector shift count is not a vector type");
6241 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6242 if (!getVShiftImm(Op, ElementBits, Cnt))
6243 return false;
6244 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6245}
6246
6247/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6248/// operand of a vector shift right operation. For a shift opcode, the value
6249/// is positive, but for an intrinsic the value count must be negative. The
6250/// absolute value must be in the range:
6251/// 1 <= |Value| <= ElementBits for a right shift; or
6252/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6253static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6254 int64_t &Cnt) {
6255 assert(VT.isVector() && "vector shift count is not a vector type");
6256 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6257 if (!getVShiftImm(Op, ElementBits, Cnt))
6258 return false;
6259 if (isIntrinsic)
6260 Cnt = -Cnt;
6261 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6262}
6263
6264SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6265 SelectionDAG &DAG) const {
6266 EVT VT = Op.getValueType();
6267 SDLoc DL(Op);
6268 int64_t Cnt;
6269
6270 if (!Op.getOperand(1).getValueType().isVector())
6271 return Op;
6272 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6273
6274 switch (Op.getOpcode()) {
6275 default:
6276 llvm_unreachable("unexpected shift opcode");
6277
6278 case ISD::SHL:
6279 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006280 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6281 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006282 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006283 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6284 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006285 Op.getOperand(0), Op.getOperand(1));
6286 case ISD::SRA:
6287 case ISD::SRL:
6288 // Right shift immediate
6289 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
6290 Cnt < EltSize) {
6291 unsigned Opc =
6292 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006293 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6294 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006295 }
6296
6297 // Right shift register. Note, there is not a shift right register
6298 // instruction, but the shift left register instruction takes a signed
6299 // value, where negative numbers specify a right shift.
6300 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6301 : Intrinsic::aarch64_neon_ushl;
6302 // negate the shift amount
6303 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6304 SDValue NegShiftLeft =
6305 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006306 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6307 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006308 return NegShiftLeft;
6309 }
6310
6311 return SDValue();
6312}
6313
6314static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6315 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6316 SDLoc dl, SelectionDAG &DAG) {
6317 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006318 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6319 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006320
6321 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6322 APInt CnstBits(VT.getSizeInBits(), 0);
6323 APInt UndefBits(VT.getSizeInBits(), 0);
6324 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6325 bool IsZero = IsCnst && (CnstBits == 0);
6326
6327 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6328 switch (CC) {
6329 default:
6330 return SDValue();
6331 case AArch64CC::NE: {
6332 SDValue Fcmeq;
6333 if (IsZero)
6334 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6335 else
6336 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6337 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6338 }
6339 case AArch64CC::EQ:
6340 if (IsZero)
6341 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6342 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6343 case AArch64CC::GE:
6344 if (IsZero)
6345 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6346 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6347 case AArch64CC::GT:
6348 if (IsZero)
6349 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6350 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6351 case AArch64CC::LS:
6352 if (IsZero)
6353 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6354 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6355 case AArch64CC::LT:
6356 if (!NoNans)
6357 return SDValue();
6358 // If we ignore NaNs then we can use to the MI implementation.
6359 // Fallthrough.
6360 case AArch64CC::MI:
6361 if (IsZero)
6362 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6363 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6364 }
6365 }
6366
6367 switch (CC) {
6368 default:
6369 return SDValue();
6370 case AArch64CC::NE: {
6371 SDValue Cmeq;
6372 if (IsZero)
6373 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6374 else
6375 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6376 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6377 }
6378 case AArch64CC::EQ:
6379 if (IsZero)
6380 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6381 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6382 case AArch64CC::GE:
6383 if (IsZero)
6384 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6385 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6386 case AArch64CC::GT:
6387 if (IsZero)
6388 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6389 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6390 case AArch64CC::LE:
6391 if (IsZero)
6392 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6393 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6394 case AArch64CC::LS:
6395 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6396 case AArch64CC::LO:
6397 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6398 case AArch64CC::LT:
6399 if (IsZero)
6400 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6401 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6402 case AArch64CC::HI:
6403 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6404 case AArch64CC::HS:
6405 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6406 }
6407}
6408
6409SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6410 SelectionDAG &DAG) const {
6411 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6412 SDValue LHS = Op.getOperand(0);
6413 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006414 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006415 SDLoc dl(Op);
6416
6417 if (LHS.getValueType().getVectorElementType().isInteger()) {
6418 assert(LHS.getValueType() == RHS.getValueType());
6419 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006420 SDValue Cmp =
6421 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6422 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006423 }
6424
6425 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6426 LHS.getValueType().getVectorElementType() == MVT::f64);
6427
6428 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6429 // clean. Some of them require two branches to implement.
6430 AArch64CC::CondCode CC1, CC2;
6431 bool ShouldInvert;
6432 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6433
6434 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6435 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006436 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006437 if (!Cmp.getNode())
6438 return SDValue();
6439
6440 if (CC2 != AArch64CC::AL) {
6441 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006442 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006443 if (!Cmp2.getNode())
6444 return SDValue();
6445
Tim Northover45aa89c2015-02-08 00:50:47 +00006446 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006447 }
6448
Tim Northover45aa89c2015-02-08 00:50:47 +00006449 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6450
Tim Northover3b0846e2014-05-24 12:50:23 +00006451 if (ShouldInvert)
6452 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6453
6454 return Cmp;
6455}
6456
6457/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6458/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6459/// specified in the intrinsic calls.
6460bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6461 const CallInst &I,
6462 unsigned Intrinsic) const {
6463 switch (Intrinsic) {
6464 case Intrinsic::aarch64_neon_ld2:
6465 case Intrinsic::aarch64_neon_ld3:
6466 case Intrinsic::aarch64_neon_ld4:
6467 case Intrinsic::aarch64_neon_ld1x2:
6468 case Intrinsic::aarch64_neon_ld1x3:
6469 case Intrinsic::aarch64_neon_ld1x4:
6470 case Intrinsic::aarch64_neon_ld2lane:
6471 case Intrinsic::aarch64_neon_ld3lane:
6472 case Intrinsic::aarch64_neon_ld4lane:
6473 case Intrinsic::aarch64_neon_ld2r:
6474 case Intrinsic::aarch64_neon_ld3r:
6475 case Intrinsic::aarch64_neon_ld4r: {
6476 Info.opc = ISD::INTRINSIC_W_CHAIN;
6477 // Conservatively set memVT to the entire set of vectors loaded.
6478 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
6479 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6480 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6481 Info.offset = 0;
6482 Info.align = 0;
6483 Info.vol = false; // volatile loads with NEON intrinsics not supported
6484 Info.readMem = true;
6485 Info.writeMem = false;
6486 return true;
6487 }
6488 case Intrinsic::aarch64_neon_st2:
6489 case Intrinsic::aarch64_neon_st3:
6490 case Intrinsic::aarch64_neon_st4:
6491 case Intrinsic::aarch64_neon_st1x2:
6492 case Intrinsic::aarch64_neon_st1x3:
6493 case Intrinsic::aarch64_neon_st1x4:
6494 case Intrinsic::aarch64_neon_st2lane:
6495 case Intrinsic::aarch64_neon_st3lane:
6496 case Intrinsic::aarch64_neon_st4lane: {
6497 Info.opc = ISD::INTRINSIC_VOID;
6498 // Conservatively set memVT to the entire set of vectors stored.
6499 unsigned NumElts = 0;
6500 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6501 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6502 if (!ArgTy->isVectorTy())
6503 break;
6504 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
6505 }
6506 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6507 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6508 Info.offset = 0;
6509 Info.align = 0;
6510 Info.vol = false; // volatile stores with NEON intrinsics not supported
6511 Info.readMem = false;
6512 Info.writeMem = true;
6513 return true;
6514 }
6515 case Intrinsic::aarch64_ldaxr:
6516 case Intrinsic::aarch64_ldxr: {
6517 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6518 Info.opc = ISD::INTRINSIC_W_CHAIN;
6519 Info.memVT = MVT::getVT(PtrTy->getElementType());
6520 Info.ptrVal = I.getArgOperand(0);
6521 Info.offset = 0;
6522 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6523 Info.vol = true;
6524 Info.readMem = true;
6525 Info.writeMem = false;
6526 return true;
6527 }
6528 case Intrinsic::aarch64_stlxr:
6529 case Intrinsic::aarch64_stxr: {
6530 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6531 Info.opc = ISD::INTRINSIC_W_CHAIN;
6532 Info.memVT = MVT::getVT(PtrTy->getElementType());
6533 Info.ptrVal = I.getArgOperand(1);
6534 Info.offset = 0;
6535 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6536 Info.vol = true;
6537 Info.readMem = false;
6538 Info.writeMem = true;
6539 return true;
6540 }
6541 case Intrinsic::aarch64_ldaxp:
6542 case Intrinsic::aarch64_ldxp: {
6543 Info.opc = ISD::INTRINSIC_W_CHAIN;
6544 Info.memVT = MVT::i128;
6545 Info.ptrVal = I.getArgOperand(0);
6546 Info.offset = 0;
6547 Info.align = 16;
6548 Info.vol = true;
6549 Info.readMem = true;
6550 Info.writeMem = false;
6551 return true;
6552 }
6553 case Intrinsic::aarch64_stlxp:
6554 case Intrinsic::aarch64_stxp: {
6555 Info.opc = ISD::INTRINSIC_W_CHAIN;
6556 Info.memVT = MVT::i128;
6557 Info.ptrVal = I.getArgOperand(2);
6558 Info.offset = 0;
6559 Info.align = 16;
6560 Info.vol = true;
6561 Info.readMem = false;
6562 Info.writeMem = true;
6563 return true;
6564 }
6565 default:
6566 break;
6567 }
6568
6569 return false;
6570}
6571
6572// Truncations from 64-bit GPR to 32-bit GPR is free.
6573bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6574 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6575 return false;
6576 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6577 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006578 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006579}
6580bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006581 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006582 return false;
6583 unsigned NumBits1 = VT1.getSizeInBits();
6584 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006585 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006586}
6587
Chad Rosier54390052015-02-23 19:15:16 +00006588/// Check if it is profitable to hoist instruction in then/else to if.
6589/// Not profitable if I and it's user can form a FMA instruction
6590/// because we prefer FMSUB/FMADD.
6591bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6592 if (I->getOpcode() != Instruction::FMul)
6593 return true;
6594
6595 if (I->getNumUses() != 1)
6596 return true;
6597
6598 Instruction *User = I->user_back();
6599
6600 if (User &&
6601 !(User->getOpcode() == Instruction::FSub ||
6602 User->getOpcode() == Instruction::FAdd))
6603 return true;
6604
6605 const TargetOptions &Options = getTargetMachine().Options;
6606 EVT VT = getValueType(User->getOperand(0)->getType());
6607
6608 if (isFMAFasterThanFMulAndFAdd(VT) &&
6609 isOperationLegalOrCustom(ISD::FMA, VT) &&
6610 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6611 return false;
6612
6613 return true;
6614}
6615
Tim Northover3b0846e2014-05-24 12:50:23 +00006616// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6617// 64-bit GPR.
6618bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6619 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6620 return false;
6621 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6622 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006623 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006624}
6625bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006626 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006627 return false;
6628 unsigned NumBits1 = VT1.getSizeInBits();
6629 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006630 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006631}
6632
6633bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6634 EVT VT1 = Val.getValueType();
6635 if (isZExtFree(VT1, VT2)) {
6636 return true;
6637 }
6638
6639 if (Val.getOpcode() != ISD::LOAD)
6640 return false;
6641
6642 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00006643 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6644 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6645 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00006646}
6647
Quentin Colombet6843ac42015-03-31 20:52:32 +00006648bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6649 if (isa<FPExtInst>(Ext))
6650 return false;
6651
6652 // Vector types are next free.
6653 if (Ext->getType()->isVectorTy())
6654 return false;
6655
6656 for (const Use &U : Ext->uses()) {
6657 // The extension is free if we can fold it with a left shift in an
6658 // addressing mode or an arithmetic operation: add, sub, and cmp.
6659
6660 // Is there a shift?
6661 const Instruction *Instr = cast<Instruction>(U.getUser());
6662
6663 // Is this a constant shift?
6664 switch (Instr->getOpcode()) {
6665 case Instruction::Shl:
6666 if (!isa<ConstantInt>(Instr->getOperand(1)))
6667 return false;
6668 break;
6669 case Instruction::GetElementPtr: {
6670 gep_type_iterator GTI = gep_type_begin(Instr);
6671 std::advance(GTI, U.getOperandNo());
6672 Type *IdxTy = *GTI;
6673 // This extension will end up with a shift because of the scaling factor.
6674 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6675 // Get the shift amount based on the scaling factor:
6676 // log2(sizeof(IdxTy)) - log2(8).
6677 uint64_t ShiftAmt =
6678 countTrailingZeros(getDataLayout()->getTypeStoreSizeInBits(IdxTy)) - 3;
6679 // Is the constant foldable in the shift of the addressing mode?
6680 // I.e., shift amount is between 1 and 4 inclusive.
6681 if (ShiftAmt == 0 || ShiftAmt > 4)
6682 return false;
6683 break;
6684 }
6685 case Instruction::Trunc:
6686 // Check if this is a noop.
6687 // trunc(sext ty1 to ty2) to ty1.
6688 if (Instr->getType() == Ext->getOperand(0)->getType())
6689 continue;
6690 // FALL THROUGH.
6691 default:
6692 return false;
6693 }
6694
6695 // At this point we can use the bfm family, so this extension is free
6696 // for that use.
6697 }
6698 return true;
6699}
6700
Tim Northover3b0846e2014-05-24 12:50:23 +00006701bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6702 unsigned &RequiredAligment) const {
6703 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6704 return false;
6705 // Cyclone supports unaligned accesses.
6706 RequiredAligment = 0;
6707 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6708 return NumBits == 32 || NumBits == 64;
6709}
6710
6711bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6712 unsigned &RequiredAligment) const {
6713 if (!LoadedType.isSimple() ||
6714 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6715 return false;
6716 // Cyclone supports unaligned accesses.
6717 RequiredAligment = 0;
6718 unsigned NumBits = LoadedType.getSizeInBits();
6719 return NumBits == 32 || NumBits == 64;
6720}
6721
6722static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6723 unsigned AlignCheck) {
6724 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6725 (DstAlign == 0 || DstAlign % AlignCheck == 0));
6726}
6727
6728EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6729 unsigned SrcAlign, bool IsMemset,
6730 bool ZeroMemset,
6731 bool MemcpyStrSrc,
6732 MachineFunction &MF) const {
6733 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6734 // instruction to materialize the v2i64 zero and one store (with restrictive
6735 // addressing mode). Just do two i64 store of zero-registers.
6736 bool Fast;
6737 const Function *F = MF.getFunction();
6738 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00006739 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00006740 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00006741 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00006742 return MVT::f128;
6743
Lang Hames90333852015-04-09 03:40:33 +00006744 if (Size >= 8 &&
6745 (memOpAlign(SrcAlign, DstAlign, 8) ||
6746 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
6747 return MVT::i64;
6748
6749 if (Size >= 4 &&
6750 (memOpAlign(SrcAlign, DstAlign, 4) ||
6751 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00006752 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00006753
6754 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00006755}
6756
6757// 12-bit optionally shifted immediates are legal for adds.
6758bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6759 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6760 return true;
6761 return false;
6762}
6763
6764// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6765// immediates is the same as for an add or a sub.
6766bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6767 if (Immed < 0)
6768 Immed *= -1;
6769 return isLegalAddImmediate(Immed);
6770}
6771
6772/// isLegalAddressingMode - Return true if the addressing mode represented
6773/// by AM is legal for this target, for a load/store of the specified type.
6774bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6775 Type *Ty) const {
6776 // AArch64 has five basic addressing modes:
6777 // reg
6778 // reg + 9-bit signed offset
6779 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
6780 // reg1 + reg2
6781 // reg + SIZE_IN_BYTES * reg
6782
6783 // No global is ever allowed as a base.
6784 if (AM.BaseGV)
6785 return false;
6786
6787 // No reg+reg+imm addressing.
6788 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6789 return false;
6790
6791 // check reg + imm case:
6792 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6793 uint64_t NumBytes = 0;
6794 if (Ty->isSized()) {
6795 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6796 NumBytes = NumBits / 8;
6797 if (!isPowerOf2_64(NumBits))
6798 NumBytes = 0;
6799 }
6800
6801 if (!AM.Scale) {
6802 int64_t Offset = AM.BaseOffs;
6803
6804 // 9-bit signed offset
6805 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6806 return true;
6807
6808 // 12-bit unsigned offset
6809 unsigned shift = Log2_64(NumBytes);
6810 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6811 // Must be a multiple of NumBytes (NumBytes is a power of 2)
6812 (Offset >> shift) << shift == Offset)
6813 return true;
6814 return false;
6815 }
6816
6817 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6818
6819 if (!AM.Scale || AM.Scale == 1 ||
6820 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6821 return true;
6822 return false;
6823}
6824
6825int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6826 Type *Ty) const {
6827 // Scaling factors are not free at all.
6828 // Operands | Rt Latency
6829 // -------------------------------------------
6830 // Rt, [Xn, Xm] | 4
6831 // -------------------------------------------
6832 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6833 // Rt, [Xn, Wm, <extend> #imm] |
6834 if (isLegalAddressingMode(AM, Ty))
6835 // Scale represents reg2 * scale, thus account for 1 if
6836 // it is not equal to 0 or 1.
6837 return AM.Scale != 0 && AM.Scale != 1;
6838 return -1;
6839}
6840
6841bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6842 VT = VT.getScalarType();
6843
6844 if (!VT.isSimple())
6845 return false;
6846
6847 switch (VT.getSimpleVT().SimpleTy) {
6848 case MVT::f32:
6849 case MVT::f64:
6850 return true;
6851 default:
6852 break;
6853 }
6854
6855 return false;
6856}
6857
6858const MCPhysReg *
6859AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6860 // LR is a callee-save register, but we must treat it as clobbered by any call
6861 // site. Hence we include LR in the scratch registers, which are in turn added
6862 // as implicit-defs for stackmaps and patchpoints.
6863 static const MCPhysReg ScratchRegs[] = {
6864 AArch64::X16, AArch64::X17, AArch64::LR, 0
6865 };
6866 return ScratchRegs;
6867}
6868
6869bool
6870AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6871 EVT VT = N->getValueType(0);
6872 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6873 // it with shift to let it be lowered to UBFX.
6874 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6875 isa<ConstantSDNode>(N->getOperand(1))) {
6876 uint64_t TruncMask = N->getConstantOperandVal(1);
6877 if (isMask_64(TruncMask) &&
6878 N->getOperand(0).getOpcode() == ISD::SRL &&
6879 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6880 return false;
6881 }
6882 return true;
6883}
6884
6885bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6886 Type *Ty) const {
6887 assert(Ty->isIntegerTy());
6888
6889 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6890 if (BitSize == 0)
6891 return false;
6892
6893 int64_t Val = Imm.getSExtValue();
6894 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
6895 return true;
6896
6897 if ((int64_t)Val < 0)
6898 Val = ~Val;
6899 if (BitSize == 32)
6900 Val &= (1LL << 32) - 1;
6901
6902 unsigned LZ = countLeadingZeros((uint64_t)Val);
6903 unsigned Shift = (63 - LZ) / 16;
6904 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00006905 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00006906}
6907
6908// Generate SUBS and CSEL for integer abs.
6909static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6910 EVT VT = N->getValueType(0);
6911
6912 SDValue N0 = N->getOperand(0);
6913 SDValue N1 = N->getOperand(1);
6914 SDLoc DL(N);
6915
6916 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6917 // and change it to SUB and CSEL.
6918 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6919 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6920 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6921 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6922 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006923 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00006924 N0.getOperand(0));
6925 // Generate SUBS & CSEL.
6926 SDValue Cmp =
6927 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006928 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00006929 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006930 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006931 SDValue(Cmp.getNode(), 1));
6932 }
6933 return SDValue();
6934}
6935
6936// performXorCombine - Attempts to handle integer ABS.
6937static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6938 TargetLowering::DAGCombinerInfo &DCI,
6939 const AArch64Subtarget *Subtarget) {
6940 if (DCI.isBeforeLegalizeOps())
6941 return SDValue();
6942
6943 return performIntegerAbsCombine(N, DAG);
6944}
6945
Chad Rosier17020f92014-07-23 14:57:52 +00006946SDValue
6947AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6948 SelectionDAG &DAG,
6949 std::vector<SDNode *> *Created) const {
6950 // fold (sdiv X, pow2)
6951 EVT VT = N->getValueType(0);
6952 if ((VT != MVT::i32 && VT != MVT::i64) ||
6953 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
6954 return SDValue();
6955
6956 SDLoc DL(N);
6957 SDValue N0 = N->getOperand(0);
6958 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006959 SDValue Zero = DAG.getConstant(0, DL, VT);
6960 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00006961
6962 // Add (N0 < 0) ? Pow2 - 1 : 0;
6963 SDValue CCVal;
6964 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
6965 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6966 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
6967
6968 if (Created) {
6969 Created->push_back(Cmp.getNode());
6970 Created->push_back(Add.getNode());
6971 Created->push_back(CSel.getNode());
6972 }
6973
6974 // Divide by pow2.
6975 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006976 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00006977
6978 // If we're dividing by a positive value, we're done. Otherwise, we must
6979 // negate the result.
6980 if (Divisor.isNonNegative())
6981 return SRA;
6982
6983 if (Created)
6984 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006985 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00006986}
6987
Tim Northover3b0846e2014-05-24 12:50:23 +00006988static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6989 TargetLowering::DAGCombinerInfo &DCI,
6990 const AArch64Subtarget *Subtarget) {
6991 if (DCI.isBeforeLegalizeOps())
6992 return SDValue();
6993
6994 // Multiplication of a power of two plus/minus one can be done more
6995 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6996 // future CPUs have a cheaper MADD instruction, this may need to be
6997 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6998 // 64-bit is 5 cycles, so this is always a win.
6999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7000 APInt Value = C->getAPIntValue();
7001 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007002 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007003 if (Value.isNonNegative()) {
7004 // (mul x, 2^N + 1) => (add (shl x, N), x)
7005 APInt VM1 = Value - 1;
7006 if (VM1.isPowerOf2()) {
7007 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007008 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7009 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7010 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007011 N->getOperand(0));
7012 }
7013 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7014 APInt VP1 = Value + 1;
7015 if (VP1.isPowerOf2()) {
7016 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007017 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7018 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7019 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007020 N->getOperand(0));
7021 }
7022 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007023 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7024 APInt VNP1 = -Value + 1;
7025 if (VNP1.isPowerOf2()) {
7026 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007027 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7028 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7029 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007030 ShiftedVal);
7031 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007032 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7033 APInt VNM1 = -Value - 1;
7034 if (VNM1.isPowerOf2()) {
7035 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007036 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7037 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007038 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007039 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7040 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007041 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007042 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007043 }
7044 return SDValue();
7045}
7046
Jim Grosbachf7502c42014-07-18 00:40:52 +00007047static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7048 SelectionDAG &DAG) {
7049 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7050 // optimize away operation when it's from a constant.
7051 //
7052 // The general transformation is:
7053 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7054 // AND(VECTOR_CMP(x,y), constant2)
7055 // constant2 = UNARYOP(constant)
7056
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007057 // Early exit if this isn't a vector operation, the operand of the
7058 // unary operation isn't a bitwise AND, or if the sizes of the operations
7059 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007060 EVT VT = N->getValueType(0);
7061 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007062 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7063 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007064 return SDValue();
7065
Jim Grosbach724e4382014-07-23 20:41:43 +00007066 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007067 // make the transformation for non-constant splats as well, but it's unclear
7068 // that would be a benefit as it would not eliminate any operations, just
7069 // perform one more step in scalar code before moving to the vector unit.
7070 if (BuildVectorSDNode *BV =
7071 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007072 // Bail out if the vector isn't a constant.
7073 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007074 return SDValue();
7075
7076 // Everything checks out. Build up the new and improved node.
7077 SDLoc DL(N);
7078 EVT IntVT = BV->getValueType(0);
7079 // Create a new constant of the appropriate type for the transformed
7080 // DAG.
7081 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7082 // The AND node needs bitcasts to/from an integer vector type around it.
7083 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7084 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7085 N->getOperand(0)->getOperand(0), MaskConst);
7086 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7087 return Res;
7088 }
7089
7090 return SDValue();
7091}
7092
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007093static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7094 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007095 // First try to optimize away the conversion when it's conditionally from
7096 // a constant. Vectors only.
7097 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
7098 if (Res != SDValue())
7099 return Res;
7100
Tim Northover3b0846e2014-05-24 12:50:23 +00007101 EVT VT = N->getValueType(0);
7102 if (VT != MVT::f32 && VT != MVT::f64)
7103 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007104
Tim Northover3b0846e2014-05-24 12:50:23 +00007105 // Only optimize when the source and destination types have the same width.
7106 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7107 return SDValue();
7108
7109 // If the result of an integer load is only used by an integer-to-float
7110 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7111 // This eliminates an "integer-to-vector-move UOP and improve throughput.
7112 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007113 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007114 // Do not change the width of a volatile load.
7115 !cast<LoadSDNode>(N0)->isVolatile()) {
7116 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7117 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7118 LN0->getPointerInfo(), LN0->isVolatile(),
7119 LN0->isNonTemporal(), LN0->isInvariant(),
7120 LN0->getAlignment());
7121
7122 // Make sure successors of the original load stay after it by updating them
7123 // to use the new Chain.
7124 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7125
7126 unsigned Opcode =
7127 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7128 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7129 }
7130
7131 return SDValue();
7132}
7133
7134/// An EXTR instruction is made up of two shifts, ORed together. This helper
7135/// searches for and classifies those shifts.
7136static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7137 bool &FromHi) {
7138 if (N.getOpcode() == ISD::SHL)
7139 FromHi = false;
7140 else if (N.getOpcode() == ISD::SRL)
7141 FromHi = true;
7142 else
7143 return false;
7144
7145 if (!isa<ConstantSDNode>(N.getOperand(1)))
7146 return false;
7147
7148 ShiftAmount = N->getConstantOperandVal(1);
7149 Src = N->getOperand(0);
7150 return true;
7151}
7152
7153/// EXTR instruction extracts a contiguous chunk of bits from two existing
7154/// registers viewed as a high/low pair. This function looks for the pattern:
7155/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7156/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7157/// independent.
7158static SDValue tryCombineToEXTR(SDNode *N,
7159 TargetLowering::DAGCombinerInfo &DCI) {
7160 SelectionDAG &DAG = DCI.DAG;
7161 SDLoc DL(N);
7162 EVT VT = N->getValueType(0);
7163
7164 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7165
7166 if (VT != MVT::i32 && VT != MVT::i64)
7167 return SDValue();
7168
7169 SDValue LHS;
7170 uint32_t ShiftLHS = 0;
7171 bool LHSFromHi = 0;
7172 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7173 return SDValue();
7174
7175 SDValue RHS;
7176 uint32_t ShiftRHS = 0;
7177 bool RHSFromHi = 0;
7178 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7179 return SDValue();
7180
7181 // If they're both trying to come from the high part of the register, they're
7182 // not really an EXTR.
7183 if (LHSFromHi == RHSFromHi)
7184 return SDValue();
7185
7186 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7187 return SDValue();
7188
7189 if (LHSFromHi) {
7190 std::swap(LHS, RHS);
7191 std::swap(ShiftLHS, ShiftRHS);
7192 }
7193
7194 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007195 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007196}
7197
7198static SDValue tryCombineToBSL(SDNode *N,
7199 TargetLowering::DAGCombinerInfo &DCI) {
7200 EVT VT = N->getValueType(0);
7201 SelectionDAG &DAG = DCI.DAG;
7202 SDLoc DL(N);
7203
7204 if (!VT.isVector())
7205 return SDValue();
7206
7207 SDValue N0 = N->getOperand(0);
7208 if (N0.getOpcode() != ISD::AND)
7209 return SDValue();
7210
7211 SDValue N1 = N->getOperand(1);
7212 if (N1.getOpcode() != ISD::AND)
7213 return SDValue();
7214
7215 // We only have to look for constant vectors here since the general, variable
7216 // case can be handled in TableGen.
7217 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7218 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7219 for (int i = 1; i >= 0; --i)
7220 for (int j = 1; j >= 0; --j) {
7221 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7222 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7223 if (!BVN0 || !BVN1)
7224 continue;
7225
7226 bool FoundMatch = true;
7227 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7228 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7229 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7230 if (!CN0 || !CN1 ||
7231 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7232 FoundMatch = false;
7233 break;
7234 }
7235 }
7236
7237 if (FoundMatch)
7238 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7239 N0->getOperand(1 - i), N1->getOperand(1 - j));
7240 }
7241
7242 return SDValue();
7243}
7244
7245static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7246 const AArch64Subtarget *Subtarget) {
7247 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7248 if (!EnableAArch64ExtrGeneration)
7249 return SDValue();
7250 SelectionDAG &DAG = DCI.DAG;
7251 EVT VT = N->getValueType(0);
7252
7253 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7254 return SDValue();
7255
7256 SDValue Res = tryCombineToEXTR(N, DCI);
7257 if (Res.getNode())
7258 return Res;
7259
7260 Res = tryCombineToBSL(N, DCI);
7261 if (Res.getNode())
7262 return Res;
7263
7264 return SDValue();
7265}
7266
7267static SDValue performBitcastCombine(SDNode *N,
7268 TargetLowering::DAGCombinerInfo &DCI,
7269 SelectionDAG &DAG) {
7270 // Wait 'til after everything is legalized to try this. That way we have
7271 // legal vector types and such.
7272 if (DCI.isBeforeLegalizeOps())
7273 return SDValue();
7274
7275 // Remove extraneous bitcasts around an extract_subvector.
7276 // For example,
7277 // (v4i16 (bitconvert
7278 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7279 // becomes
7280 // (extract_subvector ((v8i16 ...), (i64 4)))
7281
7282 // Only interested in 64-bit vectors as the ultimate result.
7283 EVT VT = N->getValueType(0);
7284 if (!VT.isVector())
7285 return SDValue();
7286 if (VT.getSimpleVT().getSizeInBits() != 64)
7287 return SDValue();
7288 // Is the operand an extract_subvector starting at the beginning or halfway
7289 // point of the vector? A low half may also come through as an
7290 // EXTRACT_SUBREG, so look for that, too.
7291 SDValue Op0 = N->getOperand(0);
7292 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7293 !(Op0->isMachineOpcode() &&
7294 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7295 return SDValue();
7296 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7297 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7298 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7299 return SDValue();
7300 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7301 if (idx != AArch64::dsub)
7302 return SDValue();
7303 // The dsub reference is equivalent to a lane zero subvector reference.
7304 idx = 0;
7305 }
7306 // Look through the bitcast of the input to the extract.
7307 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7308 return SDValue();
7309 SDValue Source = Op0->getOperand(0)->getOperand(0);
7310 // If the source type has twice the number of elements as our destination
7311 // type, we know this is an extract of the high or low half of the vector.
7312 EVT SVT = Source->getValueType(0);
7313 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7314 return SDValue();
7315
7316 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7317
7318 // Create the simplified form to just extract the low or high half of the
7319 // vector directly rather than bothering with the bitcasts.
7320 SDLoc dl(N);
7321 unsigned NumElements = VT.getVectorNumElements();
7322 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007323 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007324 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7325 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007326 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007327 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7328 Source, SubReg),
7329 0);
7330 }
7331}
7332
7333static SDValue performConcatVectorsCombine(SDNode *N,
7334 TargetLowering::DAGCombinerInfo &DCI,
7335 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007336 SDLoc dl(N);
7337 EVT VT = N->getValueType(0);
7338 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7339
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007340 // Optimize concat_vectors of truncated vectors, where the intermediate
7341 // type is illegal, to avoid said illegality, e.g.,
7342 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7343 // (v2i16 (truncate (v2i64)))))
7344 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007345 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7346 // (v4i32 (bitcast (v2i64))),
7347 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007348 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7349 // on both input and result type, so we might generate worse code.
7350 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7351 if (N->getNumOperands() == 2 &&
7352 N0->getOpcode() == ISD::TRUNCATE &&
7353 N1->getOpcode() == ISD::TRUNCATE) {
7354 SDValue N00 = N0->getOperand(0);
7355 SDValue N10 = N1->getOperand(0);
7356 EVT N00VT = N00.getValueType();
7357
7358 if (N00VT == N10.getValueType() &&
7359 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7360 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007361 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7362 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7363 for (size_t i = 0; i < Mask.size(); ++i)
7364 Mask[i] = i * 2;
7365 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7366 DAG.getVectorShuffle(
7367 MidVT, dl,
7368 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7369 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007370 }
7371 }
7372
Tim Northover3b0846e2014-05-24 12:50:23 +00007373 // Wait 'til after everything is legalized to try this. That way we have
7374 // legal vector types and such.
7375 if (DCI.isBeforeLegalizeOps())
7376 return SDValue();
7377
Tim Northover3b0846e2014-05-24 12:50:23 +00007378 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7379 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7380 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007381 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007382 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007383 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007384 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007385 }
7386
7387 // Canonicalise concat_vectors so that the right-hand vector has as few
7388 // bit-casts as possible before its real operation. The primary matching
7389 // destination for these operations will be the narrowing "2" instructions,
7390 // which depend on the operation being performed on this right-hand vector.
7391 // For example,
7392 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7393 // becomes
7394 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7395
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007396 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00007397 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007398 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007399 MVT RHSTy = RHS.getValueType().getSimpleVT();
7400 // If the RHS is not a vector, this is not the pattern we're looking for.
7401 if (!RHSTy.isVector())
7402 return SDValue();
7403
7404 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7405
7406 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7407 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007408 return DAG.getNode(ISD::BITCAST, dl, VT,
7409 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7410 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7411 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00007412}
7413
7414static SDValue tryCombineFixedPointConvert(SDNode *N,
7415 TargetLowering::DAGCombinerInfo &DCI,
7416 SelectionDAG &DAG) {
7417 // Wait 'til after everything is legalized to try this. That way we have
7418 // legal vector types and such.
7419 if (DCI.isBeforeLegalizeOps())
7420 return SDValue();
7421 // Transform a scalar conversion of a value from a lane extract into a
7422 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7423 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7424 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7425 //
7426 // The second form interacts better with instruction selection and the
7427 // register allocator to avoid cross-class register copies that aren't
7428 // coalescable due to a lane reference.
7429
7430 // Check the operand and see if it originates from a lane extract.
7431 SDValue Op1 = N->getOperand(1);
7432 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7433 // Yep, no additional predication needed. Perform the transform.
7434 SDValue IID = N->getOperand(0);
7435 SDValue Shift = N->getOperand(2);
7436 SDValue Vec = Op1.getOperand(0);
7437 SDValue Lane = Op1.getOperand(1);
7438 EVT ResTy = N->getValueType(0);
7439 EVT VecResTy;
7440 SDLoc DL(N);
7441
7442 // The vector width should be 128 bits by the time we get here, even
7443 // if it started as 64 bits (the extract_vector handling will have
7444 // done so).
7445 assert(Vec.getValueType().getSizeInBits() == 128 &&
7446 "unexpected vector size on extract_vector_elt!");
7447 if (Vec.getValueType() == MVT::v4i32)
7448 VecResTy = MVT::v4f32;
7449 else if (Vec.getValueType() == MVT::v2i64)
7450 VecResTy = MVT::v2f64;
7451 else
Craig Topper2a30d782014-06-18 05:05:13 +00007452 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007453
7454 SDValue Convert =
7455 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7456 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7457 }
7458 return SDValue();
7459}
7460
7461// AArch64 high-vector "long" operations are formed by performing the non-high
7462// version on an extract_subvector of each operand which gets the high half:
7463//
7464// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7465//
7466// However, there are cases which don't have an extract_high explicitly, but
7467// have another operation that can be made compatible with one for free. For
7468// example:
7469//
7470// (dupv64 scalar) --> (extract_high (dup128 scalar))
7471//
7472// This routine does the actual conversion of such DUPs, once outer routines
7473// have determined that everything else is in order.
7474static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7475 // We can handle most types of duplicate, but the lane ones have an extra
7476 // operand saying *which* lane, so we need to know.
7477 bool IsDUPLANE;
7478 switch (N.getOpcode()) {
7479 case AArch64ISD::DUP:
7480 IsDUPLANE = false;
7481 break;
7482 case AArch64ISD::DUPLANE8:
7483 case AArch64ISD::DUPLANE16:
7484 case AArch64ISD::DUPLANE32:
7485 case AArch64ISD::DUPLANE64:
7486 IsDUPLANE = true;
7487 break;
7488 default:
7489 return SDValue();
7490 }
7491
7492 MVT NarrowTy = N.getSimpleValueType();
7493 if (!NarrowTy.is64BitVector())
7494 return SDValue();
7495
7496 MVT ElementTy = NarrowTy.getVectorElementType();
7497 unsigned NumElems = NarrowTy.getVectorNumElements();
7498 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7499
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007500 SDLoc dl(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00007501 SDValue NewDUP;
7502 if (IsDUPLANE)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007503 NewDUP = DAG.getNode(N.getOpcode(), dl, NewDUPVT, N.getOperand(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00007504 N.getOperand(1));
7505 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007506 NewDUP = DAG.getNode(AArch64ISD::DUP, dl, NewDUPVT, N.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007507
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007508 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, NewDUP,
7509 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007510}
7511
7512static bool isEssentiallyExtractSubvector(SDValue N) {
7513 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7514 return true;
7515
7516 return N.getOpcode() == ISD::BITCAST &&
7517 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7518}
7519
7520/// \brief Helper structure to keep track of ISD::SET_CC operands.
7521struct GenericSetCCInfo {
7522 const SDValue *Opnd0;
7523 const SDValue *Opnd1;
7524 ISD::CondCode CC;
7525};
7526
7527/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7528struct AArch64SetCCInfo {
7529 const SDValue *Cmp;
7530 AArch64CC::CondCode CC;
7531};
7532
7533/// \brief Helper structure to keep track of SetCC information.
7534union SetCCInfo {
7535 GenericSetCCInfo Generic;
7536 AArch64SetCCInfo AArch64;
7537};
7538
7539/// \brief Helper structure to be able to read SetCC information. If set to
7540/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7541/// GenericSetCCInfo.
7542struct SetCCInfoAndKind {
7543 SetCCInfo Info;
7544 bool IsAArch64;
7545};
7546
7547/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7548/// an
7549/// AArch64 lowered one.
7550/// \p SetCCInfo is filled accordingly.
7551/// \post SetCCInfo is meanginfull only when this function returns true.
7552/// \return True when Op is a kind of SET_CC operation.
7553static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7554 // If this is a setcc, this is straight forward.
7555 if (Op.getOpcode() == ISD::SETCC) {
7556 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7557 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7558 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7559 SetCCInfo.IsAArch64 = false;
7560 return true;
7561 }
7562 // Otherwise, check if this is a matching csel instruction.
7563 // In other words:
7564 // - csel 1, 0, cc
7565 // - csel 0, 1, !cc
7566 if (Op.getOpcode() != AArch64ISD::CSEL)
7567 return false;
7568 // Set the information about the operands.
7569 // TODO: we want the operands of the Cmp not the csel
7570 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7571 SetCCInfo.IsAArch64 = true;
7572 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7573 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7574
7575 // Check that the operands matches the constraints:
7576 // (1) Both operands must be constants.
7577 // (2) One must be 1 and the other must be 0.
7578 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7579 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7580
7581 // Check (1).
7582 if (!TValue || !FValue)
7583 return false;
7584
7585 // Check (2).
7586 if (!TValue->isOne()) {
7587 // Update the comparison when we are interested in !cc.
7588 std::swap(TValue, FValue);
7589 SetCCInfo.Info.AArch64.CC =
7590 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7591 }
7592 return TValue->isOne() && FValue->isNullValue();
7593}
7594
7595// Returns true if Op is setcc or zext of setcc.
7596static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7597 if (isSetCC(Op, Info))
7598 return true;
7599 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7600 isSetCC(Op->getOperand(0), Info));
7601}
7602
7603// The folding we want to perform is:
7604// (add x, [zext] (setcc cc ...) )
7605// -->
7606// (csel x, (add x, 1), !cc ...)
7607//
7608// The latter will get matched to a CSINC instruction.
7609static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7610 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7611 SDValue LHS = Op->getOperand(0);
7612 SDValue RHS = Op->getOperand(1);
7613 SetCCInfoAndKind InfoAndKind;
7614
7615 // If neither operand is a SET_CC, give up.
7616 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7617 std::swap(LHS, RHS);
7618 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7619 return SDValue();
7620 }
7621
7622 // FIXME: This could be generatized to work for FP comparisons.
7623 EVT CmpVT = InfoAndKind.IsAArch64
7624 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7625 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7626 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7627 return SDValue();
7628
7629 SDValue CCVal;
7630 SDValue Cmp;
7631 SDLoc dl(Op);
7632 if (InfoAndKind.IsAArch64) {
7633 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007634 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
7635 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007636 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7637 } else
7638 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7639 *InfoAndKind.Info.Generic.Opnd1,
7640 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7641 CCVal, DAG, dl);
7642
7643 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007644 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007645 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
7646}
7647
7648// The basic add/sub long vector instructions have variants with "2" on the end
7649// which act on the high-half of their inputs. They are normally matched by
7650// patterns like:
7651//
7652// (add (zeroext (extract_high LHS)),
7653// (zeroext (extract_high RHS)))
7654// -> uaddl2 vD, vN, vM
7655//
7656// However, if one of the extracts is something like a duplicate, this
7657// instruction can still be used profitably. This function puts the DAG into a
7658// more appropriate form for those patterns to trigger.
7659static SDValue performAddSubLongCombine(SDNode *N,
7660 TargetLowering::DAGCombinerInfo &DCI,
7661 SelectionDAG &DAG) {
7662 if (DCI.isBeforeLegalizeOps())
7663 return SDValue();
7664
7665 MVT VT = N->getSimpleValueType(0);
7666 if (!VT.is128BitVector()) {
7667 if (N->getOpcode() == ISD::ADD)
7668 return performSetccAddFolding(N, DAG);
7669 return SDValue();
7670 }
7671
7672 // Make sure both branches are extended in the same way.
7673 SDValue LHS = N->getOperand(0);
7674 SDValue RHS = N->getOperand(1);
7675 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
7676 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
7677 LHS.getOpcode() != RHS.getOpcode())
7678 return SDValue();
7679
7680 unsigned ExtType = LHS.getOpcode();
7681
7682 // It's not worth doing if at least one of the inputs isn't already an
7683 // extract, but we don't know which it'll be so we have to try both.
7684 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
7685 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
7686 if (!RHS.getNode())
7687 return SDValue();
7688
7689 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
7690 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
7691 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
7692 if (!LHS.getNode())
7693 return SDValue();
7694
7695 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
7696 }
7697
7698 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
7699}
7700
7701// Massage DAGs which we can use the high-half "long" operations on into
7702// something isel will recognize better. E.g.
7703//
7704// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
7705// (aarch64_neon_umull (extract_high (v2i64 vec)))
7706// (extract_high (v2i64 (dup128 scalar)))))
7707//
7708static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
7709 TargetLowering::DAGCombinerInfo &DCI,
7710 SelectionDAG &DAG) {
7711 if (DCI.isBeforeLegalizeOps())
7712 return SDValue();
7713
7714 SDValue LHS = N->getOperand(1);
7715 SDValue RHS = N->getOperand(2);
7716 assert(LHS.getValueType().is64BitVector() &&
7717 RHS.getValueType().is64BitVector() &&
7718 "unexpected shape for long operation");
7719
7720 // Either node could be a DUP, but it's not worth doing both of them (you'd
7721 // just as well use the non-high version) so look for a corresponding extract
7722 // operation on the other "wing".
7723 if (isEssentiallyExtractSubvector(LHS)) {
7724 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
7725 if (!RHS.getNode())
7726 return SDValue();
7727 } else if (isEssentiallyExtractSubvector(RHS)) {
7728 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
7729 if (!LHS.getNode())
7730 return SDValue();
7731 }
7732
7733 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
7734 N->getOperand(0), LHS, RHS);
7735}
7736
7737static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
7738 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
7739 unsigned ElemBits = ElemTy.getSizeInBits();
7740
7741 int64_t ShiftAmount;
7742 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
7743 APInt SplatValue, SplatUndef;
7744 unsigned SplatBitSize;
7745 bool HasAnyUndefs;
7746 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7747 HasAnyUndefs, ElemBits) ||
7748 SplatBitSize != ElemBits)
7749 return SDValue();
7750
7751 ShiftAmount = SplatValue.getSExtValue();
7752 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
7753 ShiftAmount = CVN->getSExtValue();
7754 } else
7755 return SDValue();
7756
7757 unsigned Opcode;
7758 bool IsRightShift;
7759 switch (IID) {
7760 default:
7761 llvm_unreachable("Unknown shift intrinsic");
7762 case Intrinsic::aarch64_neon_sqshl:
7763 Opcode = AArch64ISD::SQSHL_I;
7764 IsRightShift = false;
7765 break;
7766 case Intrinsic::aarch64_neon_uqshl:
7767 Opcode = AArch64ISD::UQSHL_I;
7768 IsRightShift = false;
7769 break;
7770 case Intrinsic::aarch64_neon_srshl:
7771 Opcode = AArch64ISD::SRSHR_I;
7772 IsRightShift = true;
7773 break;
7774 case Intrinsic::aarch64_neon_urshl:
7775 Opcode = AArch64ISD::URSHR_I;
7776 IsRightShift = true;
7777 break;
7778 case Intrinsic::aarch64_neon_sqshlu:
7779 Opcode = AArch64ISD::SQSHLU_I;
7780 IsRightShift = false;
7781 break;
7782 }
7783
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007784 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
7785 SDLoc dl(N);
7786 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
7787 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
7788 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
7789 SDLoc dl(N);
7790 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
7791 DAG.getConstant(ShiftAmount, dl, MVT::i32));
7792 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007793
7794 return SDValue();
7795}
7796
7797// The CRC32[BH] instructions ignore the high bits of their data operand. Since
7798// the intrinsics must be legal and take an i32, this means there's almost
7799// certainly going to be a zext in the DAG which we can eliminate.
7800static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
7801 SDValue AndN = N->getOperand(2);
7802 if (AndN.getOpcode() != ISD::AND)
7803 return SDValue();
7804
7805 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
7806 if (!CMask || CMask->getZExtValue() != Mask)
7807 return SDValue();
7808
7809 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
7810 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
7811}
7812
Ahmed Bougachafab58922015-03-10 20:45:38 +00007813static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
7814 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007815 SDLoc dl(N);
7816 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
7817 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00007818 N->getOperand(1).getSimpleValueType(),
7819 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007820 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00007821}
7822
Tim Northover3b0846e2014-05-24 12:50:23 +00007823static SDValue performIntrinsicCombine(SDNode *N,
7824 TargetLowering::DAGCombinerInfo &DCI,
7825 const AArch64Subtarget *Subtarget) {
7826 SelectionDAG &DAG = DCI.DAG;
7827 unsigned IID = getIntrinsicID(N);
7828 switch (IID) {
7829 default:
7830 break;
7831 case Intrinsic::aarch64_neon_vcvtfxs2fp:
7832 case Intrinsic::aarch64_neon_vcvtfxu2fp:
7833 return tryCombineFixedPointConvert(N, DCI, DAG);
7834 break;
Ahmed Bougachafab58922015-03-10 20:45:38 +00007835 case Intrinsic::aarch64_neon_saddv:
7836 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
7837 case Intrinsic::aarch64_neon_uaddv:
7838 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
7839 case Intrinsic::aarch64_neon_sminv:
7840 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
7841 case Intrinsic::aarch64_neon_uminv:
7842 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
7843 case Intrinsic::aarch64_neon_smaxv:
7844 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
7845 case Intrinsic::aarch64_neon_umaxv:
7846 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007847 case Intrinsic::aarch64_neon_fmax:
7848 return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
7849 N->getOperand(1), N->getOperand(2));
7850 case Intrinsic::aarch64_neon_fmin:
7851 return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
7852 N->getOperand(1), N->getOperand(2));
7853 case Intrinsic::aarch64_neon_smull:
7854 case Intrinsic::aarch64_neon_umull:
7855 case Intrinsic::aarch64_neon_pmull:
7856 case Intrinsic::aarch64_neon_sqdmull:
7857 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
7858 case Intrinsic::aarch64_neon_sqshl:
7859 case Intrinsic::aarch64_neon_uqshl:
7860 case Intrinsic::aarch64_neon_sqshlu:
7861 case Intrinsic::aarch64_neon_srshl:
7862 case Intrinsic::aarch64_neon_urshl:
7863 return tryCombineShiftImm(IID, N, DAG);
7864 case Intrinsic::aarch64_crc32b:
7865 case Intrinsic::aarch64_crc32cb:
7866 return tryCombineCRC32(0xff, N, DAG);
7867 case Intrinsic::aarch64_crc32h:
7868 case Intrinsic::aarch64_crc32ch:
7869 return tryCombineCRC32(0xffff, N, DAG);
7870 }
7871 return SDValue();
7872}
7873
7874static SDValue performExtendCombine(SDNode *N,
7875 TargetLowering::DAGCombinerInfo &DCI,
7876 SelectionDAG &DAG) {
7877 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7878 // we can convert that DUP into another extract_high (of a bigger DUP), which
7879 // helps the backend to decide that an sabdl2 would be useful, saving a real
7880 // extract_high operation.
7881 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7882 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7883 SDNode *ABDNode = N->getOperand(0).getNode();
7884 unsigned IID = getIntrinsicID(ABDNode);
7885 if (IID == Intrinsic::aarch64_neon_sabd ||
7886 IID == Intrinsic::aarch64_neon_uabd) {
7887 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7888 if (!NewABD.getNode())
7889 return SDValue();
7890
7891 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7892 NewABD);
7893 }
7894 }
7895
7896 // This is effectively a custom type legalization for AArch64.
7897 //
7898 // Type legalization will split an extend of a small, legal, type to a larger
7899 // illegal type by first splitting the destination type, often creating
7900 // illegal source types, which then get legalized in isel-confusing ways,
7901 // leading to really terrible codegen. E.g.,
7902 // %result = v8i32 sext v8i8 %value
7903 // becomes
7904 // %losrc = extract_subreg %value, ...
7905 // %hisrc = extract_subreg %value, ...
7906 // %lo = v4i32 sext v4i8 %losrc
7907 // %hi = v4i32 sext v4i8 %hisrc
7908 // Things go rapidly downhill from there.
7909 //
7910 // For AArch64, the [sz]ext vector instructions can only go up one element
7911 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7912 // take two instructions.
7913 //
7914 // This implies that the most efficient way to do the extend from v8i8
7915 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7916 // the normal splitting to happen for the v8i16->v8i32.
7917
7918 // This is pre-legalization to catch some cases where the default
7919 // type legalization will create ill-tempered code.
7920 if (!DCI.isBeforeLegalizeOps())
7921 return SDValue();
7922
7923 // We're only interested in cleaning things up for non-legal vector types
7924 // here. If both the source and destination are legal, things will just
7925 // work naturally without any fiddling.
7926 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7927 EVT ResVT = N->getValueType(0);
7928 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7929 return SDValue();
7930 // If the vector type isn't a simple VT, it's beyond the scope of what
7931 // we're worried about here. Let legalization do its thing and hope for
7932 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00007933 SDValue Src = N->getOperand(0);
7934 EVT SrcVT = Src->getValueType(0);
7935 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00007936 return SDValue();
7937
Tim Northover3b0846e2014-05-24 12:50:23 +00007938 // If the source VT is a 64-bit vector, we can play games and get the
7939 // better results we want.
7940 if (SrcVT.getSizeInBits() != 64)
7941 return SDValue();
7942
7943 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7944 unsigned ElementCount = SrcVT.getVectorNumElements();
7945 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7946 SDLoc DL(N);
7947 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7948
7949 // Now split the rest of the operation into two halves, each with a 64
7950 // bit source.
7951 EVT LoVT, HiVT;
7952 SDValue Lo, Hi;
7953 unsigned NumElements = ResVT.getVectorNumElements();
7954 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7955 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7956 ResVT.getVectorElementType(), NumElements / 2);
7957
7958 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7959 LoVT.getVectorNumElements());
7960 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007961 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007962 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007963 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007964 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7965 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7966
7967 // Now combine the parts back together so we still have a single result
7968 // like the combiner expects.
7969 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7970}
7971
7972/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7973/// value. The load store optimizer pass will merge them to store pair stores.
7974/// This has better performance than a splat of the scalar followed by a split
7975/// vector store. Even if the stores are not merged it is four stores vs a dup,
7976/// followed by an ext.b and two stores.
7977static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7978 SDValue StVal = St->getValue();
7979 EVT VT = StVal.getValueType();
7980
7981 // Don't replace floating point stores, they possibly won't be transformed to
7982 // stp because of the store pair suppress pass.
7983 if (VT.isFloatingPoint())
7984 return SDValue();
7985
7986 // Check for insert vector elements.
7987 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7988 return SDValue();
7989
7990 // We can express a splat as store pair(s) for 2 or 4 elements.
7991 unsigned NumVecElts = VT.getVectorNumElements();
7992 if (NumVecElts != 4 && NumVecElts != 2)
7993 return SDValue();
7994 SDValue SplatVal = StVal.getOperand(1);
7995 unsigned RemainInsertElts = NumVecElts - 1;
7996
7997 // Check that this is a splat.
7998 while (--RemainInsertElts) {
7999 SDValue NextInsertElt = StVal.getOperand(0);
8000 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8001 return SDValue();
8002 if (NextInsertElt.getOperand(1) != SplatVal)
8003 return SDValue();
8004 StVal = NextInsertElt;
8005 }
8006 unsigned OrigAlignment = St->getAlignment();
8007 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8008 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8009
8010 // Create scalar stores. This is at least as good as the code sequence for a
8011 // split unaligned store wich is a dup.s, ext.b, and two stores.
8012 // Most of the time the three stores should be replaced by store pair
8013 // instructions (stp).
8014 SDLoc DL(St);
8015 SDValue BasePtr = St->getBasePtr();
8016 SDValue NewST1 =
8017 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8018 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8019
8020 unsigned Offset = EltOffset;
8021 while (--NumVecElts) {
8022 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008023 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008024 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8025 St->getPointerInfo(), St->isVolatile(),
8026 St->isNonTemporal(), Alignment);
8027 Offset += EltOffset;
8028 }
8029 return NewST1;
8030}
8031
8032static SDValue performSTORECombine(SDNode *N,
8033 TargetLowering::DAGCombinerInfo &DCI,
8034 SelectionDAG &DAG,
8035 const AArch64Subtarget *Subtarget) {
8036 if (!DCI.isBeforeLegalize())
8037 return SDValue();
8038
8039 StoreSDNode *S = cast<StoreSDNode>(N);
8040 if (S->isVolatile())
8041 return SDValue();
8042
8043 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008044 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008045 if (!Subtarget->isCyclone())
8046 return SDValue();
8047
8048 // Don't split at Oz.
8049 MachineFunction &MF = DAG.getMachineFunction();
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00008050 bool IsMinSize = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
Tim Northover3b0846e2014-05-24 12:50:23 +00008051 if (IsMinSize)
8052 return SDValue();
8053
8054 SDValue StVal = S->getValue();
8055 EVT VT = StVal.getValueType();
8056
8057 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8058 // those up regresses performance on micro-benchmarks and olden/bh.
8059 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8060 return SDValue();
8061
8062 // Split unaligned 16B stores. They are terrible for performance.
8063 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8064 // extensions can use this to mark that it does not want splitting to happen
8065 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8066 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8067 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8068 S->getAlignment() <= 2)
8069 return SDValue();
8070
8071 // If we get a splat of a scalar convert this vector store to a store of
8072 // scalars. They will be merged into store pairs thereby removing two
8073 // instructions.
8074 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
8075 if (ReplacedSplat != SDValue())
8076 return ReplacedSplat;
8077
8078 SDLoc DL(S);
8079 unsigned NumElts = VT.getVectorNumElements() / 2;
8080 // Split VT into two.
8081 EVT HalfVT =
8082 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8083 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008084 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008085 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008086 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008087 SDValue BasePtr = S->getBasePtr();
8088 SDValue NewST1 =
8089 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8090 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8091 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008092 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008093 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8094 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8095 S->getAlignment());
8096}
8097
8098/// Target-specific DAG combine function for post-increment LD1 (lane) and
8099/// post-increment LD1R.
8100static SDValue performPostLD1Combine(SDNode *N,
8101 TargetLowering::DAGCombinerInfo &DCI,
8102 bool IsLaneOp) {
8103 if (DCI.isBeforeLegalizeOps())
8104 return SDValue();
8105
8106 SelectionDAG &DAG = DCI.DAG;
8107 EVT VT = N->getValueType(0);
8108
8109 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8110 SDNode *LD = N->getOperand(LoadIdx).getNode();
8111 // If it is not LOAD, can not do such combine.
8112 if (LD->getOpcode() != ISD::LOAD)
8113 return SDValue();
8114
8115 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8116 EVT MemVT = LoadSDN->getMemoryVT();
8117 // Check if memory operand is the same type as the vector element.
8118 if (MemVT != VT.getVectorElementType())
8119 return SDValue();
8120
8121 // Check if there are other uses. If so, do not combine as it will introduce
8122 // an extra load.
8123 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8124 ++UI) {
8125 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8126 continue;
8127 if (*UI != N)
8128 return SDValue();
8129 }
8130
8131 SDValue Addr = LD->getOperand(1);
8132 SDValue Vector = N->getOperand(0);
8133 // Search for a use of the address operand that is an increment.
8134 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8135 Addr.getNode()->use_end(); UI != UE; ++UI) {
8136 SDNode *User = *UI;
8137 if (User->getOpcode() != ISD::ADD
8138 || UI.getUse().getResNo() != Addr.getResNo())
8139 continue;
8140
8141 // Check that the add is independent of the load. Otherwise, folding it
8142 // would create a cycle.
8143 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8144 continue;
8145 // Also check that add is not used in the vector operand. This would also
8146 // create a cycle.
8147 if (User->isPredecessorOf(Vector.getNode()))
8148 continue;
8149
8150 // If the increment is a constant, it must match the memory ref size.
8151 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8152 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8153 uint32_t IncVal = CInc->getZExtValue();
8154 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8155 if (IncVal != NumBytes)
8156 continue;
8157 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8158 }
8159
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008160 // Finally, check that the vector doesn't depend on the load.
8161 // Again, this would create a cycle.
8162 // The load depending on the vector is fine, as that's the case for the
8163 // LD1*post we'll eventually generate anyway.
8164 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8165 continue;
8166
Tim Northover3b0846e2014-05-24 12:50:23 +00008167 SmallVector<SDValue, 8> Ops;
8168 Ops.push_back(LD->getOperand(0)); // Chain
8169 if (IsLaneOp) {
8170 Ops.push_back(Vector); // The vector to be inserted
8171 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8172 }
8173 Ops.push_back(Addr);
8174 Ops.push_back(Inc);
8175
8176 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008177 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008178 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8179 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8180 MemVT,
8181 LoadSDN->getMemOperand());
8182
8183 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008184 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008185 NewResults.push_back(SDValue(LD, 0)); // The result of load
8186 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8187 DCI.CombineTo(LD, NewResults);
8188 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8189 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8190
8191 break;
8192 }
8193 return SDValue();
8194}
8195
8196/// Target-specific DAG combine function for NEON load/store intrinsics
8197/// to merge base address updates.
8198static SDValue performNEONPostLDSTCombine(SDNode *N,
8199 TargetLowering::DAGCombinerInfo &DCI,
8200 SelectionDAG &DAG) {
8201 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8202 return SDValue();
8203
8204 unsigned AddrOpIdx = N->getNumOperands() - 1;
8205 SDValue Addr = N->getOperand(AddrOpIdx);
8206
8207 // Search for a use of the address operand that is an increment.
8208 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8209 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8210 SDNode *User = *UI;
8211 if (User->getOpcode() != ISD::ADD ||
8212 UI.getUse().getResNo() != Addr.getResNo())
8213 continue;
8214
8215 // Check that the add is independent of the load/store. Otherwise, folding
8216 // it would create a cycle.
8217 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8218 continue;
8219
8220 // Find the new opcode for the updating load/store.
8221 bool IsStore = false;
8222 bool IsLaneOp = false;
8223 bool IsDupOp = false;
8224 unsigned NewOpc = 0;
8225 unsigned NumVecs = 0;
8226 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8227 switch (IntNo) {
8228 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8229 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
8230 NumVecs = 2; break;
8231 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
8232 NumVecs = 3; break;
8233 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
8234 NumVecs = 4; break;
8235 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
8236 NumVecs = 2; IsStore = true; break;
8237 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
8238 NumVecs = 3; IsStore = true; break;
8239 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
8240 NumVecs = 4; IsStore = true; break;
8241 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
8242 NumVecs = 2; break;
8243 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
8244 NumVecs = 3; break;
8245 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
8246 NumVecs = 4; break;
8247 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
8248 NumVecs = 2; IsStore = true; break;
8249 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
8250 NumVecs = 3; IsStore = true; break;
8251 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
8252 NumVecs = 4; IsStore = true; break;
8253 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
8254 NumVecs = 2; IsDupOp = true; break;
8255 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
8256 NumVecs = 3; IsDupOp = true; break;
8257 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
8258 NumVecs = 4; IsDupOp = true; break;
8259 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
8260 NumVecs = 2; IsLaneOp = true; break;
8261 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
8262 NumVecs = 3; IsLaneOp = true; break;
8263 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
8264 NumVecs = 4; IsLaneOp = true; break;
8265 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
8266 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8267 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
8268 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8269 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
8270 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8271 }
8272
8273 EVT VecTy;
8274 if (IsStore)
8275 VecTy = N->getOperand(2).getValueType();
8276 else
8277 VecTy = N->getValueType(0);
8278
8279 // If the increment is a constant, it must match the memory ref size.
8280 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8281 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8282 uint32_t IncVal = CInc->getZExtValue();
8283 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8284 if (IsLaneOp || IsDupOp)
8285 NumBytes /= VecTy.getVectorNumElements();
8286 if (IncVal != NumBytes)
8287 continue;
8288 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8289 }
8290 SmallVector<SDValue, 8> Ops;
8291 Ops.push_back(N->getOperand(0)); // Incoming chain
8292 // Load lane and store have vector list as input.
8293 if (IsLaneOp || IsStore)
8294 for (unsigned i = 2; i < AddrOpIdx; ++i)
8295 Ops.push_back(N->getOperand(i));
8296 Ops.push_back(Addr); // Base register
8297 Ops.push_back(Inc);
8298
8299 // Return Types.
8300 EVT Tys[6];
8301 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8302 unsigned n;
8303 for (n = 0; n < NumResultVecs; ++n)
8304 Tys[n] = VecTy;
8305 Tys[n++] = MVT::i64; // Type of write back register
8306 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00008307 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008308
8309 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8310 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8311 MemInt->getMemoryVT(),
8312 MemInt->getMemOperand());
8313
8314 // Update the uses.
8315 std::vector<SDValue> NewResults;
8316 for (unsigned i = 0; i < NumResultVecs; ++i) {
8317 NewResults.push_back(SDValue(UpdN.getNode(), i));
8318 }
8319 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8320 DCI.CombineTo(N, NewResults);
8321 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8322
8323 break;
8324 }
8325 return SDValue();
8326}
8327
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008328// Checks to see if the value is the prescribed width and returns information
8329// about its extension mode.
8330static
8331bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8332 ExtType = ISD::NON_EXTLOAD;
8333 switch(V.getNode()->getOpcode()) {
8334 default:
8335 return false;
8336 case ISD::LOAD: {
8337 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8338 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8339 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8340 ExtType = LoadNode->getExtensionType();
8341 return true;
8342 }
8343 return false;
8344 }
8345 case ISD::AssertSext: {
8346 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8347 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8348 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8349 ExtType = ISD::SEXTLOAD;
8350 return true;
8351 }
8352 return false;
8353 }
8354 case ISD::AssertZext: {
8355 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8356 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8357 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8358 ExtType = ISD::ZEXTLOAD;
8359 return true;
8360 }
8361 return false;
8362 }
8363 case ISD::Constant:
8364 case ISD::TargetConstant: {
Reid Kleckner39ad7c92014-08-29 22:14:26 +00008365 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
Aaron Ballman8ca53882014-09-02 12:19:02 +00008366 1LL << (width - 1))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008367 return true;
8368 return false;
8369 }
8370 }
8371
8372 return true;
8373}
8374
8375// This function does a whole lot of voodoo to determine if the tests are
8376// equivalent without and with a mask. Essentially what happens is that given a
8377// DAG resembling:
8378//
8379// +-------------+ +-------------+ +-------------+ +-------------+
8380// | Input | | AddConstant | | CompConstant| | CC |
8381// +-------------+ +-------------+ +-------------+ +-------------+
8382// | | | |
8383// V V | +----------+
8384// +-------------+ +----+ | |
8385// | ADD | |0xff| | |
8386// +-------------+ +----+ | |
8387// | | | |
8388// V V | |
8389// +-------------+ | |
8390// | AND | | |
8391// +-------------+ | |
8392// | | |
8393// +-----+ | |
8394// | | |
8395// V V V
8396// +-------------+
8397// | CMP |
8398// +-------------+
8399//
8400// The AND node may be safely removed for some combinations of inputs. In
8401// particular we need to take into account the extension type of the Input,
8402// the exact values of AddConstant, CompConstant, and CC, along with the nominal
8403// width of the input (this can work for any width inputs, the above graph is
8404// specific to 8 bits.
8405//
8406// The specific equations were worked out by generating output tables for each
8407// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8408// problem was simplified by working with 4 bit inputs, which means we only
8409// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8410// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8411// patterns present in both extensions (0,7). For every distinct set of
8412// AddConstant and CompConstants bit patterns we can consider the masked and
8413// unmasked versions to be equivalent if the result of this function is true for
8414// all 16 distinct bit patterns of for the current extension type of Input (w0).
8415//
8416// sub w8, w0, w1
8417// and w10, w8, #0x0f
8418// cmp w8, w2
8419// cset w9, AArch64CC
8420// cmp w10, w2
8421// cset w11, AArch64CC
8422// cmp w9, w11
8423// cset w0, eq
8424// ret
8425//
8426// Since the above function shows when the outputs are equivalent it defines
8427// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8428// would be expensive to run during compiles. The equations below were written
8429// in a test harness that confirmed they gave equivalent outputs to the above
8430// for all inputs function, so they can be used determine if the removal is
8431// legal instead.
8432//
8433// isEquivalentMaskless() is the code for testing if the AND can be removed
8434// factored out of the DAG recognition as the DAG can take several forms.
8435
8436static
8437bool isEquivalentMaskless(unsigned CC, unsigned width,
8438 ISD::LoadExtType ExtType, signed AddConstant,
8439 signed CompConstant) {
8440 // By being careful about our equations and only writing the in term
8441 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8442 // make them generally applicable to all bit widths.
8443 signed MaxUInt = (1 << width);
8444
8445 // For the purposes of these comparisons sign extending the type is
8446 // equivalent to zero extending the add and displacing it by half the integer
8447 // width. Provided we are careful and make sure our equations are valid over
8448 // the whole range we can just adjust the input and avoid writing equations
8449 // for sign extended inputs.
8450 if (ExtType == ISD::SEXTLOAD)
8451 AddConstant -= (1 << (width-1));
8452
8453 switch(CC) {
8454 case AArch64CC::LE:
8455 case AArch64CC::GT: {
8456 if ((AddConstant == 0) ||
8457 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8458 (AddConstant >= 0 && CompConstant < 0) ||
8459 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8460 return true;
8461 } break;
8462 case AArch64CC::LT:
8463 case AArch64CC::GE: {
8464 if ((AddConstant == 0) ||
8465 (AddConstant >= 0 && CompConstant <= 0) ||
8466 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8467 return true;
8468 } break;
8469 case AArch64CC::HI:
8470 case AArch64CC::LS: {
8471 if ((AddConstant >= 0 && CompConstant < 0) ||
8472 (AddConstant <= 0 && CompConstant >= -1 &&
8473 CompConstant < AddConstant + MaxUInt))
8474 return true;
8475 } break;
8476 case AArch64CC::PL:
8477 case AArch64CC::MI: {
8478 if ((AddConstant == 0) ||
8479 (AddConstant > 0 && CompConstant <= 0) ||
8480 (AddConstant < 0 && CompConstant <= AddConstant))
8481 return true;
8482 } break;
8483 case AArch64CC::LO:
8484 case AArch64CC::HS: {
8485 if ((AddConstant >= 0 && CompConstant <= 0) ||
8486 (AddConstant <= 0 && CompConstant >= 0 &&
8487 CompConstant <= AddConstant + MaxUInt))
8488 return true;
8489 } break;
8490 case AArch64CC::EQ:
8491 case AArch64CC::NE: {
8492 if ((AddConstant > 0 && CompConstant < 0) ||
8493 (AddConstant < 0 && CompConstant >= 0 &&
8494 CompConstant < AddConstant + MaxUInt) ||
8495 (AddConstant >= 0 && CompConstant >= 0 &&
8496 CompConstant >= AddConstant) ||
8497 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8498
8499 return true;
8500 } break;
8501 case AArch64CC::VS:
8502 case AArch64CC::VC:
8503 case AArch64CC::AL:
8504 case AArch64CC::NV:
8505 return true;
8506 case AArch64CC::Invalid:
8507 break;
8508 }
8509
8510 return false;
8511}
8512
8513static
8514SDValue performCONDCombine(SDNode *N,
8515 TargetLowering::DAGCombinerInfo &DCI,
8516 SelectionDAG &DAG, unsigned CCIndex,
8517 unsigned CmpIndex) {
8518 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8519 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8520 unsigned CondOpcode = SubsNode->getOpcode();
8521
8522 if (CondOpcode != AArch64ISD::SUBS)
8523 return SDValue();
8524
8525 // There is a SUBS feeding this condition. Is it fed by a mask we can
8526 // use?
8527
8528 SDNode *AndNode = SubsNode->getOperand(0).getNode();
8529 unsigned MaskBits = 0;
8530
8531 if (AndNode->getOpcode() != ISD::AND)
8532 return SDValue();
8533
8534 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8535 uint32_t CNV = CN->getZExtValue();
8536 if (CNV == 255)
8537 MaskBits = 8;
8538 else if (CNV == 65535)
8539 MaskBits = 16;
8540 }
8541
8542 if (!MaskBits)
8543 return SDValue();
8544
8545 SDValue AddValue = AndNode->getOperand(0);
8546
8547 if (AddValue.getOpcode() != ISD::ADD)
8548 return SDValue();
8549
8550 // The basic dag structure is correct, grab the inputs and validate them.
8551
8552 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8553 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8554 SDValue SubsInputValue = SubsNode->getOperand(1);
8555
8556 // The mask is present and the provenance of all the values is a smaller type,
8557 // lets see if the mask is superfluous.
8558
8559 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8560 !isa<ConstantSDNode>(SubsInputValue.getNode()))
8561 return SDValue();
8562
8563 ISD::LoadExtType ExtType;
8564
8565 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8566 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8567 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8568 return SDValue();
8569
8570 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8571 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8572 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8573 return SDValue();
8574
8575 // The AND is not necessary, remove it.
8576
8577 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8578 SubsNode->getValueType(1));
8579 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8580
8581 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8582 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8583
8584 return SDValue(N, 0);
8585}
8586
Tim Northover3b0846e2014-05-24 12:50:23 +00008587// Optimize compare with zero and branch.
8588static SDValue performBRCONDCombine(SDNode *N,
8589 TargetLowering::DAGCombinerInfo &DCI,
8590 SelectionDAG &DAG) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008591 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8592 if (NV.getNode())
8593 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008594 SDValue Chain = N->getOperand(0);
8595 SDValue Dest = N->getOperand(1);
8596 SDValue CCVal = N->getOperand(2);
8597 SDValue Cmp = N->getOperand(3);
8598
8599 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8600 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8601 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8602 return SDValue();
8603
8604 unsigned CmpOpc = Cmp.getOpcode();
8605 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8606 return SDValue();
8607
8608 // Only attempt folding if there is only one use of the flag and no use of the
8609 // value.
8610 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8611 return SDValue();
8612
8613 SDValue LHS = Cmp.getOperand(0);
8614 SDValue RHS = Cmp.getOperand(1);
8615
8616 assert(LHS.getValueType() == RHS.getValueType() &&
8617 "Expected the value type to be the same for both operands!");
8618 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8619 return SDValue();
8620
8621 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8622 std::swap(LHS, RHS);
8623
8624 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8625 return SDValue();
8626
8627 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8628 LHS.getOpcode() == ISD::SRL)
8629 return SDValue();
8630
8631 // Fold the compare into the branch instruction.
8632 SDValue BR;
8633 if (CC == AArch64CC::EQ)
8634 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8635 else
8636 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8637
8638 // Do not add new nodes to DAG combiner worklist.
8639 DCI.CombineTo(N, BR, false);
8640
8641 return SDValue();
8642}
8643
8644// vselect (v1i1 setcc) ->
8645// vselect (v1iXX setcc) (XX is the size of the compared operand type)
8646// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
8647// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
8648// such VSELECT.
8649static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
8650 SDValue N0 = N->getOperand(0);
8651 EVT CCVT = N0.getValueType();
8652
8653 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
8654 CCVT.getVectorElementType() != MVT::i1)
8655 return SDValue();
8656
8657 EVT ResVT = N->getValueType(0);
8658 EVT CmpVT = N0.getOperand(0).getValueType();
8659 // Only combine when the result type is of the same size as the compared
8660 // operands.
8661 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
8662 return SDValue();
8663
8664 SDValue IfTrue = N->getOperand(1);
8665 SDValue IfFalse = N->getOperand(2);
8666 SDValue SetCC =
8667 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
8668 N0.getOperand(0), N0.getOperand(1),
8669 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8670 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
8671 IfTrue, IfFalse);
8672}
8673
8674/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
8675/// the compare-mask instructions rather than going via NZCV, even if LHS and
8676/// RHS are really scalar. This replaces any scalar setcc in the above pattern
8677/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00008678static SDValue performSelectCombine(SDNode *N,
8679 TargetLowering::DAGCombinerInfo &DCI) {
8680 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00008681 SDValue N0 = N->getOperand(0);
8682 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00008683
Ahmed Bougachac004c602015-04-27 21:43:12 +00008684 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00008685 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008686
Ahmed Bougachac004c602015-04-27 21:43:12 +00008687 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
8688 // scalar SetCCResultType. We also don't expect vectors, because we assume
8689 // that selects fed by vector SETCCs are canonicalized to VSELECT.
8690 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
8691 "Scalar-SETCC feeding SELECT has unexpected result type!");
8692
Tim Northoverc1c05ae2014-08-29 13:05:18 +00008693 // If NumMaskElts == 0, the comparison is larger than select result. The
8694 // largest real NEON comparison is 64-bits per lane, which means the result is
8695 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00008696 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00008697
8698 // Don't try to do this optimization when the setcc itself has i1 operands.
8699 // There are no legal vectors of i1, so this would be pointless.
8700 if (SrcVT == MVT::i1)
8701 return SDValue();
8702
Tim Northover3c0915e2014-08-29 15:34:58 +00008703 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00008704 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00008705 return SDValue();
8706
Tim Northoverc1c05ae2014-08-29 13:05:18 +00008707 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00008708 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
8709
Ahmed Bougacha89bba612015-04-27 21:01:20 +00008710 // Also bail out if the vector CCVT isn't the same size as ResVT.
8711 // This can happen if the SETCC operand size doesn't divide the ResVT size
8712 // (e.g., f64 vs v3f32).
8713 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
8714 return SDValue();
8715
Ahmed Bougachac004c602015-04-27 21:43:12 +00008716 // Make sure we didn't create illegal types, if we're not supposed to.
8717 assert(DCI.isBeforeLegalize() ||
8718 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
8719
Tim Northover3b0846e2014-05-24 12:50:23 +00008720 // First perform a vector comparison, where lane 0 is the one we're interested
8721 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00008722 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008723 SDValue LHS =
8724 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
8725 SDValue RHS =
8726 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
8727 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
8728
8729 // Now duplicate the comparison mask we want across all other lanes.
8730 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
8731 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00008732 Mask = DAG.getNode(ISD::BITCAST, DL,
8733 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00008734
8735 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
8736}
8737
8738SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
8739 DAGCombinerInfo &DCI) const {
8740 SelectionDAG &DAG = DCI.DAG;
8741 switch (N->getOpcode()) {
8742 default:
8743 break;
8744 case ISD::ADD:
8745 case ISD::SUB:
8746 return performAddSubLongCombine(N, DCI, DAG);
8747 case ISD::XOR:
8748 return performXorCombine(N, DAG, DCI, Subtarget);
8749 case ISD::MUL:
8750 return performMulCombine(N, DAG, DCI, Subtarget);
8751 case ISD::SINT_TO_FP:
8752 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008753 return performIntToFpCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00008754 case ISD::OR:
8755 return performORCombine(N, DCI, Subtarget);
8756 case ISD::INTRINSIC_WO_CHAIN:
8757 return performIntrinsicCombine(N, DCI, Subtarget);
8758 case ISD::ANY_EXTEND:
8759 case ISD::ZERO_EXTEND:
8760 case ISD::SIGN_EXTEND:
8761 return performExtendCombine(N, DCI, DAG);
8762 case ISD::BITCAST:
8763 return performBitcastCombine(N, DCI, DAG);
8764 case ISD::CONCAT_VECTORS:
8765 return performConcatVectorsCombine(N, DCI, DAG);
8766 case ISD::SELECT:
Ahmed Bougachac004c602015-04-27 21:43:12 +00008767 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +00008768 case ISD::VSELECT:
8769 return performVSelectCombine(N, DCI.DAG);
8770 case ISD::STORE:
8771 return performSTORECombine(N, DCI, DAG, Subtarget);
8772 case AArch64ISD::BRCOND:
8773 return performBRCONDCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008774 case AArch64ISD::CSEL:
8775 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00008776 case AArch64ISD::DUP:
8777 return performPostLD1Combine(N, DCI, false);
8778 case ISD::INSERT_VECTOR_ELT:
8779 return performPostLD1Combine(N, DCI, true);
8780 case ISD::INTRINSIC_VOID:
8781 case ISD::INTRINSIC_W_CHAIN:
8782 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8783 case Intrinsic::aarch64_neon_ld2:
8784 case Intrinsic::aarch64_neon_ld3:
8785 case Intrinsic::aarch64_neon_ld4:
8786 case Intrinsic::aarch64_neon_ld1x2:
8787 case Intrinsic::aarch64_neon_ld1x3:
8788 case Intrinsic::aarch64_neon_ld1x4:
8789 case Intrinsic::aarch64_neon_ld2lane:
8790 case Intrinsic::aarch64_neon_ld3lane:
8791 case Intrinsic::aarch64_neon_ld4lane:
8792 case Intrinsic::aarch64_neon_ld2r:
8793 case Intrinsic::aarch64_neon_ld3r:
8794 case Intrinsic::aarch64_neon_ld4r:
8795 case Intrinsic::aarch64_neon_st2:
8796 case Intrinsic::aarch64_neon_st3:
8797 case Intrinsic::aarch64_neon_st4:
8798 case Intrinsic::aarch64_neon_st1x2:
8799 case Intrinsic::aarch64_neon_st1x3:
8800 case Intrinsic::aarch64_neon_st1x4:
8801 case Intrinsic::aarch64_neon_st2lane:
8802 case Intrinsic::aarch64_neon_st3lane:
8803 case Intrinsic::aarch64_neon_st4lane:
8804 return performNEONPostLDSTCombine(N, DCI, DAG);
8805 default:
8806 break;
8807 }
8808 }
8809 return SDValue();
8810}
8811
8812// Check if the return value is used as only a return value, as otherwise
8813// we can't perform a tail-call. In particular, we need to check for
8814// target ISD nodes that are returns and any other "odd" constructs
8815// that the generic analysis code won't necessarily catch.
8816bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
8817 SDValue &Chain) const {
8818 if (N->getNumValues() != 1)
8819 return false;
8820 if (!N->hasNUsesOfValue(1, 0))
8821 return false;
8822
8823 SDValue TCChain = Chain;
8824 SDNode *Copy = *N->use_begin();
8825 if (Copy->getOpcode() == ISD::CopyToReg) {
8826 // If the copy has a glue operand, we conservatively assume it isn't safe to
8827 // perform a tail call.
8828 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
8829 MVT::Glue)
8830 return false;
8831 TCChain = Copy->getOperand(0);
8832 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
8833 return false;
8834
8835 bool HasRet = false;
8836 for (SDNode *Node : Copy->uses()) {
8837 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
8838 return false;
8839 HasRet = true;
8840 }
8841
8842 if (!HasRet)
8843 return false;
8844
8845 Chain = TCChain;
8846 return true;
8847}
8848
8849// Return whether the an instruction can potentially be optimized to a tail
8850// call. This will cause the optimizers to attempt to move, or duplicate,
8851// return instructions to help enable tail call optimizations for this
8852// instruction.
8853bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
8854 if (!CI->isTailCall())
8855 return false;
8856
8857 return true;
8858}
8859
8860bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
8861 SDValue &Offset,
8862 ISD::MemIndexedMode &AM,
8863 bool &IsInc,
8864 SelectionDAG &DAG) const {
8865 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
8866 return false;
8867
8868 Base = Op->getOperand(0);
8869 // All of the indexed addressing mode instructions take a signed
8870 // 9 bit immediate offset.
8871 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
8872 int64_t RHSC = (int64_t)RHS->getZExtValue();
8873 if (RHSC >= 256 || RHSC <= -256)
8874 return false;
8875 IsInc = (Op->getOpcode() == ISD::ADD);
8876 Offset = Op->getOperand(1);
8877 return true;
8878 }
8879 return false;
8880}
8881
8882bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8883 SDValue &Offset,
8884 ISD::MemIndexedMode &AM,
8885 SelectionDAG &DAG) const {
8886 EVT VT;
8887 SDValue Ptr;
8888 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8889 VT = LD->getMemoryVT();
8890 Ptr = LD->getBasePtr();
8891 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8892 VT = ST->getMemoryVT();
8893 Ptr = ST->getBasePtr();
8894 } else
8895 return false;
8896
8897 bool IsInc;
8898 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
8899 return false;
8900 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
8901 return true;
8902}
8903
8904bool AArch64TargetLowering::getPostIndexedAddressParts(
8905 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
8906 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
8907 EVT VT;
8908 SDValue Ptr;
8909 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8910 VT = LD->getMemoryVT();
8911 Ptr = LD->getBasePtr();
8912 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8913 VT = ST->getMemoryVT();
8914 Ptr = ST->getBasePtr();
8915 } else
8916 return false;
8917
8918 bool IsInc;
8919 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
8920 return false;
8921 // Post-indexing updates the base, so it's not a valid transform
8922 // if that's not the same as the load's pointer.
8923 if (Ptr != Base)
8924 return false;
8925 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
8926 return true;
8927}
8928
Tim Northoverf8bfe212014-07-18 13:07:05 +00008929static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
8930 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +00008931 SDLoc DL(N);
8932 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +00008933
8934 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
8935 return;
8936
Tim Northoverf8bfe212014-07-18 13:07:05 +00008937 Op = SDValue(
8938 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
8939 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008940 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00008941 0);
8942 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
8943 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
8944}
8945
Tim Northover3b0846e2014-05-24 12:50:23 +00008946void AArch64TargetLowering::ReplaceNodeResults(
8947 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
8948 switch (N->getOpcode()) {
8949 default:
8950 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +00008951 case ISD::BITCAST:
8952 ReplaceBITCASTResults(N, Results, DAG);
8953 return;
Tim Northover3b0846e2014-05-24 12:50:23 +00008954 case ISD::FP_TO_UINT:
8955 case ISD::FP_TO_SINT:
8956 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
8957 // Let normal code take care of it by not adding anything to Results.
8958 return;
8959 }
8960}
8961
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00008962bool AArch64TargetLowering::useLoadStackGuardNode() const {
8963 return true;
8964}
8965
Hao Liu44e5d7a2014-11-21 06:39:58 +00008966bool AArch64TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8967 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8968 // reciprocal if there are three or more FDIVs.
8969 return NumUsers > 2;
8970}
8971
Chandler Carruth9d010ff2014-07-03 00:23:43 +00008972TargetLoweringBase::LegalizeTypeAction
8973AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
8974 MVT SVT = VT.getSimpleVT();
8975 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
8976 // v4i16, v2i32 instead of to promote.
8977 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
8978 || SVT == MVT::v1f32)
8979 return TypeWidenVector;
8980
8981 return TargetLoweringBase::getPreferredVectorAction(VT);
8982}
8983
Robin Morisseted3d48f2014-09-03 21:29:59 +00008984// Loads and stores less than 128-bits are already atomic; ones above that
8985// are doomed anyway, so defer to the default libcall and blame the OS when
8986// things go wrong.
8987bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
8988 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
8989 return Size == 128;
8990}
8991
8992// Loads and stores less than 128-bits are already atomic; ones above that
8993// are doomed anyway, so defer to the default libcall and blame the OS when
8994// things go wrong.
8995bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
8996 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
8997 return Size == 128;
8998}
8999
9000// For the real atomic operations, we have ldxr/stxr up to 128 bits,
JF Bastienf14889e2015-03-04 15:47:57 +00009001TargetLoweringBase::AtomicRMWExpansionKind
9002AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +00009003 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
JF Bastienf14889e2015-03-04 15:47:57 +00009004 return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9005 : AtomicRMWExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +00009006}
9007
Robin Morisset25c8e312014-09-17 00:06:58 +00009008bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9009 return true;
9010}
9011
Tim Northover3b0846e2014-05-24 12:50:23 +00009012Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9013 AtomicOrdering Ord) const {
9014 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9015 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +00009016 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009017
9018 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9019 // intrinsic must return {i64, i64} and we have to recombine them into a
9020 // single i128 here.
9021 if (ValTy->getPrimitiveSizeInBits() == 128) {
9022 Intrinsic::ID Int =
9023 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9024 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9025
9026 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9027 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9028
9029 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9030 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9031 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9032 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9033 return Builder.CreateOr(
9034 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9035 }
9036
9037 Type *Tys[] = { Addr->getType() };
9038 Intrinsic::ID Int =
9039 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9040 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9041
9042 return Builder.CreateTruncOrBitCast(
9043 Builder.CreateCall(Ldxr, Addr),
9044 cast<PointerType>(Addr->getType())->getElementType());
9045}
9046
9047Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9048 Value *Val, Value *Addr,
9049 AtomicOrdering Ord) const {
9050 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +00009051 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009052
9053 // Since the intrinsics must have legal type, the i128 intrinsics take two
9054 // parameters: "i64, i64". We must marshal Val into the appropriate form
9055 // before the call.
9056 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9057 Intrinsic::ID Int =
9058 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9059 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9060 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9061
9062 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9063 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9064 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9065 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
9066 }
9067
9068 Intrinsic::ID Int =
9069 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9070 Type *Tys[] = { Addr->getType() };
9071 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9072
9073 return Builder.CreateCall2(
9074 Stxr, Builder.CreateZExtOrBitCast(
9075 Val, Stxr->getFunctionType()->getParamType(0)),
9076 Addr);
9077}
Tim Northover3c55cca2014-11-27 21:02:42 +00009078
9079bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9080 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9081 return Ty->isArrayTy();
9082}