blob: 2be5f3c4a64050f10c23ecb4eda7dc94283af7f7 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
18#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64TargetMachine.h"
20#include "AArch64TargetObjectFile.h"
21#include "MCTargetDesc/AArch64AddressingModes.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "aarch64-lower"
39
40STATISTIC(NumTailCalls, "Number of tail calls");
41STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
Tim Northover3b0846e2014-05-24 12:50:23 +000043// Place holder until extr generation is tested fully.
44static cl::opt<bool>
45EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47 cl::init(true));
48
49static cl::opt<bool>
50EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000051 cl::desc("Allow AArch64 SLI/SRI formation"),
52 cl::init(false));
53
54// FIXME: The necessary dtprel relocations don't seem to be supported
55// well in the GNU bfd and gold linkers at the moment. Therefore, by
56// default, for now, fall back to GeneralDynamic code generation.
57cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000061
Matthias Braunaf7d7702015-07-16 20:02:37 +000062/// Value type used for condition codes.
63static const MVT MVT_CC = MVT::i32;
64
Eric Christopher905f12d2015-01-29 00:19:42 +000065AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000068
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85 }
86
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000097 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000098
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000105 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000106 }
107
108 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000109 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000110
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
146
Balaram Makam92431702016-02-01 19:13:07 +0000147 // Custom lowering hooks are needed for OR
148 // to fold it into CCMP.
149 setOperationAction(ISD::OR, MVT::i32, Custom);
150 setOperationAction(ISD::OR, MVT::i64, Custom);
151
152 // Custom lowering hooks are needed for AND
153 // to fold it into CCMP.
154 setOperationAction(ISD::AND, MVT::i32, Custom);
155 setOperationAction(ISD::AND, MVT::i64, Custom);
156
Tim Northover3b0846e2014-05-24 12:50:23 +0000157 // Virtually no operation on f128 is legal, but LLVM can't expand them when
158 // there's a valid register class, so we need custom operations in most cases.
159 setOperationAction(ISD::FABS, MVT::f128, Expand);
160 setOperationAction(ISD::FADD, MVT::f128, Custom);
161 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
162 setOperationAction(ISD::FCOS, MVT::f128, Expand);
163 setOperationAction(ISD::FDIV, MVT::f128, Custom);
164 setOperationAction(ISD::FMA, MVT::f128, Expand);
165 setOperationAction(ISD::FMUL, MVT::f128, Custom);
166 setOperationAction(ISD::FNEG, MVT::f128, Expand);
167 setOperationAction(ISD::FPOW, MVT::f128, Expand);
168 setOperationAction(ISD::FREM, MVT::f128, Expand);
169 setOperationAction(ISD::FRINT, MVT::f128, Expand);
170 setOperationAction(ISD::FSIN, MVT::f128, Expand);
171 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
172 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
173 setOperationAction(ISD::FSUB, MVT::f128, Custom);
174 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
175 setOperationAction(ISD::SETCC, MVT::f128, Custom);
176 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
177 setOperationAction(ISD::SELECT, MVT::f128, Custom);
178 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
179 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
180
181 // Lowering for many of the conversions is actually specified by the non-f128
182 // type. The LowerXXX function will be trivial when f128 isn't involved.
183 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
184 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
185 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
186 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
187 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
188 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
189 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
190 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
191 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
192 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
193 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
194 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
195 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
196 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
197
198 // Variable arguments.
199 setOperationAction(ISD::VASTART, MVT::Other, Custom);
200 setOperationAction(ISD::VAARG, MVT::Other, Custom);
201 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
202 setOperationAction(ISD::VAEND, MVT::Other, Expand);
203
204 // Variable-sized objects.
205 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
206 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
207 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
208
Tim Northover3b0846e2014-05-24 12:50:23 +0000209 // Constant pool entries
210 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
211
212 // BlockAddress
213 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
214
215 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
216 setOperationAction(ISD::ADDC, MVT::i32, Custom);
217 setOperationAction(ISD::ADDE, MVT::i32, Custom);
218 setOperationAction(ISD::SUBC, MVT::i32, Custom);
219 setOperationAction(ISD::SUBE, MVT::i32, Custom);
220 setOperationAction(ISD::ADDC, MVT::i64, Custom);
221 setOperationAction(ISD::ADDE, MVT::i64, Custom);
222 setOperationAction(ISD::SUBC, MVT::i64, Custom);
223 setOperationAction(ISD::SUBE, MVT::i64, Custom);
224
225 // AArch64 lacks both left-rotate and popcount instructions.
226 setOperationAction(ISD::ROTL, MVT::i32, Expand);
227 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000228 for (MVT VT : MVT::vector_valuetypes()) {
229 setOperationAction(ISD::ROTL, VT, Expand);
230 setOperationAction(ISD::ROTR, VT, Expand);
231 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000232
233 // AArch64 doesn't have {U|S}MUL_LOHI.
234 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
235 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
236
237
238 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
239 // counterparts, which AArch64 supports directly.
240 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
241 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
242 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
243 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
244
245 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
246 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
247
248 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
249 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000250 for (MVT VT : MVT::vector_valuetypes()) {
251 setOperationAction(ISD::SDIVREM, VT, Expand);
252 setOperationAction(ISD::UDIVREM, VT, Expand);
253 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000254 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);
James Molloy63be1982015-08-14 09:08:50 +0000317 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
318 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000319
Oliver Stannard89d15422014-08-27 16:16:04 +0000320 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
321 // known to be safe.
322 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
323 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
324 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
325 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
326 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
327 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
328 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
329 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
330 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
331 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
332 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
333 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
334
335 // Expand all other v4f16 operations.
336 // FIXME: We could generate better code by promoting some operations to
337 // a pair of v4f32s
338 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
339 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
340 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
341 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
342 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
343 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
344 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
345 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
346 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
347 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
348 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
349 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
350 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
351 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
352 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
353 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
354 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
355 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
356 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
357 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
358 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
359 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
360 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
361 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
362 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
363 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
364
365
366 // v8f16 is also a storage-only type, so expand it.
367 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
368 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
369 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
370 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
371 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
372 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
373 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
374 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
375 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
376 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
377 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
378 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
379 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
380 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
381 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
382 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
383 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
384 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
385 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
386 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
387 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
388 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
389 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
390 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
391 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
392 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
393 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
394 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
395 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
396 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
397 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
398
Tim Northover3b0846e2014-05-24 12:50:23 +0000399 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000400 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000401 setOperationAction(ISD::FFLOOR, Ty, Legal);
402 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
403 setOperationAction(ISD::FCEIL, Ty, Legal);
404 setOperationAction(ISD::FRINT, Ty, Legal);
405 setOperationAction(ISD::FTRUNC, Ty, Legal);
406 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000407 setOperationAction(ISD::FMINNUM, Ty, Legal);
408 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000409 setOperationAction(ISD::FMINNAN, Ty, Legal);
410 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000411 }
412
413 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
414
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000415 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
416 // This requires the Performance Monitors extension.
417 if (Subtarget->hasPerfMon())
418 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
419
Tim Northover3b0846e2014-05-24 12:50:23 +0000420 if (Subtarget->isTargetMachO()) {
421 // For iOS, we don't want to the normal expansion of a libcall to
422 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
423 // traffic.
424 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
425 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
426 } else {
427 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
428 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
429 }
430
Juergen Ributzka23266502014-12-10 19:43:32 +0000431 // Make floating-point constants legal for the large code model, so they don't
432 // become loads from the constant pool.
433 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
434 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
435 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
436 }
437
Tim Northover3b0846e2014-05-24 12:50:23 +0000438 // AArch64 does not have floating-point extending loads, i1 sign-extending
439 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000440 for (MVT VT : MVT::fp_valuetypes()) {
441 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
442 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
443 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
444 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
445 }
446 for (MVT VT : MVT::integer_valuetypes())
447 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
448
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
450 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
451 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
452 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
453 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
454 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
455 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000456
457 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
458 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
459
Tim Northover3b0846e2014-05-24 12:50:23 +0000460 // Indexed loads and stores are supported.
461 for (unsigned im = (unsigned)ISD::PRE_INC;
462 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
463 setIndexedLoadAction(im, MVT::i8, Legal);
464 setIndexedLoadAction(im, MVT::i16, Legal);
465 setIndexedLoadAction(im, MVT::i32, Legal);
466 setIndexedLoadAction(im, MVT::i64, Legal);
467 setIndexedLoadAction(im, MVT::f64, Legal);
468 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000469 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000470 setIndexedStoreAction(im, MVT::i8, Legal);
471 setIndexedStoreAction(im, MVT::i16, Legal);
472 setIndexedStoreAction(im, MVT::i32, Legal);
473 setIndexedStoreAction(im, MVT::i64, Legal);
474 setIndexedStoreAction(im, MVT::f64, Legal);
475 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000476 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 }
478
479 // Trap.
480 setOperationAction(ISD::TRAP, MVT::Other, Legal);
481
482 // We combine OR nodes for bitfield operations.
483 setTargetDAGCombine(ISD::OR);
484
485 // Vector add and sub nodes may conceal a high-half opportunity.
486 // Also, try to fold ADD into CSINC/CSINV..
487 setTargetDAGCombine(ISD::ADD);
488 setTargetDAGCombine(ISD::SUB);
489
490 setTargetDAGCombine(ISD::XOR);
491 setTargetDAGCombine(ISD::SINT_TO_FP);
492 setTargetDAGCombine(ISD::UINT_TO_FP);
493
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000494 setTargetDAGCombine(ISD::FP_TO_SINT);
495 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000496 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000497
Tim Northover3b0846e2014-05-24 12:50:23 +0000498 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
499
500 setTargetDAGCombine(ISD::ANY_EXTEND);
501 setTargetDAGCombine(ISD::ZERO_EXTEND);
502 setTargetDAGCombine(ISD::SIGN_EXTEND);
503 setTargetDAGCombine(ISD::BITCAST);
504 setTargetDAGCombine(ISD::CONCAT_VECTORS);
505 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000506 if (Subtarget->supportsAddressTopByteIgnored())
507 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000508
509 setTargetDAGCombine(ISD::MUL);
510
511 setTargetDAGCombine(ISD::SELECT);
512 setTargetDAGCombine(ISD::VSELECT);
513
514 setTargetDAGCombine(ISD::INTRINSIC_VOID);
515 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
516 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000517 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000518
519 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
520 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
521 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
522
523 setStackPointerRegisterToSaveRestore(AArch64::SP);
524
525 setSchedulingPreference(Sched::Hybrid);
526
527 // Enable TBZ/TBNZ
528 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000529 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000530
531 setMinFunctionAlignment(2);
532
Tim Northover3b0846e2014-05-24 12:50:23 +0000533 setHasExtractBitsInsn(true);
534
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000535 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
536
Tim Northover3b0846e2014-05-24 12:50:23 +0000537 if (Subtarget->hasNEON()) {
538 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
539 // silliness like this:
540 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
541 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
542 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
543 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
544 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
545 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
546 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
547 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
548 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
549 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
550 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
551 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
552 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
553 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
554 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
555 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
556 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
557 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
558 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
559 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
560 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
561 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
562 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
563 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
564 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
565
566 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
567 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
568 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
569 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
570 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
571
572 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
573
574 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
575 // elements smaller than i32, so promote the input to i32 first.
576 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
577 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
578 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
579 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000580 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
581 // -> v8f16 conversions.
582 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
583 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
584 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
585 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000586 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
587 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
588 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
589 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
590 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000591 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
592 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
593 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
594 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000595
596 // AArch64 doesn't have MUL.2d:
597 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000598 // Custom handling for some quad-vector types to detect MULL.
599 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
600 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
601 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
602
Tim Northover3b0846e2014-05-24 12:50:23 +0000603 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
604 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
605 // Likewise, narrowing and extending vector loads/stores aren't handled
606 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000607 for (MVT VT : MVT::vector_valuetypes()) {
608 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000609
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000610 setOperationAction(ISD::MULHS, VT, Expand);
611 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
612 setOperationAction(ISD::MULHU, VT, Expand);
613 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000614
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000615 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000616
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000617 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000618 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000619 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
620 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
621 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
622 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000623 }
624
625 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000626 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000627 setOperationAction(ISD::FFLOOR, Ty, Legal);
628 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
629 setOperationAction(ISD::FCEIL, Ty, Legal);
630 setOperationAction(ISD::FRINT, Ty, Legal);
631 setOperationAction(ISD::FTRUNC, Ty, Legal);
632 setOperationAction(ISD::FROUND, Ty, Legal);
633 }
634 }
James Molloyf089ab72014-08-06 10:42:18 +0000635
636 // Prefer likely predicted branches to selects on out-of-order cores.
637 if (Subtarget->isCortexA57())
638 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000639}
640
641void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000642 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000643 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
644 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
645
646 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
647 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000648 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000649 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
650 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
651
652 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
653 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
654 }
655
656 // Mark vector float intrinsics as expand.
657 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
658 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
659 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
660 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
661 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
662 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
663 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
664 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
665 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
666 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000667
668 // But we do support custom-lowering for FCOPYSIGN.
669 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000670 }
671
672 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
673 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
674 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
675 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
676 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
677 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
678 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
679 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
680 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
681 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
682 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
683 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
684
685 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
686 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
687 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000688 for (MVT InnerVT : MVT::all_valuetypes())
689 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000690
691 // CNT supports only B element sizes.
692 if (VT != MVT::v8i8 && VT != MVT::v16i8)
693 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
694
695 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
696 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
697 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
698 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
699 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
700
701 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
702 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
703
Hal Finkelcd8664c2015-12-11 23:11:52 +0000704 // [SU][MIN|MAX] are available for all NEON types apart from i64.
James Molloycfb04432015-05-15 16:15:57 +0000705 if (!VT.isFloatingPoint() &&
706 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000707 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
James Molloycfb04432015-05-15 16:15:57 +0000708 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
709
James Molloy63be1982015-08-14 09:08:50 +0000710 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
711 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000712 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
713 ISD::FMINNUM, ISD::FMAXNUM})
James Molloyedf38f02015-08-11 12:06:33 +0000714 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
715
Tim Northover3b0846e2014-05-24 12:50:23 +0000716 if (Subtarget->isLittleEndian()) {
717 for (unsigned im = (unsigned)ISD::PRE_INC;
718 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
719 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
720 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
721 }
722 }
723}
724
725void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
726 addRegisterClass(VT, &AArch64::FPR64RegClass);
727 addTypeForNEON(VT, MVT::v2i32);
728}
729
730void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
731 addRegisterClass(VT, &AArch64::FPR128RegClass);
732 addTypeForNEON(VT, MVT::v4i32);
733}
734
Mehdi Amini44ede332015-07-09 02:09:04 +0000735EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
736 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000737 if (!VT.isVector())
738 return MVT::i32;
739 return VT.changeVectorElementTypeToInteger();
740}
741
742/// computeKnownBitsForTargetNode - Determine which of the bits specified in
743/// Mask are known to be either zero or one and return them in the
744/// KnownZero/KnownOne bitsets.
745void AArch64TargetLowering::computeKnownBitsForTargetNode(
746 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
747 const SelectionDAG &DAG, unsigned Depth) const {
748 switch (Op.getOpcode()) {
749 default:
750 break;
751 case AArch64ISD::CSEL: {
752 APInt KnownZero2, KnownOne2;
753 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
754 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
755 KnownZero &= KnownZero2;
756 KnownOne &= KnownOne2;
757 break;
758 }
759 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000760 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000761 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
762 switch (IntID) {
763 default: return;
764 case Intrinsic::aarch64_ldaxr:
765 case Intrinsic::aarch64_ldxr: {
766 unsigned BitWidth = KnownOne.getBitWidth();
767 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
768 unsigned MemBits = VT.getScalarType().getSizeInBits();
769 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
770 return;
771 }
772 }
773 break;
774 }
775 case ISD::INTRINSIC_WO_CHAIN:
776 case ISD::INTRINSIC_VOID: {
777 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
778 switch (IntNo) {
779 default:
780 break;
781 case Intrinsic::aarch64_neon_umaxv:
782 case Intrinsic::aarch64_neon_uminv: {
783 // Figure out the datatype of the vector operand. The UMINV instruction
784 // will zero extend the result, so we can mark as known zero all the
785 // bits larger than the element datatype. 32-bit or larget doesn't need
786 // this as those are legal types and will be handled by isel directly.
787 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
788 unsigned BitWidth = KnownZero.getBitWidth();
789 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
790 assert(BitWidth >= 8 && "Unexpected width!");
791 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
792 KnownZero |= Mask;
793 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
794 assert(BitWidth >= 16 && "Unexpected width!");
795 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
796 KnownZero |= Mask;
797 }
798 break;
799 } break;
800 }
801 }
802 }
803}
804
Mehdi Aminieaabc512015-07-09 15:12:23 +0000805MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
806 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000807 return MVT::i64;
808}
809
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000810bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
811 unsigned AddrSpace,
812 unsigned Align,
813 bool *Fast) const {
814 if (Subtarget->requiresStrictAlign())
815 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000816
817 // FIXME: This is mostly true for Cyclone, but not necessarily others.
818 if (Fast) {
819 // FIXME: Define an attribute for slow unaligned accesses instead of
820 // relying on the CPU type as a proxy.
821 // On Cyclone, unaligned 128-bit stores are slow.
822 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
823 // See comments in performSTORECombine() for more details about
824 // these conditions.
825
826 // Code that uses clang vector extensions can mark that it
827 // wants unaligned accesses to be treated as fast by
828 // underspecifying alignment to be 1 or 2.
829 Align <= 2 ||
830
831 // Disregard v2i64. Memcpy lowering produces those and splitting
832 // them regresses performance on micro-benchmarks and olden/bh.
833 VT == MVT::v2i64;
834 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000835 return true;
836}
837
Tim Northover3b0846e2014-05-24 12:50:23 +0000838FastISel *
839AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
840 const TargetLibraryInfo *libInfo) const {
841 return AArch64::createFastISel(funcInfo, libInfo);
842}
843
844const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000845 switch ((AArch64ISD::NodeType)Opcode) {
846 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000847 case AArch64ISD::CALL: return "AArch64ISD::CALL";
848 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
849 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
850 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
851 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
852 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
853 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
854 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
855 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
856 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
857 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
858 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000859 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000860 case AArch64ISD::ADC: return "AArch64ISD::ADC";
861 case AArch64ISD::SBC: return "AArch64ISD::SBC";
862 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
863 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
864 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
865 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
866 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000867 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
868 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
869 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000870 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000871 case AArch64ISD::DUP: return "AArch64ISD::DUP";
872 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
873 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
874 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
875 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
876 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
877 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
878 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
879 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
880 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
881 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
882 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
883 case AArch64ISD::BICi: return "AArch64ISD::BICi";
884 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
885 case AArch64ISD::BSL: return "AArch64ISD::BSL";
886 case AArch64ISD::NEG: return "AArch64ISD::NEG";
887 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
888 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
889 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
890 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
891 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
892 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
893 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
894 case AArch64ISD::REV16: return "AArch64ISD::REV16";
895 case AArch64ISD::REV32: return "AArch64ISD::REV32";
896 case AArch64ISD::REV64: return "AArch64ISD::REV64";
897 case AArch64ISD::EXT: return "AArch64ISD::EXT";
898 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
899 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
900 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
901 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
902 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
903 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
904 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
905 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
906 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
907 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
908 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
909 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
910 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
911 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
912 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
913 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
914 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
915 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
916 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
917 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
918 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000919 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
920 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
921 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
922 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
923 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
924 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000925 case AArch64ISD::NOT: return "AArch64ISD::NOT";
926 case AArch64ISD::BIT: return "AArch64ISD::BIT";
927 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
928 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
929 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
930 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
931 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000932 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000933 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
934 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000935 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000936 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
937 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
938 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
939 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
940 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
941 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
942 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
943 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
944 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
945 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
946 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
947 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
948 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
949 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
950 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
951 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
952 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
953 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
954 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
955 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
956 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
957 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
958 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
959 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
960 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
961 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
962 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
963 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
964 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000965 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
966 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000967 }
Matthias Braund04893f2015-05-07 21:33:59 +0000968 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000969}
970
971MachineBasicBlock *
972AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
973 MachineBasicBlock *MBB) const {
974 // We materialise the F128CSEL pseudo-instruction as some control flow and a
975 // phi node:
976
977 // OrigBB:
978 // [... previous instrs leading to comparison ...]
979 // b.ne TrueBB
980 // b EndBB
981 // TrueBB:
982 // ; Fallthrough
983 // EndBB:
984 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
985
Tim Northover3b0846e2014-05-24 12:50:23 +0000986 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000987 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000988 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
989 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000990 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000991
992 unsigned DestReg = MI->getOperand(0).getReg();
993 unsigned IfTrueReg = MI->getOperand(1).getReg();
994 unsigned IfFalseReg = MI->getOperand(2).getReg();
995 unsigned CondCode = MI->getOperand(3).getImm();
996 bool NZCVKilled = MI->getOperand(4).isKill();
997
998 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
999 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1000 MF->insert(It, TrueBB);
1001 MF->insert(It, EndBB);
1002
1003 // Transfer rest of current basic-block to EndBB
1004 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1005 MBB->end());
1006 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1007
1008 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1009 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1010 MBB->addSuccessor(TrueBB);
1011 MBB->addSuccessor(EndBB);
1012
1013 // TrueBB falls through to the end.
1014 TrueBB->addSuccessor(EndBB);
1015
1016 if (!NZCVKilled) {
1017 TrueBB->addLiveIn(AArch64::NZCV);
1018 EndBB->addLiveIn(AArch64::NZCV);
1019 }
1020
1021 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1022 .addReg(IfTrueReg)
1023 .addMBB(TrueBB)
1024 .addReg(IfFalseReg)
1025 .addMBB(MBB);
1026
1027 MI->eraseFromParent();
1028 return EndBB;
1029}
1030
1031MachineBasicBlock *
1032AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1033 MachineBasicBlock *BB) const {
1034 switch (MI->getOpcode()) {
1035 default:
1036#ifndef NDEBUG
1037 MI->dump();
1038#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001039 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001040
1041 case AArch64::F128CSEL:
1042 return EmitF128CSEL(MI, BB);
1043
1044 case TargetOpcode::STACKMAP:
1045 case TargetOpcode::PATCHPOINT:
1046 return emitPatchPoint(MI, BB);
1047 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001048}
1049
1050//===----------------------------------------------------------------------===//
1051// AArch64 Lowering private implementation.
1052//===----------------------------------------------------------------------===//
1053
1054//===----------------------------------------------------------------------===//
1055// Lowering Code
1056//===----------------------------------------------------------------------===//
1057
1058/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1059/// CC
1060static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1061 switch (CC) {
1062 default:
1063 llvm_unreachable("Unknown condition code!");
1064 case ISD::SETNE:
1065 return AArch64CC::NE;
1066 case ISD::SETEQ:
1067 return AArch64CC::EQ;
1068 case ISD::SETGT:
1069 return AArch64CC::GT;
1070 case ISD::SETGE:
1071 return AArch64CC::GE;
1072 case ISD::SETLT:
1073 return AArch64CC::LT;
1074 case ISD::SETLE:
1075 return AArch64CC::LE;
1076 case ISD::SETUGT:
1077 return AArch64CC::HI;
1078 case ISD::SETUGE:
1079 return AArch64CC::HS;
1080 case ISD::SETULT:
1081 return AArch64CC::LO;
1082 case ISD::SETULE:
1083 return AArch64CC::LS;
1084 }
1085}
1086
1087/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1088static void changeFPCCToAArch64CC(ISD::CondCode CC,
1089 AArch64CC::CondCode &CondCode,
1090 AArch64CC::CondCode &CondCode2) {
1091 CondCode2 = AArch64CC::AL;
1092 switch (CC) {
1093 default:
1094 llvm_unreachable("Unknown FP condition!");
1095 case ISD::SETEQ:
1096 case ISD::SETOEQ:
1097 CondCode = AArch64CC::EQ;
1098 break;
1099 case ISD::SETGT:
1100 case ISD::SETOGT:
1101 CondCode = AArch64CC::GT;
1102 break;
1103 case ISD::SETGE:
1104 case ISD::SETOGE:
1105 CondCode = AArch64CC::GE;
1106 break;
1107 case ISD::SETOLT:
1108 CondCode = AArch64CC::MI;
1109 break;
1110 case ISD::SETOLE:
1111 CondCode = AArch64CC::LS;
1112 break;
1113 case ISD::SETONE:
1114 CondCode = AArch64CC::MI;
1115 CondCode2 = AArch64CC::GT;
1116 break;
1117 case ISD::SETO:
1118 CondCode = AArch64CC::VC;
1119 break;
1120 case ISD::SETUO:
1121 CondCode = AArch64CC::VS;
1122 break;
1123 case ISD::SETUEQ:
1124 CondCode = AArch64CC::EQ;
1125 CondCode2 = AArch64CC::VS;
1126 break;
1127 case ISD::SETUGT:
1128 CondCode = AArch64CC::HI;
1129 break;
1130 case ISD::SETUGE:
1131 CondCode = AArch64CC::PL;
1132 break;
1133 case ISD::SETLT:
1134 case ISD::SETULT:
1135 CondCode = AArch64CC::LT;
1136 break;
1137 case ISD::SETLE:
1138 case ISD::SETULE:
1139 CondCode = AArch64CC::LE;
1140 break;
1141 case ISD::SETNE:
1142 case ISD::SETUNE:
1143 CondCode = AArch64CC::NE;
1144 break;
1145 }
1146}
1147
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001148/// Convert a DAG fp condition code to an AArch64 CC.
1149/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1150/// should be AND'ed instead of OR'ed.
1151static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1152 AArch64CC::CondCode &CondCode,
1153 AArch64CC::CondCode &CondCode2) {
1154 CondCode2 = AArch64CC::AL;
1155 switch (CC) {
1156 default:
1157 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1158 assert(CondCode2 == AArch64CC::AL);
1159 break;
1160 case ISD::SETONE:
1161 // (a one b)
1162 // == ((a olt b) || (a ogt b))
1163 // == ((a ord b) && (a une b))
1164 CondCode = AArch64CC::VC;
1165 CondCode2 = AArch64CC::NE;
1166 break;
1167 case ISD::SETUEQ:
1168 // (a ueq b)
1169 // == ((a uno b) || (a oeq b))
1170 // == ((a ule b) && (a uge b))
1171 CondCode = AArch64CC::PL;
1172 CondCode2 = AArch64CC::LE;
1173 break;
1174 }
1175}
1176
Tim Northover3b0846e2014-05-24 12:50:23 +00001177/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1178/// CC usable with the vector instructions. Fewer operations are available
1179/// without a real NZCV register, so we have to use less efficient combinations
1180/// to get the same effect.
1181static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1182 AArch64CC::CondCode &CondCode,
1183 AArch64CC::CondCode &CondCode2,
1184 bool &Invert) {
1185 Invert = false;
1186 switch (CC) {
1187 default:
1188 // Mostly the scalar mappings work fine.
1189 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1190 break;
1191 case ISD::SETUO:
1192 Invert = true; // Fallthrough
1193 case ISD::SETO:
1194 CondCode = AArch64CC::MI;
1195 CondCode2 = AArch64CC::GE;
1196 break;
1197 case ISD::SETUEQ:
1198 case ISD::SETULT:
1199 case ISD::SETULE:
1200 case ISD::SETUGT:
1201 case ISD::SETUGE:
1202 // All of the compare-mask comparisons are ordered, but we can switch
1203 // between the two by a double inversion. E.g. ULE == !OGT.
1204 Invert = true;
1205 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1206 break;
1207 }
1208}
1209
1210static bool isLegalArithImmed(uint64_t C) {
1211 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1212 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1213}
1214
1215static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1216 SDLoc dl, SelectionDAG &DAG) {
1217 EVT VT = LHS.getValueType();
1218
1219 if (VT.isFloatingPoint())
1220 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1221
1222 // The CMP instruction is just an alias for SUBS, and representing it as
1223 // SUBS means that it's possible to get CSE with subtract operations.
1224 // A later phase can perform the optimization of setting the destination
1225 // register to WZR/XZR if it ends up being unused.
1226 unsigned Opcode = AArch64ISD::SUBS;
1227
Artyom Skrobov314ee042015-11-25 19:41:11 +00001228 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001229 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1230 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1231 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1232 // can be set differently by this operation. It comes down to whether
1233 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1234 // everything is fine. If not then the optimization is wrong. Thus general
1235 // comparisons are only valid if op2 != 0.
1236
1237 // So, finally, the only LLVM-native comparisons that don't mention C and V
1238 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1239 // the absence of information about op2.
1240 Opcode = AArch64ISD::ADDS;
1241 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001242 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001243 !isUnsignedIntSetCC(CC)) {
1244 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1245 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1246 // of the signed comparisons.
1247 Opcode = AArch64ISD::ANDS;
1248 RHS = LHS.getOperand(1);
1249 LHS = LHS.getOperand(0);
1250 }
1251
Matthias Braunaf7d7702015-07-16 20:02:37 +00001252 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001253 .getValue(1);
1254}
1255
Matthias Braunaf7d7702015-07-16 20:02:37 +00001256/// \defgroup AArch64CCMP CMP;CCMP matching
1257///
1258/// These functions deal with the formation of CMP;CCMP;... sequences.
1259/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1260/// a comparison. They set the NZCV flags to a predefined value if their
1261/// predicate is false. This allows to express arbitrary conjunctions, for
1262/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1263/// expressed as:
1264/// cmp A
1265/// ccmp B, inv(CB), CA
1266/// check for CB flags
1267///
1268/// In general we can create code for arbitrary "... (and (and A B) C)"
1269/// sequences. We can also implement some "or" expressions, because "(or A B)"
1270/// is equivalent to "not (and (not A) (not B))" and we can implement some
1271/// negation operations:
1272/// We can negate the results of a single comparison by inverting the flags
1273/// used when the predicate fails and inverting the flags tested in the next
1274/// instruction; We can also negate the results of the whole previous
1275/// conditional compare sequence by inverting the flags tested in the next
1276/// instruction. However there is no way to negate the result of a partial
1277/// sequence.
1278///
1279/// Therefore on encountering an "or" expression we can negate the subtree on
1280/// one side and have to be able to push the negate to the leafs of the subtree
1281/// on the other side (see also the comments in code). As complete example:
1282/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1283/// (and (setCC (cmp C)) (setCD (cmp D)))"
1284/// is transformed to
1285/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1286/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1287/// and implemented as:
1288/// cmp C
1289/// ccmp D, inv(CD), CC
1290/// ccmp A, CA, inv(CD)
1291/// ccmp B, CB, inv(CA)
1292/// check for CB flags
1293/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1294/// by conditional compare sequences.
1295/// @{
1296
Geoff Berrye41c2df2015-07-20 22:03:52 +00001297/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001298static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1299 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001300 AArch64CC::CondCode Predicate,
1301 AArch64CC::CondCode OutCC,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001302 SDLoc DL, SelectionDAG &DAG) {
1303 unsigned Opcode = 0;
1304 if (LHS.getValueType().isFloatingPoint())
1305 Opcode = AArch64ISD::FCCMP;
1306 else if (RHS.getOpcode() == ISD::SUB) {
1307 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001308 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001309 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1310 Opcode = AArch64ISD::CCMN;
1311 RHS = RHS.getOperand(1);
1312 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001313 }
1314 if (Opcode == 0)
1315 Opcode = AArch64ISD::CCMP;
1316
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001317 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1318 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1319 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001320 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1321 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1322}
1323
1324/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1325/// CanPushNegate is set to true if we can push a negate operation through
1326/// the tree in a was that we are left with AND operations and negate operations
1327/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1328/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1329/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001330static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001331 unsigned Depth = 0) {
1332 if (!Val.hasOneUse())
1333 return false;
1334 unsigned Opcode = Val->getOpcode();
1335 if (Opcode == ISD::SETCC) {
Matthias Braunfdef49b2016-01-23 04:05:22 +00001336 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001337 return true;
1338 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001339 // Protect against exponential runtime and stack overflow.
1340 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001341 return false;
1342 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1343 SDValue O0 = Val->getOperand(0);
1344 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001345 bool CanNegateL;
1346 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001347 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001348 bool CanNegateR;
1349 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001350 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001351
1352 if (Opcode == ISD::OR) {
1353 // For an OR expression we need to be able to negate at least one side or
1354 // we cannot do the transformation at all.
1355 if (!CanNegateL && !CanNegateR)
1356 return false;
1357 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1358 // can negate the x and y subtrees.
1359 CanNegate = CanNegateL && CanNegateR;
1360 } else {
1361 // If the operands are OR expressions then we finally need to negate their
1362 // outputs, we can only do that for the operand with emitted last by
1363 // negating OutCC, not for both operands.
1364 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1365 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1366 if (NeedsNegOutL && NeedsNegOutR)
1367 return false;
1368 // We cannot negate an AND operation (it would become an OR),
1369 CanNegate = false;
1370 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001371 return true;
1372 }
1373 return false;
1374}
1375
1376/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1377/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1378/// Tries to transform the given i1 producing node @p Val to a series compare
1379/// and conditional compare operations. @returns an NZCV flags producing node
1380/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1381/// transformation was not possible.
1382/// On recursive invocations @p PushNegate may be set to true to have negation
1383/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1384/// for the comparisons in the current subtree; @p Depth limits the search
1385/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001386static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1387 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1388 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001389 // We're at a tree leaf, produce a conditional comparison operation.
1390 unsigned Opcode = Val->getOpcode();
1391 if (Opcode == ISD::SETCC) {
1392 SDValue LHS = Val->getOperand(0);
1393 SDValue RHS = Val->getOperand(1);
1394 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1395 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001396 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001397 CC = getSetCCInverse(CC, isInteger);
1398 SDLoc DL(Val);
1399 // Determine OutCC and handle FP special case.
1400 if (isInteger) {
1401 OutCC = changeIntCCToAArch64CC(CC);
1402 } else {
1403 assert(LHS.getValueType().isFloatingPoint());
1404 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001405 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1406 // Some floating point conditions can't be tested with a single condition
1407 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001408 if (ExtraCC != AArch64CC::AL) {
1409 SDValue ExtraCmp;
1410 if (!CCOp.getNode())
1411 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001412 else
1413 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1414 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001415 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001416 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001417 }
1418 }
1419
1420 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001421 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001422 return emitComparison(LHS, RHS, CC, DL, DAG);
1423 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001424 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001425 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001426 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001427 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1428 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001429
1430 // Check if both sides can be transformed.
1431 SDValue LHS = Val->getOperand(0);
1432 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001433
Matthias Braunfdef49b2016-01-23 04:05:22 +00001434 // In case of an OR we need to negate our operands and the result.
1435 // (A v B) <=> not(not(A) ^ not(B))
1436 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001437 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001438 // predicate flags giving us a free negation for one side. The other side
1439 // must be negatable by itself.
1440 if (NegateOpsAndResult) {
1441 // See which side we can negate.
1442 bool CanNegateL;
1443 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1444 assert(isValidL && "Valid conjunction/disjunction tree");
1445 (void)isValidL;
1446
1447#ifndef NDEBUG
1448 bool CanNegateR;
1449 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1450 assert(isValidR && "Valid conjunction/disjunction tree");
1451 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1452#endif
1453
1454 // Order the side which we cannot negate to RHS so we can emit it first.
1455 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001456 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001457 } else {
1458 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001459 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001460 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001461 // Order the side where we need to negate the output flags to RHS so it
1462 // gets emitted first.
1463 if (NeedsNegOutL)
1464 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001465 }
1466
1467 // Emit RHS. If we want to negate the tree we only need to push a negate
1468 // through if we are already in a PushNegate case, otherwise we can negate
1469 // the "flags to test" afterwards.
1470 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001471 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1472 CCOp, Predicate);
1473 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001474 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001475 // Emit LHS. We may need to negate it.
1476 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1477 NegateOpsAndResult, CmpR,
1478 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001479 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001480 // (or absorb the Negate parameter).
1481 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001482 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1483 return CmpL;
1484}
1485
Matthias Braunfdef49b2016-01-23 04:05:22 +00001486/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1487/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1488/// \see emitConjunctionDisjunctionTreeRec().
1489static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1490 AArch64CC::CondCode &OutCC) {
1491 bool CanNegate;
1492 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1493 return SDValue();
1494
1495 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1496 AArch64CC::AL);
1497}
1498
Matthias Braunaf7d7702015-07-16 20:02:37 +00001499/// @}
1500
Tim Northover3b0846e2014-05-24 12:50:23 +00001501static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1502 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1503 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1504 EVT VT = RHS.getValueType();
1505 uint64_t C = RHSC->getZExtValue();
1506 if (!isLegalArithImmed(C)) {
1507 // Constant does not fit, try adjusting it by one?
1508 switch (CC) {
1509 default:
1510 break;
1511 case ISD::SETLT:
1512 case ISD::SETGE:
1513 if ((VT == MVT::i32 && C != 0x80000000 &&
1514 isLegalArithImmed((uint32_t)(C - 1))) ||
1515 (VT == MVT::i64 && C != 0x80000000ULL &&
1516 isLegalArithImmed(C - 1ULL))) {
1517 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1518 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001519 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001520 }
1521 break;
1522 case ISD::SETULT:
1523 case ISD::SETUGE:
1524 if ((VT == MVT::i32 && C != 0 &&
1525 isLegalArithImmed((uint32_t)(C - 1))) ||
1526 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1527 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1528 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001529 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001530 }
1531 break;
1532 case ISD::SETLE:
1533 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001534 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001535 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001536 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001537 isLegalArithImmed(C + 1ULL))) {
1538 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1539 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001540 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001541 }
1542 break;
1543 case ISD::SETULE:
1544 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001545 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001546 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001547 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001548 isLegalArithImmed(C + 1ULL))) {
1549 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1550 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001551 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001552 }
1553 break;
1554 }
1555 }
1556 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001557 SDValue Cmp;
1558 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001559 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001560 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1561
1562 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1563 // For the i8 operand, the largest immediate is 255, so this can be easily
1564 // encoded in the compare instruction. For the i16 operand, however, the
1565 // largest immediate cannot be encoded in the compare.
1566 // Therefore, use a sign extending load and cmn to avoid materializing the
1567 // -1 constant. For example,
1568 // movz w1, #65535
1569 // ldrh w0, [x0, #0]
1570 // cmp w0, w1
1571 // >
1572 // ldrsh w0, [x0, #0]
1573 // cmn w0, #1
1574 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1575 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001576 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001577 // transformation is profitable.
1578 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1579 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1580 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1581 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1582 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1583 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1584 SDValue SExt =
1585 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1586 DAG.getValueType(MVT::i16));
1587 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1588 RHS.getValueType()),
1589 CC, dl, DAG);
1590 AArch64CC = changeIntCCToAArch64CC(CC);
1591 }
1592 }
1593
1594 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1595 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1596 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1597 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001598 }
1599 }
1600 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001601
1602 if (!Cmp) {
1603 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1604 AArch64CC = changeIntCCToAArch64CC(CC);
1605 }
1606 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001607 return Cmp;
1608}
1609
Balaram Makam92431702016-02-01 19:13:07 +00001610// Attempt to form conditional compare sequences for and/or trees
1611// with setcc leafs.
1612static SDValue tryLowerToAArch64Cmp(SDValue Op, SelectionDAG &DAG) {
1613 SDValue LHS = Op.getOperand(0);
1614 SDValue RHS = Op.getOperand(1);
1615 if ((LHS.getOpcode() != ISD::SETCC) || (RHS.getOpcode() != ISD::SETCC))
1616 return Op;
1617
1618 bool CanNegate;
1619 if (!isConjunctionDisjunctionTree(Op, CanNegate))
1620 return SDValue();
1621
1622 EVT VT = Op.getValueType();
1623 SDLoc DL(Op);
1624 SDValue TVal = DAG.getConstant(1, DL, VT);
1625 SDValue FVal = DAG.getConstant(0, DL, VT);
1626 SDValue CCVal;
1627 SDValue Cmp = getAArch64Cmp(Op, FVal, ISD::SETEQ, CCVal, DAG, DL);
1628 return DAG.getNode(AArch64ISD::CSEL, DL, VT, FVal, TVal, CCVal, Cmp);
1629}
1630
Tim Northover3b0846e2014-05-24 12:50:23 +00001631static std::pair<SDValue, SDValue>
1632getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1633 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1634 "Unsupported value type");
1635 SDValue Value, Overflow;
1636 SDLoc DL(Op);
1637 SDValue LHS = Op.getOperand(0);
1638 SDValue RHS = Op.getOperand(1);
1639 unsigned Opc = 0;
1640 switch (Op.getOpcode()) {
1641 default:
1642 llvm_unreachable("Unknown overflow instruction!");
1643 case ISD::SADDO:
1644 Opc = AArch64ISD::ADDS;
1645 CC = AArch64CC::VS;
1646 break;
1647 case ISD::UADDO:
1648 Opc = AArch64ISD::ADDS;
1649 CC = AArch64CC::HS;
1650 break;
1651 case ISD::SSUBO:
1652 Opc = AArch64ISD::SUBS;
1653 CC = AArch64CC::VS;
1654 break;
1655 case ISD::USUBO:
1656 Opc = AArch64ISD::SUBS;
1657 CC = AArch64CC::LO;
1658 break;
1659 // Multiply needs a little bit extra work.
1660 case ISD::SMULO:
1661 case ISD::UMULO: {
1662 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001663 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001664 if (Op.getValueType() == MVT::i32) {
1665 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1666 // For a 32 bit multiply with overflow check we want the instruction
1667 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1668 // need to generate the following pattern:
1669 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1670 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1671 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1672 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1673 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001674 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001675 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1676 // operation. We need to clear out the upper 32 bits, because we used a
1677 // widening multiply that wrote all 64 bits. In the end this should be a
1678 // noop.
1679 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1680 if (IsSigned) {
1681 // The signed overflow check requires more than just a simple check for
1682 // any bit set in the upper 32 bits of the result. These bits could be
1683 // just the sign bits of a negative number. To perform the overflow
1684 // check we have to arithmetic shift right the 32nd bit of the result by
1685 // 31 bits. Then we compare the result to the upper 32 bits.
1686 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001687 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001688 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1689 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001690 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001691 // It is important that LowerBits is last, otherwise the arithmetic
1692 // shift will not be folded into the compare (SUBS).
1693 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1694 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1695 .getValue(1);
1696 } else {
1697 // The overflow check for unsigned multiply is easy. We only need to
1698 // check if any of the upper 32 bits are set. This can be done with a
1699 // CMP (shifted register). For that we need to generate the following
1700 // pattern:
1701 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1702 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001703 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001704 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1705 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001706 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1707 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001708 UpperBits).getValue(1);
1709 }
1710 break;
1711 }
1712 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1713 // For the 64 bit multiply
1714 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1715 if (IsSigned) {
1716 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1717 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001718 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001719 // It is important that LowerBits is last, otherwise the arithmetic
1720 // shift will not be folded into the compare (SUBS).
1721 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1722 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1723 .getValue(1);
1724 } else {
1725 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1726 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1727 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001728 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1729 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001730 UpperBits).getValue(1);
1731 }
1732 break;
1733 }
1734 } // switch (...)
1735
1736 if (Opc) {
1737 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1738
1739 // Emit the AArch64 operation with overflow check.
1740 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1741 Overflow = Value.getValue(1);
1742 }
1743 return std::make_pair(Value, Overflow);
1744}
1745
1746SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1747 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001748 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001749 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001750}
1751
Balaram Makam92431702016-02-01 19:13:07 +00001752SDValue AArch64TargetLowering::LowerAND(SDValue Op, SelectionDAG &DAG) const {
1753 if (Op.getValueType().isVector())
1754 return LowerVectorAND(Op, DAG);
1755 return tryLowerToAArch64Cmp(Op, DAG);
1756}
1757
1758SDValue AArch64TargetLowering::LowerOR(SDValue Op, SelectionDAG &DAG) const {
1759 if (Op.getValueType().isVector())
1760 return LowerVectorOR(Op, DAG);
1761 return tryLowerToAArch64Cmp(Op, DAG);
1762}
1763
Tim Northover3b0846e2014-05-24 12:50:23 +00001764static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1765 SDValue Sel = Op.getOperand(0);
1766 SDValue Other = Op.getOperand(1);
1767
1768 // If neither operand is a SELECT_CC, give up.
1769 if (Sel.getOpcode() != ISD::SELECT_CC)
1770 std::swap(Sel, Other);
1771 if (Sel.getOpcode() != ISD::SELECT_CC)
1772 return Op;
1773
1774 // The folding we want to perform is:
1775 // (xor x, (select_cc a, b, cc, 0, -1) )
1776 // -->
1777 // (csel x, (xor x, -1), cc ...)
1778 //
1779 // The latter will get matched to a CSINV instruction.
1780
1781 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1782 SDValue LHS = Sel.getOperand(0);
1783 SDValue RHS = Sel.getOperand(1);
1784 SDValue TVal = Sel.getOperand(2);
1785 SDValue FVal = Sel.getOperand(3);
1786 SDLoc dl(Sel);
1787
1788 // FIXME: This could be generalized to non-integer comparisons.
1789 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1790 return Op;
1791
1792 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1793 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1794
Eric Christopher572e03a2015-06-19 01:53:21 +00001795 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001796 if (!CFVal || !CTVal)
1797 return Op;
1798
1799 // We can commute the SELECT_CC by inverting the condition. This
1800 // might be needed to make this fit into a CSINV pattern.
1801 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1802 std::swap(TVal, FVal);
1803 std::swap(CTVal, CFVal);
1804 CC = ISD::getSetCCInverse(CC, true);
1805 }
1806
1807 // If the constants line up, perform the transform!
1808 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1809 SDValue CCVal;
1810 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1811
1812 FVal = Other;
1813 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001814 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001815
1816 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1817 CCVal, Cmp);
1818 }
1819
1820 return Op;
1821}
1822
1823static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1824 EVT VT = Op.getValueType();
1825
1826 // Let legalize expand this if it isn't a legal type yet.
1827 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1828 return SDValue();
1829
1830 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1831
1832 unsigned Opc;
1833 bool ExtraOp = false;
1834 switch (Op.getOpcode()) {
1835 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001836 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001837 case ISD::ADDC:
1838 Opc = AArch64ISD::ADDS;
1839 break;
1840 case ISD::SUBC:
1841 Opc = AArch64ISD::SUBS;
1842 break;
1843 case ISD::ADDE:
1844 Opc = AArch64ISD::ADCS;
1845 ExtraOp = true;
1846 break;
1847 case ISD::SUBE:
1848 Opc = AArch64ISD::SBCS;
1849 ExtraOp = true;
1850 break;
1851 }
1852
1853 if (!ExtraOp)
1854 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1855 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1856 Op.getOperand(2));
1857}
1858
1859static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1860 // Let legalize expand this if it isn't a legal type yet.
1861 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1862 return SDValue();
1863
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001864 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001865 AArch64CC::CondCode CC;
1866 // The actual operation that sets the overflow or carry flag.
1867 SDValue Value, Overflow;
1868 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1869
1870 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001871 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1872 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001873
1874 // We use an inverted condition, because the conditional select is inverted
1875 // too. This will allow it to be selected to a single instruction:
1876 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001877 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1878 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001879 CCVal, Overflow);
1880
1881 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001882 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001883}
1884
1885// Prefetch operands are:
1886// 1: Address to prefetch
1887// 2: bool isWrite
1888// 3: int locality (0 = no locality ... 3 = extreme locality)
1889// 4: bool isDataCache
1890static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1891 SDLoc DL(Op);
1892 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1893 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001894 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001895
1896 bool IsStream = !Locality;
1897 // When the locality number is set
1898 if (Locality) {
1899 // The front-end should have filtered out the out-of-range values
1900 assert(Locality <= 3 && "Prefetch locality out-of-range");
1901 // The locality degree is the opposite of the cache speed.
1902 // Put the number the other way around.
1903 // The encoding starts at 0 for level 1
1904 Locality = 3 - Locality;
1905 }
1906
1907 // built the mask value encoding the expected behavior.
1908 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001909 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001910 (Locality << 1) | // Cache level bits
1911 (unsigned)IsStream; // Stream bit
1912 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001913 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001914}
1915
1916SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1917 SelectionDAG &DAG) const {
1918 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1919
1920 RTLIB::Libcall LC;
1921 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1922
1923 return LowerF128Call(Op, DAG, LC);
1924}
1925
1926SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1927 SelectionDAG &DAG) const {
1928 if (Op.getOperand(0).getValueType() != MVT::f128) {
1929 // It's legal except when f128 is involved
1930 return Op;
1931 }
1932
1933 RTLIB::Libcall LC;
1934 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1935
1936 // FP_ROUND node has a second operand indicating whether it is known to be
1937 // precise. That doesn't take part in the LibCall so we can't directly use
1938 // LowerF128Call.
1939 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001940 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1941 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001942}
1943
1944static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1945 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1946 // Any additional optimization in this function should be recorded
1947 // in the cost tables.
1948 EVT InVT = Op.getOperand(0).getValueType();
1949 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001950 unsigned NumElts = InVT.getVectorNumElements();
1951
1952 // f16 vectors are promoted to f32 before a conversion.
1953 if (InVT.getVectorElementType() == MVT::f16) {
1954 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1955 SDLoc dl(Op);
1956 return DAG.getNode(
1957 Op.getOpcode(), dl, Op.getValueType(),
1958 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1959 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001960
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001961 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001962 SDLoc dl(Op);
1963 SDValue Cv =
1964 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1965 Op.getOperand(0));
1966 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001967 }
1968
1969 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001970 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001971 MVT ExtVT =
1972 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1973 VT.getVectorNumElements());
1974 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001975 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1976 }
1977
1978 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001979 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001980}
1981
1982SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1983 SelectionDAG &DAG) const {
1984 if (Op.getOperand(0).getValueType().isVector())
1985 return LowerVectorFP_TO_INT(Op, DAG);
1986
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001987 // f16 conversions are promoted to f32.
1988 if (Op.getOperand(0).getValueType() == MVT::f16) {
1989 SDLoc dl(Op);
1990 return DAG.getNode(
1991 Op.getOpcode(), dl, Op.getValueType(),
1992 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1993 }
1994
Tim Northover3b0846e2014-05-24 12:50:23 +00001995 if (Op.getOperand(0).getValueType() != MVT::f128) {
1996 // It's legal except when f128 is involved
1997 return Op;
1998 }
1999
2000 RTLIB::Libcall LC;
2001 if (Op.getOpcode() == ISD::FP_TO_SINT)
2002 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2003 else
2004 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2005
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002006 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002007 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002008}
2009
2010static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2011 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2012 // Any additional optimization in this function should be recorded
2013 // in the cost tables.
2014 EVT VT = Op.getValueType();
2015 SDLoc dl(Op);
2016 SDValue In = Op.getOperand(0);
2017 EVT InVT = In.getValueType();
2018
Tim Northoveref0d7602014-06-15 09:27:06 +00002019 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2020 MVT CastVT =
2021 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2022 InVT.getVectorNumElements());
2023 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002024 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002025 }
2026
Tim Northoveref0d7602014-06-15 09:27:06 +00002027 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2028 unsigned CastOpc =
2029 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2030 EVT CastVT = VT.changeVectorElementTypeToInteger();
2031 In = DAG.getNode(CastOpc, dl, CastVT, In);
2032 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002033 }
2034
Tim Northoveref0d7602014-06-15 09:27:06 +00002035 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002036}
2037
2038SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2039 SelectionDAG &DAG) const {
2040 if (Op.getValueType().isVector())
2041 return LowerVectorINT_TO_FP(Op, DAG);
2042
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002043 // f16 conversions are promoted to f32.
2044 if (Op.getValueType() == MVT::f16) {
2045 SDLoc dl(Op);
2046 return DAG.getNode(
2047 ISD::FP_ROUND, dl, MVT::f16,
2048 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002049 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002050 }
2051
Tim Northover3b0846e2014-05-24 12:50:23 +00002052 // i128 conversions are libcalls.
2053 if (Op.getOperand(0).getValueType() == MVT::i128)
2054 return SDValue();
2055
2056 // Other conversions are legal, unless it's to the completely software-based
2057 // fp128.
2058 if (Op.getValueType() != MVT::f128)
2059 return Op;
2060
2061 RTLIB::Libcall LC;
2062 if (Op.getOpcode() == ISD::SINT_TO_FP)
2063 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2064 else
2065 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2066
2067 return LowerF128Call(Op, DAG, LC);
2068}
2069
2070SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2071 SelectionDAG &DAG) const {
2072 // For iOS, we want to call an alternative entry point: __sincos_stret,
2073 // which returns the values in two S / D registers.
2074 SDLoc dl(Op);
2075 SDValue Arg = Op.getOperand(0);
2076 EVT ArgVT = Arg.getValueType();
2077 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2078
2079 ArgListTy Args;
2080 ArgListEntry Entry;
2081
2082 Entry.Node = Arg;
2083 Entry.Ty = ArgTy;
2084 Entry.isSExt = false;
2085 Entry.isZExt = false;
2086 Args.push_back(Entry);
2087
2088 const char *LibcallName =
2089 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002090 SDValue Callee =
2091 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002092
Reid Kleckner343c3952014-11-20 23:51:47 +00002093 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002094 TargetLowering::CallLoweringInfo CLI(DAG);
2095 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00002096 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002097
2098 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2099 return CallResult.first;
2100}
2101
Tim Northoverf8bfe212014-07-18 13:07:05 +00002102static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2103 if (Op.getValueType() != MVT::f16)
2104 return SDValue();
2105
2106 assert(Op.getOperand(0).getValueType() == MVT::i16);
2107 SDLoc DL(Op);
2108
2109 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2110 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2111 return SDValue(
2112 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002113 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002114 0);
2115}
2116
Chad Rosierd9d0f862014-10-08 02:31:24 +00002117static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2118 if (OrigVT.getSizeInBits() >= 64)
2119 return OrigVT;
2120
2121 assert(OrigVT.isSimple() && "Expecting a simple value type");
2122
2123 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2124 switch (OrigSimpleTy) {
2125 default: llvm_unreachable("Unexpected Vector Type");
2126 case MVT::v2i8:
2127 case MVT::v2i16:
2128 return MVT::v2i32;
2129 case MVT::v4i8:
2130 return MVT::v4i16;
2131 }
2132}
2133
2134static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2135 const EVT &OrigTy,
2136 const EVT &ExtTy,
2137 unsigned ExtOpcode) {
2138 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2139 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2140 // 64-bits we need to insert a new extension so that it will be 64-bits.
2141 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2142 if (OrigTy.getSizeInBits() >= 64)
2143 return N;
2144
2145 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2146 EVT NewVT = getExtensionTo64Bits(OrigTy);
2147
2148 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2149}
2150
2151static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2152 bool isSigned) {
2153 EVT VT = N->getValueType(0);
2154
2155 if (N->getOpcode() != ISD::BUILD_VECTOR)
2156 return false;
2157
Pete Cooper3af9a252015-06-26 18:17:36 +00002158 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002159 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2160 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2161 unsigned HalfSize = EltSize / 2;
2162 if (isSigned) {
2163 if (!isIntN(HalfSize, C->getSExtValue()))
2164 return false;
2165 } else {
2166 if (!isUIntN(HalfSize, C->getZExtValue()))
2167 return false;
2168 }
2169 continue;
2170 }
2171 return false;
2172 }
2173
2174 return true;
2175}
2176
2177static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2178 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2179 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2180 N->getOperand(0)->getValueType(0),
2181 N->getValueType(0),
2182 N->getOpcode());
2183
2184 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2185 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002186 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002187 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2188 unsigned NumElts = VT.getVectorNumElements();
2189 MVT TruncVT = MVT::getIntegerVT(EltSize);
2190 SmallVector<SDValue, 8> Ops;
2191 for (unsigned i = 0; i != NumElts; ++i) {
2192 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2193 const APInt &CInt = C->getAPIntValue();
2194 // Element types smaller than 32 bits are not legal, so use i32 elements.
2195 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002196 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002197 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002198 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00002199 MVT::getVectorVT(TruncVT, NumElts), Ops);
2200}
2201
2202static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2203 if (N->getOpcode() == ISD::SIGN_EXTEND)
2204 return true;
2205 if (isExtendedBUILD_VECTOR(N, DAG, true))
2206 return true;
2207 return false;
2208}
2209
2210static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2211 if (N->getOpcode() == ISD::ZERO_EXTEND)
2212 return true;
2213 if (isExtendedBUILD_VECTOR(N, DAG, false))
2214 return true;
2215 return false;
2216}
2217
2218static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2219 unsigned Opcode = N->getOpcode();
2220 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2221 SDNode *N0 = N->getOperand(0).getNode();
2222 SDNode *N1 = N->getOperand(1).getNode();
2223 return N0->hasOneUse() && N1->hasOneUse() &&
2224 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2225 }
2226 return false;
2227}
2228
2229static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2230 unsigned Opcode = N->getOpcode();
2231 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2232 SDNode *N0 = N->getOperand(0).getNode();
2233 SDNode *N1 = N->getOperand(1).getNode();
2234 return N0->hasOneUse() && N1->hasOneUse() &&
2235 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2236 }
2237 return false;
2238}
2239
2240static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2241 // Multiplications are only custom-lowered for 128-bit vectors so that
2242 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2243 EVT VT = Op.getValueType();
2244 assert(VT.is128BitVector() && VT.isInteger() &&
2245 "unexpected type for custom-lowering ISD::MUL");
2246 SDNode *N0 = Op.getOperand(0).getNode();
2247 SDNode *N1 = Op.getOperand(1).getNode();
2248 unsigned NewOpc = 0;
2249 bool isMLA = false;
2250 bool isN0SExt = isSignExtended(N0, DAG);
2251 bool isN1SExt = isSignExtended(N1, DAG);
2252 if (isN0SExt && isN1SExt)
2253 NewOpc = AArch64ISD::SMULL;
2254 else {
2255 bool isN0ZExt = isZeroExtended(N0, DAG);
2256 bool isN1ZExt = isZeroExtended(N1, DAG);
2257 if (isN0ZExt && isN1ZExt)
2258 NewOpc = AArch64ISD::UMULL;
2259 else if (isN1SExt || isN1ZExt) {
2260 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2261 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2262 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2263 NewOpc = AArch64ISD::SMULL;
2264 isMLA = true;
2265 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2266 NewOpc = AArch64ISD::UMULL;
2267 isMLA = true;
2268 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2269 std::swap(N0, N1);
2270 NewOpc = AArch64ISD::UMULL;
2271 isMLA = true;
2272 }
2273 }
2274
2275 if (!NewOpc) {
2276 if (VT == MVT::v2i64)
2277 // Fall through to expand this. It is not legal.
2278 return SDValue();
2279 else
2280 // Other vector multiplications are legal.
2281 return Op;
2282 }
2283 }
2284
2285 // Legalize to a S/UMULL instruction
2286 SDLoc DL(Op);
2287 SDValue Op0;
2288 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2289 if (!isMLA) {
2290 Op0 = skipExtensionForVectorMULL(N0, DAG);
2291 assert(Op0.getValueType().is64BitVector() &&
2292 Op1.getValueType().is64BitVector() &&
2293 "unexpected types for extended operands to VMULL");
2294 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2295 }
2296 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2297 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2298 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2299 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2300 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2301 EVT Op1VT = Op1.getValueType();
2302 return DAG.getNode(N0->getOpcode(), DL, VT,
2303 DAG.getNode(NewOpc, DL, VT,
2304 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2305 DAG.getNode(NewOpc, DL, VT,
2306 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2307}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002308
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002309SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2310 SelectionDAG &DAG) const {
2311 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2312 SDLoc dl(Op);
2313 switch (IntNo) {
2314 default: return SDValue(); // Don't custom lower most intrinsics.
2315 case Intrinsic::aarch64_thread_pointer: {
2316 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2317 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2318 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002319 case Intrinsic::aarch64_neon_smax:
2320 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2321 Op.getOperand(1), Op.getOperand(2));
2322 case Intrinsic::aarch64_neon_umax:
2323 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2324 Op.getOperand(1), Op.getOperand(2));
2325 case Intrinsic::aarch64_neon_smin:
2326 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2327 Op.getOperand(1), Op.getOperand(2));
2328 case Intrinsic::aarch64_neon_umin:
2329 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2330 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002331 }
2332}
2333
Tim Northover3b0846e2014-05-24 12:50:23 +00002334SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2335 SelectionDAG &DAG) const {
2336 switch (Op.getOpcode()) {
2337 default:
2338 llvm_unreachable("unimplemented operand");
2339 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002340 case ISD::BITCAST:
2341 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002342 case ISD::GlobalAddress:
2343 return LowerGlobalAddress(Op, DAG);
2344 case ISD::GlobalTLSAddress:
2345 return LowerGlobalTLSAddress(Op, DAG);
2346 case ISD::SETCC:
2347 return LowerSETCC(Op, DAG);
2348 case ISD::BR_CC:
2349 return LowerBR_CC(Op, DAG);
2350 case ISD::SELECT:
2351 return LowerSELECT(Op, DAG);
2352 case ISD::SELECT_CC:
2353 return LowerSELECT_CC(Op, DAG);
2354 case ISD::JumpTable:
2355 return LowerJumpTable(Op, DAG);
2356 case ISD::ConstantPool:
2357 return LowerConstantPool(Op, DAG);
2358 case ISD::BlockAddress:
2359 return LowerBlockAddress(Op, DAG);
2360 case ISD::VASTART:
2361 return LowerVASTART(Op, DAG);
2362 case ISD::VACOPY:
2363 return LowerVACOPY(Op, DAG);
2364 case ISD::VAARG:
2365 return LowerVAARG(Op, DAG);
2366 case ISD::ADDC:
2367 case ISD::ADDE:
2368 case ISD::SUBC:
2369 case ISD::SUBE:
2370 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2371 case ISD::SADDO:
2372 case ISD::UADDO:
2373 case ISD::SSUBO:
2374 case ISD::USUBO:
2375 case ISD::SMULO:
2376 case ISD::UMULO:
2377 return LowerXALUO(Op, DAG);
2378 case ISD::FADD:
2379 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2380 case ISD::FSUB:
2381 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2382 case ISD::FMUL:
2383 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2384 case ISD::FDIV:
2385 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2386 case ISD::FP_ROUND:
2387 return LowerFP_ROUND(Op, DAG);
2388 case ISD::FP_EXTEND:
2389 return LowerFP_EXTEND(Op, DAG);
2390 case ISD::FRAMEADDR:
2391 return LowerFRAMEADDR(Op, DAG);
2392 case ISD::RETURNADDR:
2393 return LowerRETURNADDR(Op, DAG);
2394 case ISD::INSERT_VECTOR_ELT:
2395 return LowerINSERT_VECTOR_ELT(Op, DAG);
2396 case ISD::EXTRACT_VECTOR_ELT:
2397 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2398 case ISD::BUILD_VECTOR:
2399 return LowerBUILD_VECTOR(Op, DAG);
2400 case ISD::VECTOR_SHUFFLE:
2401 return LowerVECTOR_SHUFFLE(Op, DAG);
2402 case ISD::EXTRACT_SUBVECTOR:
2403 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2404 case ISD::SRA:
2405 case ISD::SRL:
2406 case ISD::SHL:
2407 return LowerVectorSRA_SRL_SHL(Op, DAG);
2408 case ISD::SHL_PARTS:
2409 return LowerShiftLeftParts(Op, DAG);
2410 case ISD::SRL_PARTS:
2411 case ISD::SRA_PARTS:
2412 return LowerShiftRightParts(Op, DAG);
2413 case ISD::CTPOP:
2414 return LowerCTPOP(Op, DAG);
2415 case ISD::FCOPYSIGN:
2416 return LowerFCOPYSIGN(Op, DAG);
2417 case ISD::AND:
Balaram Makam92431702016-02-01 19:13:07 +00002418 return LowerAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002419 case ISD::OR:
Balaram Makam92431702016-02-01 19:13:07 +00002420 return LowerOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002421 case ISD::XOR:
2422 return LowerXOR(Op, DAG);
2423 case ISD::PREFETCH:
2424 return LowerPREFETCH(Op, DAG);
2425 case ISD::SINT_TO_FP:
2426 case ISD::UINT_TO_FP:
2427 return LowerINT_TO_FP(Op, DAG);
2428 case ISD::FP_TO_SINT:
2429 case ISD::FP_TO_UINT:
2430 return LowerFP_TO_INT(Op, DAG);
2431 case ISD::FSINCOS:
2432 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002433 case ISD::MUL:
2434 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002435 case ISD::INTRINSIC_WO_CHAIN:
2436 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002437 }
2438}
2439
Tim Northover3b0846e2014-05-24 12:50:23 +00002440//===----------------------------------------------------------------------===//
2441// Calling Convention Implementation
2442//===----------------------------------------------------------------------===//
2443
2444#include "AArch64GenCallingConv.inc"
2445
Robin Morisset039781e2014-08-29 21:53:01 +00002446/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002447CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2448 bool IsVarArg) const {
2449 switch (CC) {
2450 default:
2451 llvm_unreachable("Unsupported calling convention.");
2452 case CallingConv::WebKit_JS:
2453 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002454 case CallingConv::GHC:
2455 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002456 case CallingConv::C:
2457 case CallingConv::Fast:
2458 if (!Subtarget->isTargetDarwin())
2459 return CC_AArch64_AAPCS;
2460 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2461 }
2462}
2463
2464SDValue AArch64TargetLowering::LowerFormalArguments(
2465 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2466 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2467 SmallVectorImpl<SDValue> &InVals) const {
2468 MachineFunction &MF = DAG.getMachineFunction();
2469 MachineFrameInfo *MFI = MF.getFrameInfo();
2470
2471 // Assign locations to all of the incoming arguments.
2472 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002473 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2474 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002475
2476 // At this point, Ins[].VT may already be promoted to i32. To correctly
2477 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2478 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2479 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2480 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2481 // LocVT.
2482 unsigned NumArgs = Ins.size();
2483 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2484 unsigned CurArgIdx = 0;
2485 for (unsigned i = 0; i != NumArgs; ++i) {
2486 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002487 if (Ins[i].isOrigArg()) {
2488 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2489 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002490
Andrew Trick05938a52015-02-16 18:10:47 +00002491 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002492 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2493 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002494 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2495 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2496 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2497 ValVT = MVT::i8;
2498 else if (ActualMVT == MVT::i16)
2499 ValVT = MVT::i16;
2500 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002501 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2502 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002503 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002504 assert(!Res && "Call operand has unhandled type");
2505 (void)Res;
2506 }
2507 assert(ArgLocs.size() == Ins.size());
2508 SmallVector<SDValue, 16> ArgValues;
2509 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2510 CCValAssign &VA = ArgLocs[i];
2511
2512 if (Ins[i].Flags.isByVal()) {
2513 // Byval is used for HFAs in the PCS, but the system should work in a
2514 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002515 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002516 int Size = Ins[i].Flags.getByValSize();
2517 unsigned NumRegs = (Size + 7) / 8;
2518
2519 // FIXME: This works on big-endian for composite byvals, which are the common
2520 // case. It should also work for fundamental types too.
2521 unsigned FrameIdx =
2522 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002523 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002524 InVals.push_back(FrameIdxN);
2525
2526 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002527 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002528
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002529 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002530 // Arguments stored in registers.
2531 EVT RegVT = VA.getLocVT();
2532
2533 SDValue ArgValue;
2534 const TargetRegisterClass *RC;
2535
2536 if (RegVT == MVT::i32)
2537 RC = &AArch64::GPR32RegClass;
2538 else if (RegVT == MVT::i64)
2539 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002540 else if (RegVT == MVT::f16)
2541 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002542 else if (RegVT == MVT::f32)
2543 RC = &AArch64::FPR32RegClass;
2544 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2545 RC = &AArch64::FPR64RegClass;
2546 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2547 RC = &AArch64::FPR128RegClass;
2548 else
2549 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2550
2551 // Transform the arguments in physical registers into virtual ones.
2552 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2553 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2554
2555 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2556 // to 64 bits. Insert an assert[sz]ext to capture this, then
2557 // truncate to the right size.
2558 switch (VA.getLocInfo()) {
2559 default:
2560 llvm_unreachable("Unknown loc info!");
2561 case CCValAssign::Full:
2562 break;
2563 case CCValAssign::BCvt:
2564 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2565 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002566 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002567 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002568 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002569 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2570 // nodes after our lowering.
2571 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002572 break;
2573 }
2574
2575 InVals.push_back(ArgValue);
2576
2577 } else { // VA.isRegLoc()
2578 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2579 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002580 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002581
2582 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002583 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2584 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002585 BEAlign = 8 - ArgSize;
2586
2587 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2588
2589 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002590 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002591 SDValue ArgValue;
2592
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002593 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002594 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002595 MVT MemVT = VA.getValVT();
2596
Tim Northover47e003c2014-05-26 17:21:53 +00002597 switch (VA.getLocInfo()) {
2598 default:
2599 break;
Tim Northover6890add2014-06-03 13:54:53 +00002600 case CCValAssign::BCvt:
2601 MemVT = VA.getLocVT();
2602 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002603 case CCValAssign::SExt:
2604 ExtType = ISD::SEXTLOAD;
2605 break;
2606 case CCValAssign::ZExt:
2607 ExtType = ISD::ZEXTLOAD;
2608 break;
2609 case CCValAssign::AExt:
2610 ExtType = ISD::EXTLOAD;
2611 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002612 }
2613
Alex Lorenze40c8a22015-08-11 23:09:45 +00002614 ArgValue = DAG.getExtLoad(
2615 ExtType, DL, VA.getLocVT(), Chain, FIN,
2616 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2617 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002618
Tim Northover3b0846e2014-05-24 12:50:23 +00002619 InVals.push_back(ArgValue);
2620 }
2621 }
2622
2623 // varargs
2624 if (isVarArg) {
2625 if (!Subtarget->isTargetDarwin()) {
2626 // The AAPCS variadic function ABI is identical to the non-variadic
2627 // one. As a result there may be more arguments in registers and we should
2628 // save them for future reference.
2629 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2630 }
2631
2632 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2633 // This will point to the next argument passed via stack.
2634 unsigned StackOffset = CCInfo.getNextStackOffset();
2635 // We currently pass all varargs at 8-byte alignment.
2636 StackOffset = ((StackOffset + 7) & ~7);
2637 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2638 }
2639
2640 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2641 unsigned StackArgSize = CCInfo.getNextStackOffset();
2642 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2643 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2644 // This is a non-standard ABI so by fiat I say we're allowed to make full
2645 // use of the stack area to be popped, which must be aligned to 16 bytes in
2646 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002647 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002648
2649 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2650 // a multiple of 16.
2651 FuncInfo->setArgumentStackToRestore(StackArgSize);
2652
2653 // This realignment carries over to the available bytes below. Our own
2654 // callers will guarantee the space is free by giving an aligned value to
2655 // CALLSEQ_START.
2656 }
2657 // Even if we're not expected to free up the space, it's useful to know how
2658 // much is there while considering tail calls (because we can reuse it).
2659 FuncInfo->setBytesInStackArgArea(StackArgSize);
2660
2661 return Chain;
2662}
2663
2664void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2665 SelectionDAG &DAG, SDLoc DL,
2666 SDValue &Chain) const {
2667 MachineFunction &MF = DAG.getMachineFunction();
2668 MachineFrameInfo *MFI = MF.getFrameInfo();
2669 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002670 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002671
2672 SmallVector<SDValue, 8> MemOps;
2673
2674 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2675 AArch64::X3, AArch64::X4, AArch64::X5,
2676 AArch64::X6, AArch64::X7 };
2677 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002678 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002679
2680 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2681 int GPRIdx = 0;
2682 if (GPRSaveSize != 0) {
2683 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2684
Mehdi Amini44ede332015-07-09 02:09:04 +00002685 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002686
2687 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2688 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2689 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002690 SDValue Store = DAG.getStore(
2691 Val.getValue(1), DL, Val, FIN,
2692 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2693 false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002694 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002695 FIN =
2696 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002697 }
2698 }
2699 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2700 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2701
2702 if (Subtarget->hasFPARMv8()) {
2703 static const MCPhysReg FPRArgRegs[] = {
2704 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2705 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2706 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002707 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002708
2709 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2710 int FPRIdx = 0;
2711 if (FPRSaveSize != 0) {
2712 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2713
Mehdi Amini44ede332015-07-09 02:09:04 +00002714 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002715
2716 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2717 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2718 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2719
Alex Lorenze40c8a22015-08-11 23:09:45 +00002720 SDValue Store = DAG.getStore(
2721 Val.getValue(1), DL, Val, FIN,
2722 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2723 false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002724 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002725 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2726 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002727 }
2728 }
2729 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2730 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2731 }
2732
2733 if (!MemOps.empty()) {
2734 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2735 }
2736}
2737
2738/// LowerCallResult - Lower the result values of a call into the
2739/// appropriate copies out of appropriate physical registers.
2740SDValue AArch64TargetLowering::LowerCallResult(
2741 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2742 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2743 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2744 SDValue ThisVal) const {
2745 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2746 ? RetCC_AArch64_WebKit_JS
2747 : RetCC_AArch64_AAPCS;
2748 // Assign locations to each value returned by this call.
2749 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002750 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2751 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002752 CCInfo.AnalyzeCallResult(Ins, RetCC);
2753
2754 // Copy all of the result registers out of their specified physreg.
2755 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2756 CCValAssign VA = RVLocs[i];
2757
2758 // Pass 'this' value directly from the argument to return value, to avoid
2759 // reg unit interference
2760 if (i == 0 && isThisReturn) {
2761 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2762 "unexpected return calling convention register assignment");
2763 InVals.push_back(ThisVal);
2764 continue;
2765 }
2766
2767 SDValue Val =
2768 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2769 Chain = Val.getValue(1);
2770 InFlag = Val.getValue(2);
2771
2772 switch (VA.getLocInfo()) {
2773 default:
2774 llvm_unreachable("Unknown loc info!");
2775 case CCValAssign::Full:
2776 break;
2777 case CCValAssign::BCvt:
2778 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2779 break;
2780 }
2781
2782 InVals.push_back(Val);
2783 }
2784
2785 return Chain;
2786}
2787
2788bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2789 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2790 bool isCalleeStructRet, bool isCallerStructRet,
2791 const SmallVectorImpl<ISD::OutputArg> &Outs,
2792 const SmallVectorImpl<SDValue> &OutVals,
2793 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2794 // For CallingConv::C this function knows whether the ABI needs
2795 // changing. That's not true for other conventions so they will have to opt in
2796 // manually.
2797 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2798 return false;
2799
2800 const MachineFunction &MF = DAG.getMachineFunction();
2801 const Function *CallerF = MF.getFunction();
2802 CallingConv::ID CallerCC = CallerF->getCallingConv();
2803 bool CCMatch = CallerCC == CalleeCC;
2804
2805 // Byval parameters hand the function a pointer directly into the stack area
2806 // we want to reuse during a tail call. Working around this *is* possible (see
2807 // X86) but less efficient and uglier in LowerCall.
2808 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2809 e = CallerF->arg_end();
2810 i != e; ++i)
2811 if (i->hasByValAttr())
2812 return false;
2813
2814 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2815 if (IsTailCallConvention(CalleeCC) && CCMatch)
2816 return true;
2817 return false;
2818 }
2819
Oliver Stannard12993dd2014-08-18 12:42:15 +00002820 // Externally-defined functions with weak linkage should not be
2821 // tail-called on AArch64 when the OS does not support dynamic
2822 // pre-emption of symbols, as the AAELF spec requires normal calls
2823 // to undefined weak functions to be replaced with a NOP or jump to the
2824 // next instruction. The behaviour of branch instructions in this
2825 // situation (as used for tail calls) is implementation-defined, so we
2826 // cannot rely on the linker replacing the tail call with a return.
2827 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2828 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002829 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002830 if (GV->hasExternalWeakLinkage() &&
2831 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002832 return false;
2833 }
2834
Tim Northover3b0846e2014-05-24 12:50:23 +00002835 // Now we search for cases where we can use a tail call without changing the
2836 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2837 // concept.
2838
2839 // I want anyone implementing a new calling convention to think long and hard
2840 // about this assert.
2841 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2842 "Unexpected variadic calling convention");
2843
2844 if (isVarArg && !Outs.empty()) {
2845 // At least two cases here: if caller is fastcc then we can't have any
2846 // memory arguments (we'd be expected to clean up the stack afterwards). If
2847 // caller is C then we could potentially use its argument area.
2848
2849 // FIXME: for now we take the most conservative of these in both cases:
2850 // disallow all variadic memory operands.
2851 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002852 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2853 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002854
2855 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002856 for (const CCValAssign &ArgLoc : ArgLocs)
2857 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002858 return false;
2859 }
2860
2861 // If the calling conventions do not match, then we'd better make sure the
2862 // results are returned in the same way as what the caller expects.
2863 if (!CCMatch) {
2864 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002865 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2866 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002867 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2868
2869 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002870 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2871 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002872 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2873
2874 if (RVLocs1.size() != RVLocs2.size())
2875 return false;
2876 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2877 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2878 return false;
2879 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2880 return false;
2881 if (RVLocs1[i].isRegLoc()) {
2882 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2883 return false;
2884 } else {
2885 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2886 return false;
2887 }
2888 }
2889 }
2890
2891 // Nothing more to check if the callee is taking no arguments
2892 if (Outs.empty())
2893 return true;
2894
2895 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002896 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2897 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002898
2899 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2900
2901 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2902
2903 // If the stack arguments for this call would fit into our own save area then
2904 // the call can be made tail.
2905 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2906}
2907
2908SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2909 SelectionDAG &DAG,
2910 MachineFrameInfo *MFI,
2911 int ClobberedFI) const {
2912 SmallVector<SDValue, 8> ArgChains;
2913 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2914 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2915
2916 // Include the original chain at the beginning of the list. When this is
2917 // used by target LowerCall hooks, this helps legalize find the
2918 // CALLSEQ_BEGIN node.
2919 ArgChains.push_back(Chain);
2920
2921 // Add a chain value for each stack argument corresponding
2922 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2923 UE = DAG.getEntryNode().getNode()->use_end();
2924 U != UE; ++U)
2925 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2926 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2927 if (FI->getIndex() < 0) {
2928 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2929 int64_t InLastByte = InFirstByte;
2930 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2931
2932 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2933 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2934 ArgChains.push_back(SDValue(L, 1));
2935 }
2936
2937 // Build a tokenfactor for all the chains.
2938 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2939}
2940
2941bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2942 bool TailCallOpt) const {
2943 return CallCC == CallingConv::Fast && TailCallOpt;
2944}
2945
2946bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2947 return CallCC == CallingConv::Fast;
2948}
2949
2950/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2951/// and add input and output parameter nodes.
2952SDValue
2953AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2954 SmallVectorImpl<SDValue> &InVals) const {
2955 SelectionDAG &DAG = CLI.DAG;
2956 SDLoc &DL = CLI.DL;
2957 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2958 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2959 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2960 SDValue Chain = CLI.Chain;
2961 SDValue Callee = CLI.Callee;
2962 bool &IsTailCall = CLI.IsTailCall;
2963 CallingConv::ID CallConv = CLI.CallConv;
2964 bool IsVarArg = CLI.IsVarArg;
2965
2966 MachineFunction &MF = DAG.getMachineFunction();
2967 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2968 bool IsThisReturn = false;
2969
2970 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2971 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2972 bool IsSibCall = false;
2973
2974 if (IsTailCall) {
2975 // Check if it's really possible to do a tail call.
2976 IsTailCall = isEligibleForTailCallOptimization(
2977 Callee, CallConv, IsVarArg, IsStructRet,
2978 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2979 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2980 report_fatal_error("failed to perform tail call elimination on a call "
2981 "site marked musttail");
2982
2983 // A sibling call is one where we're under the usual C ABI and not planning
2984 // to change that but can still do a tail call:
2985 if (!TailCallOpt && IsTailCall)
2986 IsSibCall = true;
2987
2988 if (IsTailCall)
2989 ++NumTailCalls;
2990 }
2991
2992 // Analyze operands of the call, assigning locations to each operand.
2993 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002994 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2995 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002996
2997 if (IsVarArg) {
2998 // Handle fixed and variable vector arguments differently.
2999 // Variable vector arguments always go into memory.
3000 unsigned NumArgs = Outs.size();
3001
3002 for (unsigned i = 0; i != NumArgs; ++i) {
3003 MVT ArgVT = Outs[i].VT;
3004 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3005 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3006 /*IsVarArg=*/ !Outs[i].IsFixed);
3007 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3008 assert(!Res && "Call operand has unhandled type");
3009 (void)Res;
3010 }
3011 } else {
3012 // At this point, Outs[].VT may already be promoted to i32. To correctly
3013 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3014 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3015 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3016 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3017 // LocVT.
3018 unsigned NumArgs = Outs.size();
3019 for (unsigned i = 0; i != NumArgs; ++i) {
3020 MVT ValVT = Outs[i].VT;
3021 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003022 EVT ActualVT = getValueType(DAG.getDataLayout(),
3023 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003024 /*AllowUnknown*/ true);
3025 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3026 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3027 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003028 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003029 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003030 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003031 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003032
3033 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003034 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003035 assert(!Res && "Call operand has unhandled type");
3036 (void)Res;
3037 }
3038 }
3039
3040 // Get a count of how many bytes are to be pushed on the stack.
3041 unsigned NumBytes = CCInfo.getNextStackOffset();
3042
3043 if (IsSibCall) {
3044 // Since we're not changing the ABI to make this a tail call, the memory
3045 // operands are already available in the caller's incoming argument space.
3046 NumBytes = 0;
3047 }
3048
3049 // FPDiff is the byte offset of the call's argument area from the callee's.
3050 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3051 // by this amount for a tail call. In a sibling call it must be 0 because the
3052 // caller will deallocate the entire stack and the callee still expects its
3053 // arguments to begin at SP+0. Completely unused for non-tail calls.
3054 int FPDiff = 0;
3055
3056 if (IsTailCall && !IsSibCall) {
3057 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3058
3059 // Since callee will pop argument stack as a tail call, we must keep the
3060 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003061 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003062
3063 // FPDiff will be negative if this tail call requires more space than we
3064 // would automatically have in our incoming argument space. Positive if we
3065 // can actually shrink the stack.
3066 FPDiff = NumReusableBytes - NumBytes;
3067
3068 // The stack pointer must be 16-byte aligned at all times it's used for a
3069 // memory operation, which in practice means at *all* times and in
3070 // particular across call boundaries. Therefore our own arguments started at
3071 // a 16-byte aligned SP and the delta applied for the tail call should
3072 // satisfy the same constraint.
3073 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3074 }
3075
3076 // Adjust the stack pointer for the new arguments...
3077 // These operations are automatically eliminated by the prolog/epilog pass
3078 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003079 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3080 true),
3081 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003082
Mehdi Amini44ede332015-07-09 02:09:04 +00003083 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3084 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003085
3086 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3087 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003088 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003089
3090 // Walk the register/memloc assignments, inserting copies/loads.
3091 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3092 ++i, ++realArgIdx) {
3093 CCValAssign &VA = ArgLocs[i];
3094 SDValue Arg = OutVals[realArgIdx];
3095 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3096
3097 // Promote the value if needed.
3098 switch (VA.getLocInfo()) {
3099 default:
3100 llvm_unreachable("Unknown loc info!");
3101 case CCValAssign::Full:
3102 break;
3103 case CCValAssign::SExt:
3104 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3105 break;
3106 case CCValAssign::ZExt:
3107 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3108 break;
3109 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003110 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3111 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3112 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3113 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3114 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003115 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3116 break;
3117 case CCValAssign::BCvt:
3118 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3119 break;
3120 case CCValAssign::FPExt:
3121 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3122 break;
3123 }
3124
3125 if (VA.isRegLoc()) {
3126 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3127 assert(VA.getLocVT() == MVT::i64 &&
3128 "unexpected calling convention register assignment");
3129 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3130 "unexpected use of 'returned'");
3131 IsThisReturn = true;
3132 }
3133 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3134 } else {
3135 assert(VA.isMemLoc());
3136
3137 SDValue DstAddr;
3138 MachinePointerInfo DstInfo;
3139
3140 // FIXME: This works on big-endian for composite byvals, which are the
3141 // common case. It should also work for fundamental types too.
3142 uint32_t BEAlign = 0;
3143 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003144 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003145 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003146 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3147 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003148 if (OpSize < 8)
3149 BEAlign = 8 - OpSize;
3150 }
3151 unsigned LocMemOffset = VA.getLocMemOffset();
3152 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003153 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003154 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003155
3156 if (IsTailCall) {
3157 Offset = Offset + FPDiff;
3158 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3159
Mehdi Amini44ede332015-07-09 02:09:04 +00003160 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003161 DstInfo =
3162 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003163
3164 // Make sure any stack arguments overlapping with where we're storing
3165 // are loaded before this eventual operation. Otherwise they'll be
3166 // clobbered.
3167 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3168 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003169 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003170
Mehdi Amini44ede332015-07-09 02:09:04 +00003171 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003172 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3173 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003174 }
3175
3176 if (Outs[i].Flags.isByVal()) {
3177 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003178 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003179 SDValue Cpy = DAG.getMemcpy(
3180 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003181 /*isVol = */ false, /*AlwaysInline = */ false,
3182 /*isTailCall = */ false,
3183 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003184
3185 MemOpChains.push_back(Cpy);
3186 } else {
3187 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3188 // promoted to a legal register type i32, we should truncate Arg back to
3189 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003190 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3191 VA.getValVT() == MVT::i16)
3192 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003193
3194 SDValue Store =
3195 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3196 MemOpChains.push_back(Store);
3197 }
3198 }
3199 }
3200
3201 if (!MemOpChains.empty())
3202 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3203
3204 // Build a sequence of copy-to-reg nodes chained together with token chain
3205 // and flag operands which copy the outgoing args into the appropriate regs.
3206 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003207 for (auto &RegToPass : RegsToPass) {
3208 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3209 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003210 InFlag = Chain.getValue(1);
3211 }
3212
3213 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3214 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3215 // node so that legalize doesn't hack it.
3216 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3217 Subtarget->isTargetMachO()) {
3218 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3219 const GlobalValue *GV = G->getGlobal();
3220 bool InternalLinkage = GV->hasInternalLinkage();
3221 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003222 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003223 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003224 Callee =
3225 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3226 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003227 }
3228 } else if (ExternalSymbolSDNode *S =
3229 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3230 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003231 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3232 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003233 }
3234 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3235 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003236 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003237 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3238 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003239 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003240 }
3241
3242 // We don't usually want to end the call-sequence here because we would tidy
3243 // the frame up *after* the call, however in the ABI-changing tail-call case
3244 // we've carefully laid out the parameters so that when sp is reset they'll be
3245 // in the correct location.
3246 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003247 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3248 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003249 InFlag = Chain.getValue(1);
3250 }
3251
3252 std::vector<SDValue> Ops;
3253 Ops.push_back(Chain);
3254 Ops.push_back(Callee);
3255
3256 if (IsTailCall) {
3257 // Each tail call may have to adjust the stack by a different amount, so
3258 // this information must travel along with the operation for eventual
3259 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003260 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003261 }
3262
3263 // Add argument registers to the end of the list so that they are known live
3264 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003265 for (auto &RegToPass : RegsToPass)
3266 Ops.push_back(DAG.getRegister(RegToPass.first,
3267 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003268
3269 // Add a register mask operand representing the call-preserved registers.
3270 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003271 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003272 if (IsThisReturn) {
3273 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003274 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003275 if (!Mask) {
3276 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003277 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003278 }
3279 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003280 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003281
3282 assert(Mask && "Missing call preserved mask for calling convention");
3283 Ops.push_back(DAG.getRegisterMask(Mask));
3284
3285 if (InFlag.getNode())
3286 Ops.push_back(InFlag);
3287
3288 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3289
3290 // If we're doing a tall call, use a TC_RETURN here rather than an
3291 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003292 if (IsTailCall) {
3293 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003294 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003295 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003296
3297 // Returns a chain and a flag for retval copy to use.
3298 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3299 InFlag = Chain.getValue(1);
3300
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003301 uint64_t CalleePopBytes =
3302 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003303
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003304 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3305 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003306 InFlag, DL);
3307 if (!Ins.empty())
3308 InFlag = Chain.getValue(1);
3309
3310 // Handle result values, copying them out of physregs into vregs that we
3311 // return.
3312 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3313 InVals, IsThisReturn,
3314 IsThisReturn ? OutVals[0] : SDValue());
3315}
3316
3317bool AArch64TargetLowering::CanLowerReturn(
3318 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3319 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3320 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3321 ? RetCC_AArch64_WebKit_JS
3322 : RetCC_AArch64_AAPCS;
3323 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003324 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003325 return CCInfo.CheckReturn(Outs, RetCC);
3326}
3327
3328SDValue
3329AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3330 bool isVarArg,
3331 const SmallVectorImpl<ISD::OutputArg> &Outs,
3332 const SmallVectorImpl<SDValue> &OutVals,
3333 SDLoc DL, SelectionDAG &DAG) const {
3334 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3335 ? RetCC_AArch64_WebKit_JS
3336 : RetCC_AArch64_AAPCS;
3337 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003338 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3339 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003340 CCInfo.AnalyzeReturn(Outs, RetCC);
3341
3342 // Copy the result values into the output registers.
3343 SDValue Flag;
3344 SmallVector<SDValue, 4> RetOps(1, Chain);
3345 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3346 ++i, ++realRVLocIdx) {
3347 CCValAssign &VA = RVLocs[i];
3348 assert(VA.isRegLoc() && "Can only return in registers!");
3349 SDValue Arg = OutVals[realRVLocIdx];
3350
3351 switch (VA.getLocInfo()) {
3352 default:
3353 llvm_unreachable("Unknown loc info!");
3354 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003355 if (Outs[i].ArgVT == MVT::i1) {
3356 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3357 // value. This is strictly redundant on Darwin (which uses "zeroext
3358 // i1"), but will be optimised out before ISel.
3359 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3360 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3361 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003362 break;
3363 case CCValAssign::BCvt:
3364 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3365 break;
3366 }
3367
3368 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3369 Flag = Chain.getValue(1);
3370 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3371 }
Manman Rencbe4f942015-12-16 21:04:19 +00003372 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3373 const MCPhysReg *I =
3374 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3375 if (I) {
3376 for (; *I; ++I) {
3377 if (AArch64::GPR64RegClass.contains(*I))
3378 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3379 else if (AArch64::FPR64RegClass.contains(*I))
3380 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3381 else
3382 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3383 }
3384 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003385
3386 RetOps[0] = Chain; // Update chain.
3387
3388 // Add the flag if we have it.
3389 if (Flag.getNode())
3390 RetOps.push_back(Flag);
3391
3392 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3393}
3394
3395//===----------------------------------------------------------------------===//
3396// Other Lowering Code
3397//===----------------------------------------------------------------------===//
3398
3399SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3400 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003401 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003402 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003403 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3404 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003405 unsigned char OpFlags =
3406 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3407
3408 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3409 "unexpected offset in global node");
3410
3411 // This also catched the large code model case for Darwin.
3412 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3413 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3414 // FIXME: Once remat is capable of dealing with instructions with register
3415 // operands, expand this into two nodes instead of using a wrapper node.
3416 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3417 }
3418
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003419 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3420 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3421 "use of MO_CONSTPOOL only supported on small model");
3422 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3423 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3424 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3425 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3426 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003427 SDValue GlobalAddr = DAG.getLoad(
3428 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3429 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3430 /*isVolatile=*/false,
3431 /*isNonTemporal=*/true,
3432 /*isInvariant=*/true, 8);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003433 if (GN->getOffset() != 0)
3434 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003435 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003436 return GlobalAddr;
3437 }
3438
Tim Northover3b0846e2014-05-24 12:50:23 +00003439 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3440 const unsigned char MO_NC = AArch64II::MO_NC;
3441 return DAG.getNode(
3442 AArch64ISD::WrapperLarge, DL, PtrVT,
3443 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3444 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3445 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3446 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3447 } else {
3448 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3449 // the only correct model on Darwin.
3450 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3451 OpFlags | AArch64II::MO_PAGE);
3452 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3453 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3454
3455 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3456 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3457 }
3458}
3459
3460/// \brief Convert a TLS address reference into the correct sequence of loads
3461/// and calls to compute the variable's address (for Darwin, currently) and
3462/// return an SDValue containing the final node.
3463
3464/// Darwin only has one TLS scheme which must be capable of dealing with the
3465/// fully general situation, in the worst case. This means:
3466/// + "extern __thread" declaration.
3467/// + Defined in a possibly unknown dynamic library.
3468///
3469/// The general system is that each __thread variable has a [3 x i64] descriptor
3470/// which contains information used by the runtime to calculate the address. The
3471/// only part of this the compiler needs to know about is the first xword, which
3472/// contains a function pointer that must be called with the address of the
3473/// entire descriptor in "x0".
3474///
3475/// Since this descriptor may be in a different unit, in general even the
3476/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3477/// is:
3478/// adrp x0, _var@TLVPPAGE
3479/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3480/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3481/// ; the function pointer
3482/// blr x1 ; Uses descriptor address in x0
3483/// ; Address of _var is now in x0.
3484///
3485/// If the address of _var's descriptor *is* known to the linker, then it can
3486/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3487/// a slight efficiency gain.
3488SDValue
3489AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3490 SelectionDAG &DAG) const {
3491 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3492
3493 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003494 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003495 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3496
3497 SDValue TLVPAddr =
3498 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3499 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3500
3501 // The first entry in the descriptor is a function pointer that we must call
3502 // to obtain the address of the variable.
3503 SDValue Chain = DAG.getEntryNode();
3504 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003505 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3506 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3507 true, true, 8);
Tim Northover3b0846e2014-05-24 12:50:23 +00003508 Chain = FuncTLVGet.getValue(1);
3509
3510 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3511 MFI->setAdjustsStack(true);
3512
3513 // TLS calls preserve all registers except those that absolutely must be
3514 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3515 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003516 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003517 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003518
3519 // Finally, we can make the call. This is just a degenerate version of a
3520 // normal AArch64 call node: x0 takes the address of the descriptor, and
3521 // returns the address of the variable in this thread.
3522 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3523 Chain =
3524 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3525 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3526 DAG.getRegisterMask(Mask), Chain.getValue(1));
3527 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3528}
3529
3530/// When accessing thread-local variables under either the general-dynamic or
3531/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3532/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003533/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003534///
Kristof Beylsaea84612015-03-04 09:12:08 +00003535/// The sequence is:
3536/// adrp x0, :tlsdesc:var
3537/// ldr x1, [x0, #:tlsdesc_lo12:var]
3538/// add x0, x0, #:tlsdesc_lo12:var
3539/// .tlsdesccall var
3540/// blr x1
3541/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003542///
Kristof Beylsaea84612015-03-04 09:12:08 +00003543/// The above sequence must be produced unscheduled, to enable the linker to
3544/// optimize/relax this sequence.
3545/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3546/// above sequence, and expanded really late in the compilation flow, to ensure
3547/// the sequence is produced as per above.
3548SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3549 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003550 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003551
Kristof Beylsaea84612015-03-04 09:12:08 +00003552 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003553 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003554
3555 SmallVector<SDValue, 2> Ops;
3556 Ops.push_back(Chain);
3557 Ops.push_back(SymAddr);
3558
3559 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3560 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003561
3562 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3563}
3564
3565SDValue
3566AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3567 SelectionDAG &DAG) const {
3568 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3569 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3570 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003571 // Different choices can be made for the maximum size of the TLS area for a
3572 // module. For the small address model, the default TLS size is 16MiB and the
3573 // maximum TLS size is 4GiB.
3574 // FIXME: add -mtls-size command line option and make it control the 16MiB
3575 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003576 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3577
3578 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003579
3580 if (DAG.getTarget().Options.EmulatedTLS)
3581 return LowerToTLSEmulatedModel(GA, DAG);
3582
Kristof Beylsaea84612015-03-04 09:12:08 +00003583 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3584 if (Model == TLSModel::LocalDynamic)
3585 Model = TLSModel::GeneralDynamic;
3586 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003587
3588 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003589 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003590 SDLoc DL(Op);
3591 const GlobalValue *GV = GA->getGlobal();
3592
3593 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3594
3595 if (Model == TLSModel::LocalExec) {
3596 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003597 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003598 SDValue LoVar = DAG.getTargetGlobalAddress(
3599 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003600 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003601
Kristof Beylsaea84612015-03-04 09:12:08 +00003602 SDValue TPWithOff_lo =
3603 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003604 HiVar,
3605 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003606 0);
3607 SDValue TPWithOff =
3608 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003609 LoVar,
3610 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003611 0);
3612 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003613 } else if (Model == TLSModel::InitialExec) {
3614 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3615 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3616 } else if (Model == TLSModel::LocalDynamic) {
3617 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3618 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3619 // the beginning of the module's TLS region, followed by a DTPREL offset
3620 // calculation.
3621
3622 // These accesses will need deduplicating if there's more than one.
3623 AArch64FunctionInfo *MFI =
3624 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3625 MFI->incNumLocalDynamicTLSAccesses();
3626
Tim Northover3b0846e2014-05-24 12:50:23 +00003627 // The call needs a relocation too for linker relaxation. It doesn't make
3628 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3629 // the address.
3630 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3631 AArch64II::MO_TLS);
3632
3633 // Now we can calculate the offset from TPIDR_EL0 to this module's
3634 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003635 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003636
3637 // Now use :dtprel_whatever: operations to calculate this variable's offset
3638 // in its thread-storage area.
3639 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003640 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003641 SDValue LoVar = DAG.getTargetGlobalAddress(
3642 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003643 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3644
Kristof Beylsaea84612015-03-04 09:12:08 +00003645 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003646 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003647 0);
3648 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003649 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003650 0);
3651 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003652 // The call needs a relocation too for linker relaxation. It doesn't make
3653 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3654 // the address.
3655 SDValue SymAddr =
3656 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3657
3658 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003659 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003660 } else
3661 llvm_unreachable("Unsupported ELF TLS access model");
3662
3663 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3664}
3665
3666SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3667 SelectionDAG &DAG) const {
3668 if (Subtarget->isTargetDarwin())
3669 return LowerDarwinGlobalTLSAddress(Op, DAG);
3670 else if (Subtarget->isTargetELF())
3671 return LowerELFGlobalTLSAddress(Op, DAG);
3672
3673 llvm_unreachable("Unexpected platform trying to use TLS");
3674}
3675SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3676 SDValue Chain = Op.getOperand(0);
3677 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3678 SDValue LHS = Op.getOperand(2);
3679 SDValue RHS = Op.getOperand(3);
3680 SDValue Dest = Op.getOperand(4);
3681 SDLoc dl(Op);
3682
3683 // Handle f128 first, since lowering it will result in comparing the return
3684 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3685 // is expecting to deal with.
3686 if (LHS.getValueType() == MVT::f128) {
3687 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3688
3689 // If softenSetCCOperands returned a scalar, we need to compare the result
3690 // against zero to select between true and false values.
3691 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003692 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003693 CC = ISD::SETNE;
3694 }
3695 }
3696
3697 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3698 // instruction.
3699 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003700 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003701 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3702 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3703 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3704 "Unexpected condition code.");
3705 // Only lower legal XALUO ops.
3706 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3707 return SDValue();
3708
3709 // The actual operation with overflow check.
3710 AArch64CC::CondCode OFCC;
3711 SDValue Value, Overflow;
3712 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3713
3714 if (CC == ISD::SETNE)
3715 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003716 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003717
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003718 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3719 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003720 }
3721
3722 if (LHS.getValueType().isInteger()) {
3723 assert((LHS.getValueType() == RHS.getValueType()) &&
3724 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3725
3726 // If the RHS of the comparison is zero, we can potentially fold this
3727 // to a specialized branch.
3728 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3729 if (RHSC && RHSC->getZExtValue() == 0) {
3730 if (CC == ISD::SETEQ) {
3731 // See if we can use a TBZ to fold in an AND as well.
3732 // TBZ has a smaller branch displacement than CBZ. If the offset is
3733 // out of bounds, a late MI-layer pass rewrites branches.
3734 // 403.gcc is an example that hits this case.
3735 if (LHS.getOpcode() == ISD::AND &&
3736 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3737 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3738 SDValue Test = LHS.getOperand(0);
3739 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003740 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003741 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3742 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003743 }
3744
3745 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3746 } else if (CC == ISD::SETNE) {
3747 // See if we can use a TBZ to fold in an AND as well.
3748 // TBZ has a smaller branch displacement than CBZ. If the offset is
3749 // out of bounds, a late MI-layer pass rewrites branches.
3750 // 403.gcc is an example that hits this case.
3751 if (LHS.getOpcode() == ISD::AND &&
3752 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3753 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3754 SDValue Test = LHS.getOperand(0);
3755 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003756 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003757 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3758 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003759 }
3760
3761 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003762 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3763 // Don't combine AND since emitComparison converts the AND to an ANDS
3764 // (a.k.a. TST) and the test in the test bit and branch instruction
3765 // becomes redundant. This would also increase register pressure.
3766 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3767 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003768 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003769 }
3770 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003771 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3772 LHS.getOpcode() != ISD::AND) {
3773 // Don't combine AND since emitComparison converts the AND to an ANDS
3774 // (a.k.a. TST) and the test in the test bit and branch instruction
3775 // becomes redundant. This would also increase register pressure.
3776 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3777 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003778 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003779 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003780
3781 SDValue CCVal;
3782 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3783 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3784 Cmp);
3785 }
3786
3787 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3788
3789 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3790 // clean. Some of them require two branches to implement.
3791 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3792 AArch64CC::CondCode CC1, CC2;
3793 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003794 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003795 SDValue BR1 =
3796 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3797 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003798 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003799 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3800 Cmp);
3801 }
3802
3803 return BR1;
3804}
3805
3806SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3807 SelectionDAG &DAG) const {
3808 EVT VT = Op.getValueType();
3809 SDLoc DL(Op);
3810
3811 SDValue In1 = Op.getOperand(0);
3812 SDValue In2 = Op.getOperand(1);
3813 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003814
3815 if (SrcVT.bitsLT(VT))
3816 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3817 else if (SrcVT.bitsGT(VT))
3818 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003819
3820 EVT VecVT;
3821 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003822 uint64_t EltMask;
3823 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003824 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3825 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003826 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003827 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003828
3829 if (!VT.isVector()) {
3830 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3831 DAG.getUNDEF(VecVT), In1);
3832 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3833 DAG.getUNDEF(VecVT), In2);
3834 } else {
3835 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3836 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3837 }
3838 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3839 EltVT = MVT::i64;
3840 VecVT = MVT::v2i64;
3841
Eric Christopher572e03a2015-06-19 01:53:21 +00003842 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003843 // immediate moves cannot materialize that in a single instruction for
3844 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003845 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003846
3847 if (!VT.isVector()) {
3848 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3849 DAG.getUNDEF(VecVT), In1);
3850 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3851 DAG.getUNDEF(VecVT), In2);
3852 } else {
3853 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3854 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3855 }
3856 } else {
3857 llvm_unreachable("Invalid type for copysign!");
3858 }
3859
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003860 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003861
3862 // If we couldn't materialize the mask above, then the mask vector will be
3863 // the zero vector, and we need to negate it here.
3864 if (VT == MVT::f64 || VT == MVT::v2f64) {
3865 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3866 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3867 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3868 }
3869
3870 SDValue Sel =
3871 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3872
3873 if (VT == MVT::f32)
3874 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3875 else if (VT == MVT::f64)
3876 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3877 else
3878 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3879}
3880
3881SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003882 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3883 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003884 return SDValue();
3885
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003886 if (!Subtarget->hasNEON())
3887 return SDValue();
3888
Tim Northover3b0846e2014-05-24 12:50:23 +00003889 // While there is no integer popcount instruction, it can
3890 // be more efficiently lowered to the following sequence that uses
3891 // AdvSIMD registers/instructions as long as the copies to/from
3892 // the AdvSIMD registers are cheap.
3893 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3894 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3895 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3896 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3897 SDValue Val = Op.getOperand(0);
3898 SDLoc DL(Op);
3899 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003900
Hao Liue0335d72015-01-30 02:13:53 +00003901 if (VT == MVT::i32)
3902 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3903 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003904
Hao Liue0335d72015-01-30 02:13:53 +00003905 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003906 SDValue UaddLV = DAG.getNode(
3907 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003908 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003909
3910 if (VT == MVT::i64)
3911 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3912 return UaddLV;
3913}
3914
3915SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3916
3917 if (Op.getValueType().isVector())
3918 return LowerVSETCC(Op, DAG);
3919
3920 SDValue LHS = Op.getOperand(0);
3921 SDValue RHS = Op.getOperand(1);
3922 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3923 SDLoc dl(Op);
3924
3925 // We chose ZeroOrOneBooleanContents, so use zero and one.
3926 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003927 SDValue TVal = DAG.getConstant(1, dl, VT);
3928 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003929
3930 // Handle f128 first, since one possible outcome is a normal integer
3931 // comparison which gets picked up by the next if statement.
3932 if (LHS.getValueType() == MVT::f128) {
3933 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3934
3935 // If softenSetCCOperands returned a scalar, use it.
3936 if (!RHS.getNode()) {
3937 assert(LHS.getValueType() == Op.getValueType() &&
3938 "Unexpected setcc expansion!");
3939 return LHS;
3940 }
3941 }
3942
3943 if (LHS.getValueType().isInteger()) {
3944 SDValue CCVal;
3945 SDValue Cmp =
3946 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3947
3948 // Note that we inverted the condition above, so we reverse the order of
3949 // the true and false operands here. This will allow the setcc to be
3950 // matched to a single CSINC instruction.
3951 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3952 }
3953
3954 // Now we know we're dealing with FP values.
3955 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3956
3957 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3958 // and do the comparison.
3959 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3960
3961 AArch64CC::CondCode CC1, CC2;
3962 changeFPCCToAArch64CC(CC, CC1, CC2);
3963 if (CC2 == AArch64CC::AL) {
3964 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003965 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003966
3967 // Note that we inverted the condition above, so we reverse the order of
3968 // the true and false operands here. This will allow the setcc to be
3969 // matched to a single CSINC instruction.
3970 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3971 } else {
3972 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3973 // totally clean. Some of them require two CSELs to implement. As is in
3974 // this case, we emit the first CSEL and then emit a second using the output
3975 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3976
3977 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003978 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003979 SDValue CS1 =
3980 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3981
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003982 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003983 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3984 }
3985}
3986
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003987SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3988 SDValue RHS, SDValue TVal,
3989 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003990 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003991 // Handle f128 first, because it will result in a comparison of some RTLIB
3992 // call result against zero.
3993 if (LHS.getValueType() == MVT::f128) {
3994 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3995
3996 // If softenSetCCOperands returned a scalar, we need to compare the result
3997 // against zero to select between true and false values.
3998 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003999 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004000 CC = ISD::SETNE;
4001 }
4002 }
4003
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004004 // Also handle f16, for which we need to do a f32 comparison.
4005 if (LHS.getValueType() == MVT::f16) {
4006 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4007 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4008 }
4009
4010 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004011 if (LHS.getValueType().isInteger()) {
4012 assert((LHS.getValueType() == RHS.getValueType()) &&
4013 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4014
4015 unsigned Opcode = AArch64ISD::CSEL;
4016
4017 // If both the TVal and the FVal are constants, see if we can swap them in
4018 // order to for a CSINV or CSINC out of them.
4019 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4020 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4021
4022 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4023 std::swap(TVal, FVal);
4024 std::swap(CTVal, CFVal);
4025 CC = ISD::getSetCCInverse(CC, true);
4026 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4027 std::swap(TVal, FVal);
4028 std::swap(CTVal, CFVal);
4029 CC = ISD::getSetCCInverse(CC, true);
4030 } else if (TVal.getOpcode() == ISD::XOR) {
4031 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4032 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004033 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004034 std::swap(TVal, FVal);
4035 std::swap(CTVal, CFVal);
4036 CC = ISD::getSetCCInverse(CC, true);
4037 }
4038 } else if (TVal.getOpcode() == ISD::SUB) {
4039 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4040 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004041 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004042 std::swap(TVal, FVal);
4043 std::swap(CTVal, CFVal);
4044 CC = ISD::getSetCCInverse(CC, true);
4045 }
4046 } else if (CTVal && CFVal) {
4047 const int64_t TrueVal = CTVal->getSExtValue();
4048 const int64_t FalseVal = CFVal->getSExtValue();
4049 bool Swap = false;
4050
4051 // If both TVal and FVal are constants, see if FVal is the
4052 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4053 // instead of a CSEL in that case.
4054 if (TrueVal == ~FalseVal) {
4055 Opcode = AArch64ISD::CSINV;
4056 } else if (TrueVal == -FalseVal) {
4057 Opcode = AArch64ISD::CSNEG;
4058 } else if (TVal.getValueType() == MVT::i32) {
4059 // If our operands are only 32-bit wide, make sure we use 32-bit
4060 // arithmetic for the check whether we can use CSINC. This ensures that
4061 // the addition in the check will wrap around properly in case there is
4062 // an overflow (which would not be the case if we do the check with
4063 // 64-bit arithmetic).
4064 const uint32_t TrueVal32 = CTVal->getZExtValue();
4065 const uint32_t FalseVal32 = CFVal->getZExtValue();
4066
4067 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4068 Opcode = AArch64ISD::CSINC;
4069
4070 if (TrueVal32 > FalseVal32) {
4071 Swap = true;
4072 }
4073 }
4074 // 64-bit check whether we can use CSINC.
4075 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4076 Opcode = AArch64ISD::CSINC;
4077
4078 if (TrueVal > FalseVal) {
4079 Swap = true;
4080 }
4081 }
4082
4083 // Swap TVal and FVal if necessary.
4084 if (Swap) {
4085 std::swap(TVal, FVal);
4086 std::swap(CTVal, CFVal);
4087 CC = ISD::getSetCCInverse(CC, true);
4088 }
4089
4090 if (Opcode != AArch64ISD::CSEL) {
4091 // Drop FVal since we can get its value by simply inverting/negating
4092 // TVal.
4093 FVal = TVal;
4094 }
4095 }
4096
4097 SDValue CCVal;
4098 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4099
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004100 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004101 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4102 }
4103
4104 // Now we know we're dealing with FP values.
4105 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4106 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004107 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004108 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4109
4110 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4111 // clean. Some of them require two CSELs to implement.
4112 AArch64CC::CondCode CC1, CC2;
4113 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004114 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004115 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4116
4117 // If we need a second CSEL, emit it, using the output of the first as the
4118 // RHS. We're effectively OR'ing the two CC's together.
4119 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004120 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004121 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4122 }
4123
4124 // Otherwise, return the output of the first CSEL.
4125 return CS1;
4126}
4127
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004128SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4129 SelectionDAG &DAG) const {
4130 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4131 SDValue LHS = Op.getOperand(0);
4132 SDValue RHS = Op.getOperand(1);
4133 SDValue TVal = Op.getOperand(2);
4134 SDValue FVal = Op.getOperand(3);
4135 SDLoc DL(Op);
4136 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4137}
4138
4139SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4140 SelectionDAG &DAG) const {
4141 SDValue CCVal = Op->getOperand(0);
4142 SDValue TVal = Op->getOperand(1);
4143 SDValue FVal = Op->getOperand(2);
4144 SDLoc DL(Op);
4145
4146 unsigned Opc = CCVal.getOpcode();
4147 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4148 // instruction.
4149 if (CCVal.getResNo() == 1 &&
4150 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4151 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4152 // Only lower legal XALUO ops.
4153 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4154 return SDValue();
4155
4156 AArch64CC::CondCode OFCC;
4157 SDValue Value, Overflow;
4158 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004159 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004160
4161 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4162 CCVal, Overflow);
4163 }
4164
4165 // Lower it the same way as we would lower a SELECT_CC node.
4166 ISD::CondCode CC;
4167 SDValue LHS, RHS;
4168 if (CCVal.getOpcode() == ISD::SETCC) {
4169 LHS = CCVal.getOperand(0);
4170 RHS = CCVal.getOperand(1);
4171 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4172 } else {
4173 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004174 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004175 CC = ISD::SETNE;
4176 }
4177 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4178}
4179
Tim Northover3b0846e2014-05-24 12:50:23 +00004180SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4181 SelectionDAG &DAG) const {
4182 // Jump table entries as PC relative offsets. No additional tweaking
4183 // is necessary here. Just get the address of the jump table.
4184 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004185 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004186 SDLoc DL(Op);
4187
4188 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4189 !Subtarget->isTargetMachO()) {
4190 const unsigned char MO_NC = AArch64II::MO_NC;
4191 return DAG.getNode(
4192 AArch64ISD::WrapperLarge, DL, PtrVT,
4193 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4194 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4195 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4196 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4197 AArch64II::MO_G0 | MO_NC));
4198 }
4199
4200 SDValue Hi =
4201 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4202 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4203 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4204 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4205 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4206}
4207
4208SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4209 SelectionDAG &DAG) const {
4210 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004211 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004212 SDLoc DL(Op);
4213
4214 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4215 // Use the GOT for the large code model on iOS.
4216 if (Subtarget->isTargetMachO()) {
4217 SDValue GotAddr = DAG.getTargetConstantPool(
4218 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4219 AArch64II::MO_GOT);
4220 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4221 }
4222
4223 const unsigned char MO_NC = AArch64II::MO_NC;
4224 return DAG.getNode(
4225 AArch64ISD::WrapperLarge, DL, PtrVT,
4226 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4227 CP->getOffset(), AArch64II::MO_G3),
4228 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4229 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4230 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4231 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4232 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4233 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4234 } else {
4235 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4236 // ELF, the only valid one on Darwin.
4237 SDValue Hi =
4238 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4239 CP->getOffset(), AArch64II::MO_PAGE);
4240 SDValue Lo = DAG.getTargetConstantPool(
4241 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4242 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4243
4244 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4245 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4246 }
4247}
4248
4249SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4250 SelectionDAG &DAG) const {
4251 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004252 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004253 SDLoc DL(Op);
4254 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4255 !Subtarget->isTargetMachO()) {
4256 const unsigned char MO_NC = AArch64II::MO_NC;
4257 return DAG.getNode(
4258 AArch64ISD::WrapperLarge, DL, PtrVT,
4259 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4260 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4261 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4262 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4263 } else {
4264 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4265 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4266 AArch64II::MO_NC);
4267 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4268 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4269 }
4270}
4271
4272SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4273 SelectionDAG &DAG) const {
4274 AArch64FunctionInfo *FuncInfo =
4275 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4276
4277 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004278 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4279 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004280 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4281 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4282 MachinePointerInfo(SV), false, false, 0);
4283}
4284
4285SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4286 SelectionDAG &DAG) const {
4287 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4288 // Standard, section B.3.
4289 MachineFunction &MF = DAG.getMachineFunction();
4290 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004291 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004292 SDLoc DL(Op);
4293
4294 SDValue Chain = Op.getOperand(0);
4295 SDValue VAList = Op.getOperand(1);
4296 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4297 SmallVector<SDValue, 4> MemOps;
4298
4299 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004300 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004301 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4302 MachinePointerInfo(SV), false, false, 8));
4303
4304 // void *__gr_top at offset 8
4305 int GPRSize = FuncInfo->getVarArgsGPRSize();
4306 if (GPRSize > 0) {
4307 SDValue GRTop, GRTopAddr;
4308
Mehdi Amini44ede332015-07-09 02:09:04 +00004309 GRTopAddr =
4310 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004311
Mehdi Amini44ede332015-07-09 02:09:04 +00004312 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4313 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4314 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004315
4316 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4317 MachinePointerInfo(SV, 8), false, false, 8));
4318 }
4319
4320 // void *__vr_top at offset 16
4321 int FPRSize = FuncInfo->getVarArgsFPRSize();
4322 if (FPRSize > 0) {
4323 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004324 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4325 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004326
Mehdi Amini44ede332015-07-09 02:09:04 +00004327 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4328 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4329 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004330
4331 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4332 MachinePointerInfo(SV, 16), false, false, 8));
4333 }
4334
4335 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004336 SDValue GROffsAddr =
4337 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004338 MemOps.push_back(DAG.getStore(Chain, DL,
4339 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004340 GROffsAddr, MachinePointerInfo(SV, 24), false,
4341 false, 4));
4342
4343 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004344 SDValue VROffsAddr =
4345 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004346 MemOps.push_back(DAG.getStore(Chain, DL,
4347 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004348 VROffsAddr, MachinePointerInfo(SV, 28), false,
4349 false, 4));
4350
4351 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4352}
4353
4354SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4355 SelectionDAG &DAG) const {
4356 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4357 : LowerAAPCS_VASTART(Op, DAG);
4358}
4359
4360SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4361 SelectionDAG &DAG) const {
4362 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4363 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004364 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004365 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4366 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4367 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4368
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004369 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4370 Op.getOperand(2),
4371 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004372 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004373 MachinePointerInfo(SrcSV));
4374}
4375
4376SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4377 assert(Subtarget->isTargetDarwin() &&
4378 "automatic va_arg instruction only works on Darwin");
4379
4380 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4381 EVT VT = Op.getValueType();
4382 SDLoc DL(Op);
4383 SDValue Chain = Op.getOperand(0);
4384 SDValue Addr = Op.getOperand(1);
4385 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004386 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004387
Mehdi Amini44ede332015-07-09 02:09:04 +00004388 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4389 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004390 Chain = VAList.getValue(1);
4391
4392 if (Align > 8) {
4393 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004394 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4395 DAG.getConstant(Align - 1, DL, PtrVT));
4396 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4397 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004398 }
4399
4400 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004401 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004402
4403 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4404 // up to 64 bits. At the very least, we have to increase the striding of the
4405 // vaargs list to match this, and for FP values we need to introduce
4406 // FP_ROUND nodes as well.
4407 if (VT.isInteger() && !VT.isVector())
4408 ArgSize = 8;
4409 bool NeedFPTrunc = false;
4410 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4411 ArgSize = 8;
4412 NeedFPTrunc = true;
4413 }
4414
4415 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004416 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4417 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004418 // Store the incremented VAList to the legalized pointer
4419 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4420 false, false, 0);
4421
4422 // Load the actual argument out of the pointer VAList
4423 if (NeedFPTrunc) {
4424 // Load the value as an f64.
4425 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4426 MachinePointerInfo(), false, false, false, 0);
4427 // Round the value down to an f32.
4428 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004429 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004430 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4431 // Merge the rounded value with the chain output of the load.
4432 return DAG.getMergeValues(Ops, DL);
4433 }
4434
4435 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4436 false, false, 0);
4437}
4438
4439SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4440 SelectionDAG &DAG) const {
4441 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4442 MFI->setFrameAddressIsTaken(true);
4443
4444 EVT VT = Op.getValueType();
4445 SDLoc DL(Op);
4446 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4447 SDValue FrameAddr =
4448 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4449 while (Depth--)
4450 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4451 MachinePointerInfo(), false, false, false, 0);
4452 return FrameAddr;
4453}
4454
4455// FIXME? Maybe this could be a TableGen attribute on some registers and
4456// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004457unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4458 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004459 unsigned Reg = StringSwitch<unsigned>(RegName)
4460 .Case("sp", AArch64::SP)
4461 .Default(0);
4462 if (Reg)
4463 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004464 report_fatal_error(Twine("Invalid register name \""
4465 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004466}
4467
4468SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4469 SelectionDAG &DAG) const {
4470 MachineFunction &MF = DAG.getMachineFunction();
4471 MachineFrameInfo *MFI = MF.getFrameInfo();
4472 MFI->setReturnAddressIsTaken(true);
4473
4474 EVT VT = Op.getValueType();
4475 SDLoc DL(Op);
4476 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4477 if (Depth) {
4478 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004479 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004480 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4481 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4482 MachinePointerInfo(), false, false, false, 0);
4483 }
4484
4485 // Return LR, which contains the return address. Mark it an implicit live-in.
4486 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4487 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4488}
4489
4490/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4491/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4492SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4493 SelectionDAG &DAG) const {
4494 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4495 EVT VT = Op.getValueType();
4496 unsigned VTBits = VT.getSizeInBits();
4497 SDLoc dl(Op);
4498 SDValue ShOpLo = Op.getOperand(0);
4499 SDValue ShOpHi = Op.getOperand(1);
4500 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004501 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4502
4503 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4504
4505 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004506 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004507 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4508
4509 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4510 // is "undef". We wanted 0, so CSEL it directly.
4511 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4512 ISD::SETEQ, dl, DAG);
4513 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4514 HiBitsForLo =
4515 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4516 HiBitsForLo, CCVal, Cmp);
4517
Tim Northover3b0846e2014-05-24 12:50:23 +00004518 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004519 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004520
Tim Northoverf3be9d52015-12-02 00:33:54 +00004521 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4522 SDValue LoForNormalShift =
4523 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004524
Tim Northoverf3be9d52015-12-02 00:33:54 +00004525 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4526 dl, DAG);
4527 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4528 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4529 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4530 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004531
4532 // AArch64 shifts larger than the register width are wrapped rather than
4533 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004534 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4535 SDValue HiForBigShift =
4536 Opc == ISD::SRA
4537 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4538 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4539 : DAG.getConstant(0, dl, VT);
4540 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4541 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004542
4543 SDValue Ops[2] = { Lo, Hi };
4544 return DAG.getMergeValues(Ops, dl);
4545}
4546
Tim Northoverf3be9d52015-12-02 00:33:54 +00004547
Tim Northover3b0846e2014-05-24 12:50:23 +00004548/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4549/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4550SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004551 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004552 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4553 EVT VT = Op.getValueType();
4554 unsigned VTBits = VT.getSizeInBits();
4555 SDLoc dl(Op);
4556 SDValue ShOpLo = Op.getOperand(0);
4557 SDValue ShOpHi = Op.getOperand(1);
4558 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004559
4560 assert(Op.getOpcode() == ISD::SHL_PARTS);
4561 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004562 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004563 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4564
4565 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4566 // is "undef". We wanted 0, so CSEL it directly.
4567 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4568 ISD::SETEQ, dl, DAG);
4569 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4570 LoBitsForHi =
4571 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4572 LoBitsForHi, CCVal, Cmp);
4573
Tim Northover3b0846e2014-05-24 12:50:23 +00004574 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004575 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004576 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4577 SDValue HiForNormalShift =
4578 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004579
Tim Northoverf3be9d52015-12-02 00:33:54 +00004580 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004581
Tim Northoverf3be9d52015-12-02 00:33:54 +00004582 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4583 dl, DAG);
4584 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4585 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4586 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004587
4588 // AArch64 shifts of larger than register sizes are wrapped rather than
4589 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004590 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4591 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4592 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4593 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004594
4595 SDValue Ops[2] = { Lo, Hi };
4596 return DAG.getMergeValues(Ops, dl);
4597}
4598
4599bool AArch64TargetLowering::isOffsetFoldingLegal(
4600 const GlobalAddressSDNode *GA) const {
4601 // The AArch64 target doesn't support folding offsets into global addresses.
4602 return false;
4603}
4604
4605bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4606 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4607 // FIXME: We should be able to handle f128 as well with a clever lowering.
4608 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4609 return true;
4610
4611 if (VT == MVT::f64)
4612 return AArch64_AM::getFP64Imm(Imm) != -1;
4613 else if (VT == MVT::f32)
4614 return AArch64_AM::getFP32Imm(Imm) != -1;
4615 return false;
4616}
4617
4618//===----------------------------------------------------------------------===//
4619// AArch64 Optimization Hooks
4620//===----------------------------------------------------------------------===//
4621
4622//===----------------------------------------------------------------------===//
4623// AArch64 Inline Assembly Support
4624//===----------------------------------------------------------------------===//
4625
4626// Table of Constraints
4627// TODO: This is the current set of constraints supported by ARM for the
4628// compiler, not all of them may make sense, e.g. S may be difficult to support.
4629//
4630// r - A general register
4631// w - An FP/SIMD register of some size in the range v0-v31
4632// x - An FP/SIMD register of some size in the range v0-v15
4633// I - Constant that can be used with an ADD instruction
4634// J - Constant that can be used with a SUB instruction
4635// K - Constant that can be used with a 32-bit logical instruction
4636// L - Constant that can be used with a 64-bit logical instruction
4637// M - Constant that can be used as a 32-bit MOV immediate
4638// N - Constant that can be used as a 64-bit MOV immediate
4639// Q - A memory reference with base register and no offset
4640// S - A symbolic address
4641// Y - Floating point constant zero
4642// Z - Integer constant zero
4643//
4644// Note that general register operands will be output using their 64-bit x
4645// register name, whatever the size of the variable, unless the asm operand
4646// is prefixed by the %w modifier. Floating-point and SIMD register operands
4647// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4648// %q modifier.
4649
4650/// getConstraintType - Given a constraint letter, return the type of
4651/// constraint it is for this target.
4652AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004653AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004654 if (Constraint.size() == 1) {
4655 switch (Constraint[0]) {
4656 default:
4657 break;
4658 case 'z':
4659 return C_Other;
4660 case 'x':
4661 case 'w':
4662 return C_RegisterClass;
4663 // An address with a single base register. Due to the way we
4664 // currently handle addresses it is the same as 'r'.
4665 case 'Q':
4666 return C_Memory;
4667 }
4668 }
4669 return TargetLowering::getConstraintType(Constraint);
4670}
4671
4672/// Examine constraint type and operand type and determine a weight value.
4673/// This object must already have been set up with the operand type
4674/// and the current alternative constraint selected.
4675TargetLowering::ConstraintWeight
4676AArch64TargetLowering::getSingleConstraintMatchWeight(
4677 AsmOperandInfo &info, const char *constraint) const {
4678 ConstraintWeight weight = CW_Invalid;
4679 Value *CallOperandVal = info.CallOperandVal;
4680 // If we don't have a value, we can't do a match,
4681 // but allow it at the lowest weight.
4682 if (!CallOperandVal)
4683 return CW_Default;
4684 Type *type = CallOperandVal->getType();
4685 // Look at the constraint type.
4686 switch (*constraint) {
4687 default:
4688 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4689 break;
4690 case 'x':
4691 case 'w':
4692 if (type->isFloatingPointTy() || type->isVectorTy())
4693 weight = CW_Register;
4694 break;
4695 case 'z':
4696 weight = CW_Constant;
4697 break;
4698 }
4699 return weight;
4700}
4701
4702std::pair<unsigned, const TargetRegisterClass *>
4703AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004704 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004705 if (Constraint.size() == 1) {
4706 switch (Constraint[0]) {
4707 case 'r':
4708 if (VT.getSizeInBits() == 64)
4709 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4710 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4711 case 'w':
4712 if (VT == MVT::f32)
4713 return std::make_pair(0U, &AArch64::FPR32RegClass);
4714 if (VT.getSizeInBits() == 64)
4715 return std::make_pair(0U, &AArch64::FPR64RegClass);
4716 if (VT.getSizeInBits() == 128)
4717 return std::make_pair(0U, &AArch64::FPR128RegClass);
4718 break;
4719 // The instructions that this constraint is designed for can
4720 // only take 128-bit registers so just use that regclass.
4721 case 'x':
4722 if (VT.getSizeInBits() == 128)
4723 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4724 break;
4725 }
4726 }
4727 if (StringRef("{cc}").equals_lower(Constraint))
4728 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4729
4730 // Use the default implementation in TargetLowering to convert the register
4731 // constraint into a member of a register class.
4732 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004733 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004734
4735 // Not found as a standard register?
4736 if (!Res.second) {
4737 unsigned Size = Constraint.size();
4738 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4739 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004740 int RegNo;
4741 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4742 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004743 // v0 - v31 are aliases of q0 - q31.
4744 // By default we'll emit v0-v31 for this unless there's a modifier where
4745 // we'll emit the correct register as well.
4746 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4747 Res.second = &AArch64::FPR128RegClass;
4748 }
4749 }
4750 }
4751
4752 return Res;
4753}
4754
4755/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4756/// vector. If it is invalid, don't add anything to Ops.
4757void AArch64TargetLowering::LowerAsmOperandForConstraint(
4758 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4759 SelectionDAG &DAG) const {
4760 SDValue Result;
4761
4762 // Currently only support length 1 constraints.
4763 if (Constraint.length() != 1)
4764 return;
4765
4766 char ConstraintLetter = Constraint[0];
4767 switch (ConstraintLetter) {
4768 default:
4769 break;
4770
4771 // This set of constraints deal with valid constants for various instructions.
4772 // Validate and return a target constant for them if we can.
4773 case 'z': {
4774 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004775 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004776 return;
4777
4778 if (Op.getValueType() == MVT::i64)
4779 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4780 else
4781 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4782 break;
4783 }
4784
4785 case 'I':
4786 case 'J':
4787 case 'K':
4788 case 'L':
4789 case 'M':
4790 case 'N':
4791 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4792 if (!C)
4793 return;
4794
4795 // Grab the value and do some validation.
4796 uint64_t CVal = C->getZExtValue();
4797 switch (ConstraintLetter) {
4798 // The I constraint applies only to simple ADD or SUB immediate operands:
4799 // i.e. 0 to 4095 with optional shift by 12
4800 // The J constraint applies only to ADD or SUB immediates that would be
4801 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4802 // instruction [or vice versa], in other words -1 to -4095 with optional
4803 // left shift by 12.
4804 case 'I':
4805 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4806 break;
4807 return;
4808 case 'J': {
4809 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004810 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4811 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004812 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004813 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004814 return;
4815 }
4816 // The K and L constraints apply *only* to logical immediates, including
4817 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4818 // been removed and MOV should be used). So these constraints have to
4819 // distinguish between bit patterns that are valid 32-bit or 64-bit
4820 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4821 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4822 // versa.
4823 case 'K':
4824 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4825 break;
4826 return;
4827 case 'L':
4828 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4829 break;
4830 return;
4831 // The M and N constraints are a superset of K and L respectively, for use
4832 // with the MOV (immediate) alias. As well as the logical immediates they
4833 // also match 32 or 64-bit immediates that can be loaded either using a
4834 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4835 // (M) or 64-bit 0x1234000000000000 (N) etc.
4836 // As a note some of this code is liberally stolen from the asm parser.
4837 case 'M': {
4838 if (!isUInt<32>(CVal))
4839 return;
4840 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4841 break;
4842 if ((CVal & 0xFFFF) == CVal)
4843 break;
4844 if ((CVal & 0xFFFF0000ULL) == CVal)
4845 break;
4846 uint64_t NCVal = ~(uint32_t)CVal;
4847 if ((NCVal & 0xFFFFULL) == NCVal)
4848 break;
4849 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4850 break;
4851 return;
4852 }
4853 case 'N': {
4854 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4855 break;
4856 if ((CVal & 0xFFFFULL) == CVal)
4857 break;
4858 if ((CVal & 0xFFFF0000ULL) == CVal)
4859 break;
4860 if ((CVal & 0xFFFF00000000ULL) == CVal)
4861 break;
4862 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4863 break;
4864 uint64_t NCVal = ~CVal;
4865 if ((NCVal & 0xFFFFULL) == NCVal)
4866 break;
4867 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4868 break;
4869 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4870 break;
4871 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4872 break;
4873 return;
4874 }
4875 default:
4876 return;
4877 }
4878
4879 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004880 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004881 break;
4882 }
4883
4884 if (Result.getNode()) {
4885 Ops.push_back(Result);
4886 return;
4887 }
4888
4889 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4890}
4891
4892//===----------------------------------------------------------------------===//
4893// AArch64 Advanced SIMD Support
4894//===----------------------------------------------------------------------===//
4895
4896/// WidenVector - Given a value in the V64 register class, produce the
4897/// equivalent value in the V128 register class.
4898static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4899 EVT VT = V64Reg.getValueType();
4900 unsigned NarrowSize = VT.getVectorNumElements();
4901 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4902 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4903 SDLoc DL(V64Reg);
4904
4905 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004906 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004907}
4908
4909/// getExtFactor - Determine the adjustment factor for the position when
4910/// generating an "extract from vector registers" instruction.
4911static unsigned getExtFactor(SDValue &V) {
4912 EVT EltType = V.getValueType().getVectorElementType();
4913 return EltType.getSizeInBits() / 8;
4914}
4915
4916/// NarrowVector - Given a value in the V128 register class, produce the
4917/// equivalent value in the V64 register class.
4918static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4919 EVT VT = V128Reg.getValueType();
4920 unsigned WideSize = VT.getVectorNumElements();
4921 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4922 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4923 SDLoc DL(V128Reg);
4924
4925 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4926}
4927
4928// Gather data to see if the operation can be modelled as a
4929// shuffle in combination with VEXTs.
4930SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4931 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004932 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004933 SDLoc dl(Op);
4934 EVT VT = Op.getValueType();
4935 unsigned NumElts = VT.getVectorNumElements();
4936
Tim Northover7324e842014-07-24 15:39:55 +00004937 struct ShuffleSourceInfo {
4938 SDValue Vec;
4939 unsigned MinElt;
4940 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004941
Tim Northover7324e842014-07-24 15:39:55 +00004942 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4943 // be compatible with the shuffle we intend to construct. As a result
4944 // ShuffleVec will be some sliding window into the original Vec.
4945 SDValue ShuffleVec;
4946
4947 // Code should guarantee that element i in Vec starts at element "WindowBase
4948 // + i * WindowScale in ShuffleVec".
4949 int WindowBase;
4950 int WindowScale;
4951
4952 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4953 ShuffleSourceInfo(SDValue Vec)
4954 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4955 WindowScale(1) {}
4956 };
4957
4958 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4959 // node.
4960 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004961 for (unsigned i = 0; i < NumElts; ++i) {
4962 SDValue V = Op.getOperand(i);
4963 if (V.getOpcode() == ISD::UNDEF)
4964 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004965 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4966 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004967 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004968 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00004969 return SDValue();
4970 }
4971
Tim Northover7324e842014-07-24 15:39:55 +00004972 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004973 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004974 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4975 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004976 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004977
Tim Northover7324e842014-07-24 15:39:55 +00004978 // Update the minimum and maximum lane number seen.
4979 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4980 Source->MinElt = std::min(Source->MinElt, EltNo);
4981 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004982 }
4983
4984 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004985 // are involved.
4986 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004987 return SDValue();
4988
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004989 // Find out the smallest element size among result and two sources, and use
4990 // it as element size to build the shuffle_vector.
4991 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004992 for (auto &Source : Sources) {
4993 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004994 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4995 SmallestEltTy = SrcEltTy;
4996 }
4997 }
4998 unsigned ResMultiplier =
4999 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005000 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5001 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005002
Tim Northover7324e842014-07-24 15:39:55 +00005003 // If the source vector is too wide or too narrow, we may nevertheless be able
5004 // to construct a compatible shuffle either by concatenating it with UNDEF or
5005 // extracting a suitable range of elements.
5006 for (auto &Src : Sources) {
5007 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005008
Tim Northover7324e842014-07-24 15:39:55 +00005009 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005010 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005011
5012 // This stage of the search produces a source with the same element type as
5013 // the original, but with a total width matching the BUILD_VECTOR output.
5014 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005015 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5016 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005017
5018 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5019 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005020 // We can pad out the smaller vector for free, so if it's part of a
5021 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005022 Src.ShuffleVec =
5023 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5024 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005025 continue;
5026 }
5027
Tim Northover7324e842014-07-24 15:39:55 +00005028 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005029
James Molloyf497d552014-10-17 17:06:31 +00005030 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005031 // Span too large for a VEXT to cope
5032 return SDValue();
5033 }
5034
James Molloyf497d552014-10-17 17:06:31 +00005035 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005036 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005037 Src.ShuffleVec =
5038 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005039 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005040 Src.WindowBase = -NumSrcElts;
5041 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005042 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005043 Src.ShuffleVec =
5044 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005045 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005046 } else {
5047 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005048 SDValue VEXTSrc1 =
5049 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005050 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005051 SDValue VEXTSrc2 =
5052 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005053 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005054 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5055
5056 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005057 VEXTSrc2,
5058 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005059 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005060 }
5061 }
5062
Tim Northover7324e842014-07-24 15:39:55 +00005063 // Another possible incompatibility occurs from the vector element types. We
5064 // can fix this by bitcasting the source vectors to the same type we intend
5065 // for the shuffle.
5066 for (auto &Src : Sources) {
5067 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5068 if (SrcEltTy == SmallestEltTy)
5069 continue;
5070 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5071 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5072 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5073 Src.WindowBase *= Src.WindowScale;
5074 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005075
Tim Northover7324e842014-07-24 15:39:55 +00005076 // Final sanity check before we try to actually produce a shuffle.
5077 DEBUG(
5078 for (auto Src : Sources)
5079 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5080 );
5081
5082 // The stars all align, our next step is to produce the mask for the shuffle.
5083 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5084 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005085 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005086 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00005087 if (Entry.getOpcode() == ISD::UNDEF)
5088 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005089
Tim Northover7324e842014-07-24 15:39:55 +00005090 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5091 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5092
5093 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5094 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5095 // segment.
5096 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5097 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5098 VT.getVectorElementType().getSizeInBits());
5099 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5100
5101 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5102 // starting at the appropriate offset.
5103 int *LaneMask = &Mask[i * ResMultiplier];
5104
5105 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5106 ExtractBase += NumElts * (Src - Sources.begin());
5107 for (int j = 0; j < LanesDefined; ++j)
5108 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005109 }
5110
5111 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005112 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5113 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005114
Tim Northover7324e842014-07-24 15:39:55 +00005115 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5116 for (unsigned i = 0; i < Sources.size(); ++i)
5117 ShuffleOps[i] = Sources[i].ShuffleVec;
5118
5119 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5120 ShuffleOps[1], &Mask[0]);
5121 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005122}
5123
5124// check if an EXT instruction can handle the shuffle mask when the
5125// vector sources of the shuffle are the same.
5126static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5127 unsigned NumElts = VT.getVectorNumElements();
5128
5129 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5130 if (M[0] < 0)
5131 return false;
5132
5133 Imm = M[0];
5134
5135 // If this is a VEXT shuffle, the immediate value is the index of the first
5136 // element. The other shuffle indices must be the successive elements after
5137 // the first one.
5138 unsigned ExpectedElt = Imm;
5139 for (unsigned i = 1; i < NumElts; ++i) {
5140 // Increment the expected index. If it wraps around, just follow it
5141 // back to index zero and keep going.
5142 ++ExpectedElt;
5143 if (ExpectedElt == NumElts)
5144 ExpectedElt = 0;
5145
5146 if (M[i] < 0)
5147 continue; // ignore UNDEF indices
5148 if (ExpectedElt != static_cast<unsigned>(M[i]))
5149 return false;
5150 }
5151
5152 return true;
5153}
5154
5155// check if an EXT instruction can handle the shuffle mask when the
5156// vector sources of the shuffle are different.
5157static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5158 unsigned &Imm) {
5159 // Look for the first non-undef element.
5160 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5161 [](int Elt) {return Elt >= 0;});
5162
5163 // Benefit form APInt to handle overflow when calculating expected element.
5164 unsigned NumElts = VT.getVectorNumElements();
5165 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5166 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5167 // The following shuffle indices must be the successive elements after the
5168 // first real element.
5169 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5170 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5171 if (FirstWrongElt != M.end())
5172 return false;
5173
5174 // The index of an EXT is the first element if it is not UNDEF.
5175 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005176 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005177 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5178 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5179 // ExpectedElt is the last mask index plus 1.
5180 Imm = ExpectedElt.getZExtValue();
5181
5182 // There are two difference cases requiring to reverse input vectors.
5183 // For example, for vector <4 x i32> we have the following cases,
5184 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5185 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5186 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5187 // to reverse two input vectors.
5188 if (Imm < NumElts)
5189 ReverseEXT = true;
5190 else
5191 Imm -= NumElts;
5192
5193 return true;
5194}
5195
5196/// isREVMask - Check if a vector shuffle corresponds to a REV
5197/// instruction with the specified blocksize. (The order of the elements
5198/// within each block of the vector is reversed.)
5199static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5200 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5201 "Only possible block sizes for REV are: 16, 32, 64");
5202
5203 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5204 if (EltSz == 64)
5205 return false;
5206
5207 unsigned NumElts = VT.getVectorNumElements();
5208 unsigned BlockElts = M[0] + 1;
5209 // If the first shuffle index is UNDEF, be optimistic.
5210 if (M[0] < 0)
5211 BlockElts = BlockSize / EltSz;
5212
5213 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5214 return false;
5215
5216 for (unsigned i = 0; i < NumElts; ++i) {
5217 if (M[i] < 0)
5218 continue; // ignore UNDEF indices
5219 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5220 return false;
5221 }
5222
5223 return true;
5224}
5225
5226static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5227 unsigned NumElts = VT.getVectorNumElements();
5228 WhichResult = (M[0] == 0 ? 0 : 1);
5229 unsigned Idx = WhichResult * NumElts / 2;
5230 for (unsigned i = 0; i != NumElts; i += 2) {
5231 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5232 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5233 return false;
5234 Idx += 1;
5235 }
5236
5237 return true;
5238}
5239
5240static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5241 unsigned NumElts = VT.getVectorNumElements();
5242 WhichResult = (M[0] == 0 ? 0 : 1);
5243 for (unsigned i = 0; i != NumElts; ++i) {
5244 if (M[i] < 0)
5245 continue; // ignore UNDEF indices
5246 if ((unsigned)M[i] != 2 * i + WhichResult)
5247 return false;
5248 }
5249
5250 return true;
5251}
5252
5253static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5254 unsigned NumElts = VT.getVectorNumElements();
5255 WhichResult = (M[0] == 0 ? 0 : 1);
5256 for (unsigned i = 0; i < NumElts; i += 2) {
5257 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5258 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5259 return false;
5260 }
5261 return true;
5262}
5263
5264/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5265/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5266/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5267static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5268 unsigned NumElts = VT.getVectorNumElements();
5269 WhichResult = (M[0] == 0 ? 0 : 1);
5270 unsigned Idx = WhichResult * NumElts / 2;
5271 for (unsigned i = 0; i != NumElts; i += 2) {
5272 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5273 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5274 return false;
5275 Idx += 1;
5276 }
5277
5278 return true;
5279}
5280
5281/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5282/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5283/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5284static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5285 unsigned Half = VT.getVectorNumElements() / 2;
5286 WhichResult = (M[0] == 0 ? 0 : 1);
5287 for (unsigned j = 0; j != 2; ++j) {
5288 unsigned Idx = WhichResult;
5289 for (unsigned i = 0; i != Half; ++i) {
5290 int MIdx = M[i + j * Half];
5291 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5292 return false;
5293 Idx += 2;
5294 }
5295 }
5296
5297 return true;
5298}
5299
5300/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5301/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5302/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5303static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5304 unsigned NumElts = VT.getVectorNumElements();
5305 WhichResult = (M[0] == 0 ? 0 : 1);
5306 for (unsigned i = 0; i < NumElts; i += 2) {
5307 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5308 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5309 return false;
5310 }
5311 return true;
5312}
5313
5314static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5315 bool &DstIsLeft, int &Anomaly) {
5316 if (M.size() != static_cast<size_t>(NumInputElements))
5317 return false;
5318
5319 int NumLHSMatch = 0, NumRHSMatch = 0;
5320 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5321
5322 for (int i = 0; i < NumInputElements; ++i) {
5323 if (M[i] == -1) {
5324 ++NumLHSMatch;
5325 ++NumRHSMatch;
5326 continue;
5327 }
5328
5329 if (M[i] == i)
5330 ++NumLHSMatch;
5331 else
5332 LastLHSMismatch = i;
5333
5334 if (M[i] == i + NumInputElements)
5335 ++NumRHSMatch;
5336 else
5337 LastRHSMismatch = i;
5338 }
5339
5340 if (NumLHSMatch == NumInputElements - 1) {
5341 DstIsLeft = true;
5342 Anomaly = LastLHSMismatch;
5343 return true;
5344 } else if (NumRHSMatch == NumInputElements - 1) {
5345 DstIsLeft = false;
5346 Anomaly = LastRHSMismatch;
5347 return true;
5348 }
5349
5350 return false;
5351}
5352
5353static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5354 if (VT.getSizeInBits() != 128)
5355 return false;
5356
5357 unsigned NumElts = VT.getVectorNumElements();
5358
5359 for (int I = 0, E = NumElts / 2; I != E; I++) {
5360 if (Mask[I] != I)
5361 return false;
5362 }
5363
5364 int Offset = NumElts / 2;
5365 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5366 if (Mask[I] != I + SplitLHS * Offset)
5367 return false;
5368 }
5369
5370 return true;
5371}
5372
5373static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5374 SDLoc DL(Op);
5375 EVT VT = Op.getValueType();
5376 SDValue V0 = Op.getOperand(0);
5377 SDValue V1 = Op.getOperand(1);
5378 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5379
5380 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5381 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5382 return SDValue();
5383
5384 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5385
5386 if (!isConcatMask(Mask, VT, SplitV0))
5387 return SDValue();
5388
5389 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5390 VT.getVectorNumElements() / 2);
5391 if (SplitV0) {
5392 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005393 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005394 }
5395 if (V1.getValueType().getSizeInBits() == 128) {
5396 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005397 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005398 }
5399 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5400}
5401
5402/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5403/// the specified operations to build the shuffle.
5404static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5405 SDValue RHS, SelectionDAG &DAG,
5406 SDLoc dl) {
5407 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5408 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5409 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5410
5411 enum {
5412 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5413 OP_VREV,
5414 OP_VDUP0,
5415 OP_VDUP1,
5416 OP_VDUP2,
5417 OP_VDUP3,
5418 OP_VEXT1,
5419 OP_VEXT2,
5420 OP_VEXT3,
5421 OP_VUZPL, // VUZP, left result
5422 OP_VUZPR, // VUZP, right result
5423 OP_VZIPL, // VZIP, left result
5424 OP_VZIPR, // VZIP, right result
5425 OP_VTRNL, // VTRN, left result
5426 OP_VTRNR // VTRN, right result
5427 };
5428
5429 if (OpNum == OP_COPY) {
5430 if (LHSID == (1 * 9 + 2) * 9 + 3)
5431 return LHS;
5432 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5433 return RHS;
5434 }
5435
5436 SDValue OpLHS, OpRHS;
5437 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5438 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5439 EVT VT = OpLHS.getValueType();
5440
5441 switch (OpNum) {
5442 default:
5443 llvm_unreachable("Unknown shuffle opcode!");
5444 case OP_VREV:
5445 // VREV divides the vector in half and swaps within the half.
5446 if (VT.getVectorElementType() == MVT::i32 ||
5447 VT.getVectorElementType() == MVT::f32)
5448 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5449 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005450 if (VT.getVectorElementType() == MVT::i16 ||
5451 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005452 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5453 // vrev <4 x i8> -> REV16
5454 assert(VT.getVectorElementType() == MVT::i8);
5455 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5456 case OP_VDUP0:
5457 case OP_VDUP1:
5458 case OP_VDUP2:
5459 case OP_VDUP3: {
5460 EVT EltTy = VT.getVectorElementType();
5461 unsigned Opcode;
5462 if (EltTy == MVT::i8)
5463 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005464 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005465 Opcode = AArch64ISD::DUPLANE16;
5466 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5467 Opcode = AArch64ISD::DUPLANE32;
5468 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5469 Opcode = AArch64ISD::DUPLANE64;
5470 else
5471 llvm_unreachable("Invalid vector element type?");
5472
5473 if (VT.getSizeInBits() == 64)
5474 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005475 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005476 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5477 }
5478 case OP_VEXT1:
5479 case OP_VEXT2:
5480 case OP_VEXT3: {
5481 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5482 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005483 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005484 }
5485 case OP_VUZPL:
5486 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5487 OpRHS);
5488 case OP_VUZPR:
5489 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5490 OpRHS);
5491 case OP_VZIPL:
5492 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5493 OpRHS);
5494 case OP_VZIPR:
5495 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5496 OpRHS);
5497 case OP_VTRNL:
5498 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5499 OpRHS);
5500 case OP_VTRNR:
5501 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5502 OpRHS);
5503 }
5504}
5505
5506static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5507 SelectionDAG &DAG) {
5508 // Check to see if we can use the TBL instruction.
5509 SDValue V1 = Op.getOperand(0);
5510 SDValue V2 = Op.getOperand(1);
5511 SDLoc DL(Op);
5512
5513 EVT EltVT = Op.getValueType().getVectorElementType();
5514 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5515
5516 SmallVector<SDValue, 8> TBLMask;
5517 for (int Val : ShuffleMask) {
5518 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5519 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005520 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005521 }
5522 }
5523
5524 MVT IndexVT = MVT::v8i8;
5525 unsigned IndexLen = 8;
5526 if (Op.getValueType().getSizeInBits() == 128) {
5527 IndexVT = MVT::v16i8;
5528 IndexLen = 16;
5529 }
5530
5531 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5532 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5533
5534 SDValue Shuffle;
5535 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5536 if (IndexLen == 8)
5537 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5538 Shuffle = DAG.getNode(
5539 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005540 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005541 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5542 makeArrayRef(TBLMask.data(), IndexLen)));
5543 } else {
5544 if (IndexLen == 8) {
5545 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5546 Shuffle = DAG.getNode(
5547 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005548 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005549 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5550 makeArrayRef(TBLMask.data(), IndexLen)));
5551 } else {
5552 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5553 // cannot currently represent the register constraints on the input
5554 // table registers.
5555 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5556 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5557 // &TBLMask[0], IndexLen));
5558 Shuffle = DAG.getNode(
5559 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005560 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5561 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005562 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5563 makeArrayRef(TBLMask.data(), IndexLen)));
5564 }
5565 }
5566 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5567}
5568
5569static unsigned getDUPLANEOp(EVT EltType) {
5570 if (EltType == MVT::i8)
5571 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005572 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005573 return AArch64ISD::DUPLANE16;
5574 if (EltType == MVT::i32 || EltType == MVT::f32)
5575 return AArch64ISD::DUPLANE32;
5576 if (EltType == MVT::i64 || EltType == MVT::f64)
5577 return AArch64ISD::DUPLANE64;
5578
5579 llvm_unreachable("Invalid vector element type?");
5580}
5581
5582SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5583 SelectionDAG &DAG) const {
5584 SDLoc dl(Op);
5585 EVT VT = Op.getValueType();
5586
5587 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5588
5589 // Convert shuffles that are directly supported on NEON to target-specific
5590 // DAG nodes, instead of keeping them as shuffles and matching them again
5591 // during code selection. This is more efficient and avoids the possibility
5592 // of inconsistencies between legalization and selection.
5593 ArrayRef<int> ShuffleMask = SVN->getMask();
5594
5595 SDValue V1 = Op.getOperand(0);
5596 SDValue V2 = Op.getOperand(1);
5597
5598 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5599 V1.getValueType().getSimpleVT())) {
5600 int Lane = SVN->getSplatIndex();
5601 // If this is undef splat, generate it via "just" vdup, if possible.
5602 if (Lane == -1)
5603 Lane = 0;
5604
5605 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5606 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5607 V1.getOperand(0));
5608 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5609 // constant. If so, we can just reference the lane's definition directly.
5610 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5611 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5612 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5613
5614 // Otherwise, duplicate from the lane of the input vector.
5615 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5616
5617 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5618 // to make a vector of the same size as this SHUFFLE. We can ignore the
5619 // extract entirely, and canonicalise the concat using WidenVector.
5620 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5621 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5622 V1 = V1.getOperand(0);
5623 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5624 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5625 Lane -= Idx * VT.getVectorNumElements() / 2;
5626 V1 = WidenVector(V1.getOperand(Idx), DAG);
5627 } else if (VT.getSizeInBits() == 64)
5628 V1 = WidenVector(V1, DAG);
5629
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005630 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005631 }
5632
5633 if (isREVMask(ShuffleMask, VT, 64))
5634 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5635 if (isREVMask(ShuffleMask, VT, 32))
5636 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5637 if (isREVMask(ShuffleMask, VT, 16))
5638 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5639
5640 bool ReverseEXT = false;
5641 unsigned Imm;
5642 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5643 if (ReverseEXT)
5644 std::swap(V1, V2);
5645 Imm *= getExtFactor(V1);
5646 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005647 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005648 } else if (V2->getOpcode() == ISD::UNDEF &&
5649 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5650 Imm *= getExtFactor(V1);
5651 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005652 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005653 }
5654
5655 unsigned WhichResult;
5656 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5657 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5658 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5659 }
5660 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5661 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5662 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5663 }
5664 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5665 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5666 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5667 }
5668
5669 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5670 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5671 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5672 }
5673 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5674 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5675 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5676 }
5677 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5678 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5679 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5680 }
5681
5682 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5683 if (Concat.getNode())
5684 return Concat;
5685
5686 bool DstIsLeft;
5687 int Anomaly;
5688 int NumInputElements = V1.getValueType().getVectorNumElements();
5689 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5690 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005691 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005692
5693 SDValue SrcVec = V1;
5694 int SrcLane = ShuffleMask[Anomaly];
5695 if (SrcLane >= NumInputElements) {
5696 SrcVec = V2;
5697 SrcLane -= VT.getVectorNumElements();
5698 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005699 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005700
5701 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005702
5703 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005704 ScalarVT = MVT::i32;
5705
5706 return DAG.getNode(
5707 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5708 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5709 DstLaneV);
5710 }
5711
5712 // If the shuffle is not directly supported and it has 4 elements, use
5713 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5714 unsigned NumElts = VT.getVectorNumElements();
5715 if (NumElts == 4) {
5716 unsigned PFIndexes[4];
5717 for (unsigned i = 0; i != 4; ++i) {
5718 if (ShuffleMask[i] < 0)
5719 PFIndexes[i] = 8;
5720 else
5721 PFIndexes[i] = ShuffleMask[i];
5722 }
5723
5724 // Compute the index in the perfect shuffle table.
5725 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5726 PFIndexes[2] * 9 + PFIndexes[3];
5727 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5728 unsigned Cost = (PFEntry >> 30);
5729
5730 if (Cost <= 4)
5731 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5732 }
5733
5734 return GenerateTBL(Op, ShuffleMask, DAG);
5735}
5736
5737static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5738 APInt &UndefBits) {
5739 EVT VT = BVN->getValueType(0);
5740 APInt SplatBits, SplatUndef;
5741 unsigned SplatBitSize;
5742 bool HasAnyUndefs;
5743 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5744 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5745
5746 for (unsigned i = 0; i < NumSplats; ++i) {
5747 CnstBits <<= SplatBitSize;
5748 UndefBits <<= SplatBitSize;
5749 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5750 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5751 }
5752
5753 return true;
5754 }
5755
5756 return false;
5757}
5758
5759SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5760 SelectionDAG &DAG) const {
5761 BuildVectorSDNode *BVN =
5762 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5763 SDValue LHS = Op.getOperand(0);
5764 SDLoc dl(Op);
5765 EVT VT = Op.getValueType();
5766
5767 if (!BVN)
5768 return Op;
5769
5770 APInt CnstBits(VT.getSizeInBits(), 0);
5771 APInt UndefBits(VT.getSizeInBits(), 0);
5772 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5773 // We only have BIC vector immediate instruction, which is and-not.
5774 CnstBits = ~CnstBits;
5775
5776 // We make use of a little bit of goto ickiness in order to avoid having to
5777 // duplicate the immediate matching logic for the undef toggled case.
5778 bool SecondTry = false;
5779 AttemptModImm:
5780
5781 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5782 CnstBits = CnstBits.zextOrTrunc(64);
5783 uint64_t CnstVal = CnstBits.getZExtValue();
5784
5785 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5786 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5787 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5788 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005789 DAG.getConstant(CnstVal, dl, MVT::i32),
5790 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005791 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005792 }
5793
5794 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5795 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5796 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5797 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005798 DAG.getConstant(CnstVal, dl, MVT::i32),
5799 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005800 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005801 }
5802
5803 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5804 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5805 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5806 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005807 DAG.getConstant(CnstVal, dl, MVT::i32),
5808 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005809 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005810 }
5811
5812 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5813 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5814 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5815 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005816 DAG.getConstant(CnstVal, dl, MVT::i32),
5817 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005818 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005819 }
5820
5821 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5822 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5823 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5824 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005825 DAG.getConstant(CnstVal, dl, MVT::i32),
5826 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005827 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005828 }
5829
5830 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5831 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5832 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5833 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005834 DAG.getConstant(CnstVal, dl, MVT::i32),
5835 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005836 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005837 }
5838 }
5839
5840 if (SecondTry)
5841 goto FailedModImm;
5842 SecondTry = true;
5843 CnstBits = ~UndefBits;
5844 goto AttemptModImm;
5845 }
5846
5847// We can always fall back to a non-immediate AND.
5848FailedModImm:
5849 return Op;
5850}
5851
5852// Specialized code to quickly find if PotentialBVec is a BuildVector that
5853// consists of only the same constant int value, returned in reference arg
5854// ConstVal
5855static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5856 uint64_t &ConstVal) {
5857 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5858 if (!Bvec)
5859 return false;
5860 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5861 if (!FirstElt)
5862 return false;
5863 EVT VT = Bvec->getValueType(0);
5864 unsigned NumElts = VT.getVectorNumElements();
5865 for (unsigned i = 1; i < NumElts; ++i)
5866 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5867 return false;
5868 ConstVal = FirstElt->getZExtValue();
5869 return true;
5870}
5871
5872static unsigned getIntrinsicID(const SDNode *N) {
5873 unsigned Opcode = N->getOpcode();
5874 switch (Opcode) {
5875 default:
5876 return Intrinsic::not_intrinsic;
5877 case ISD::INTRINSIC_WO_CHAIN: {
5878 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5879 if (IID < Intrinsic::num_intrinsics)
5880 return IID;
5881 return Intrinsic::not_intrinsic;
5882 }
5883 }
5884}
5885
5886// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5887// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5888// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5889// Also, logical shift right -> sri, with the same structure.
5890static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5891 EVT VT = N->getValueType(0);
5892
5893 if (!VT.isVector())
5894 return SDValue();
5895
5896 SDLoc DL(N);
5897
5898 // Is the first op an AND?
5899 const SDValue And = N->getOperand(0);
5900 if (And.getOpcode() != ISD::AND)
5901 return SDValue();
5902
5903 // Is the second op an shl or lshr?
5904 SDValue Shift = N->getOperand(1);
5905 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5906 // or AArch64ISD::VLSHR vector, #shift
5907 unsigned ShiftOpc = Shift.getOpcode();
5908 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5909 return SDValue();
5910 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5911
5912 // Is the shift amount constant?
5913 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5914 if (!C2node)
5915 return SDValue();
5916
5917 // Is the and mask vector all constant?
5918 uint64_t C1;
5919 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5920 return SDValue();
5921
5922 // Is C1 == ~C2, taking into account how much one can shift elements of a
5923 // particular size?
5924 uint64_t C2 = C2node->getZExtValue();
5925 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5926 if (C2 > ElemSizeInBits)
5927 return SDValue();
5928 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5929 if ((C1 & ElemMask) != (~C2 & ElemMask))
5930 return SDValue();
5931
5932 SDValue X = And.getOperand(0);
5933 SDValue Y = Shift.getOperand(0);
5934
5935 unsigned Intrin =
5936 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5937 SDValue ResultSLI =
5938 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005939 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5940 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005941
5942 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5943 DEBUG(N->dump(&DAG));
5944 DEBUG(dbgs() << "into: \n");
5945 DEBUG(ResultSLI->dump(&DAG));
5946
5947 ++NumShiftInserts;
5948 return ResultSLI;
5949}
5950
5951SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5952 SelectionDAG &DAG) const {
5953 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5954 if (EnableAArch64SlrGeneration) {
5955 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5956 if (Res.getNode())
5957 return Res;
5958 }
5959
5960 BuildVectorSDNode *BVN =
5961 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5962 SDValue LHS = Op.getOperand(1);
5963 SDLoc dl(Op);
5964 EVT VT = Op.getValueType();
5965
5966 // OR commutes, so try swapping the operands.
5967 if (!BVN) {
5968 LHS = Op.getOperand(0);
5969 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5970 }
5971 if (!BVN)
5972 return Op;
5973
5974 APInt CnstBits(VT.getSizeInBits(), 0);
5975 APInt UndefBits(VT.getSizeInBits(), 0);
5976 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5977 // We make use of a little bit of goto ickiness in order to avoid having to
5978 // duplicate the immediate matching logic for the undef toggled case.
5979 bool SecondTry = false;
5980 AttemptModImm:
5981
5982 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5983 CnstBits = CnstBits.zextOrTrunc(64);
5984 uint64_t CnstVal = CnstBits.getZExtValue();
5985
5986 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5987 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5988 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5989 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005990 DAG.getConstant(CnstVal, dl, MVT::i32),
5991 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005992 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005993 }
5994
5995 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5996 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5997 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5998 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005999 DAG.getConstant(CnstVal, dl, MVT::i32),
6000 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006001 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006002 }
6003
6004 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6005 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6006 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6007 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006008 DAG.getConstant(CnstVal, dl, MVT::i32),
6009 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006010 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006011 }
6012
6013 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6014 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6015 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6016 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006017 DAG.getConstant(CnstVal, dl, MVT::i32),
6018 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006019 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006020 }
6021
6022 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6023 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6024 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6025 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006026 DAG.getConstant(CnstVal, dl, MVT::i32),
6027 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006028 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006029 }
6030
6031 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6032 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6033 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6034 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006035 DAG.getConstant(CnstVal, dl, MVT::i32),
6036 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006037 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006038 }
6039 }
6040
6041 if (SecondTry)
6042 goto FailedModImm;
6043 SecondTry = true;
6044 CnstBits = UndefBits;
6045 goto AttemptModImm;
6046 }
6047
6048// We can always fall back to a non-immediate OR.
6049FailedModImm:
6050 return Op;
6051}
6052
Kevin Qin4473c192014-07-07 02:45:40 +00006053// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6054// be truncated to fit element width.
6055static SDValue NormalizeBuildVector(SDValue Op,
6056 SelectionDAG &DAG) {
6057 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006058 SDLoc dl(Op);
6059 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006060 EVT EltTy= VT.getVectorElementType();
6061
6062 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6063 return Op;
6064
6065 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006066 for (SDValue Lane : Op->ops()) {
6067 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006068 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006069 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006070 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006071 }
6072 Ops.push_back(Lane);
6073 }
6074 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6075}
6076
6077SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6078 SelectionDAG &DAG) const {
6079 SDLoc dl(Op);
6080 EVT VT = Op.getValueType();
6081 Op = NormalizeBuildVector(Op, DAG);
6082 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006083
6084 APInt CnstBits(VT.getSizeInBits(), 0);
6085 APInt UndefBits(VT.getSizeInBits(), 0);
6086 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6087 // We make use of a little bit of goto ickiness in order to avoid having to
6088 // duplicate the immediate matching logic for the undef toggled case.
6089 bool SecondTry = false;
6090 AttemptModImm:
6091
6092 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6093 CnstBits = CnstBits.zextOrTrunc(64);
6094 uint64_t CnstVal = CnstBits.getZExtValue();
6095
6096 // Certain magic vector constants (used to express things like NOT
6097 // and NEG) are passed through unmodified. This allows codegen patterns
6098 // for these operations to match. Special-purpose patterns will lower
6099 // these immediates to MOVIs if it proves necessary.
6100 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6101 return Op;
6102
6103 // The many faces of MOVI...
6104 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6105 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6106 if (VT.getSizeInBits() == 128) {
6107 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006108 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006109 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006110 }
6111
6112 // Support the V64 version via subregister insertion.
6113 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006114 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006115 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006116 }
6117
6118 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6119 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6120 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6121 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006122 DAG.getConstant(CnstVal, dl, MVT::i32),
6123 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006124 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006125 }
6126
6127 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6128 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6129 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6130 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006131 DAG.getConstant(CnstVal, dl, MVT::i32),
6132 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006133 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006134 }
6135
6136 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6137 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6138 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6139 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006140 DAG.getConstant(CnstVal, dl, MVT::i32),
6141 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006142 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006143 }
6144
6145 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6146 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6147 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6148 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006149 DAG.getConstant(CnstVal, dl, MVT::i32),
6150 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006151 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006152 }
6153
6154 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6155 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6156 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6157 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006158 DAG.getConstant(CnstVal, dl, MVT::i32),
6159 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006160 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006161 }
6162
6163 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6164 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6165 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6166 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006167 DAG.getConstant(CnstVal, dl, MVT::i32),
6168 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006169 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006170 }
6171
6172 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6173 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6174 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6175 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006176 DAG.getConstant(CnstVal, dl, MVT::i32),
6177 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006178 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006179 }
6180
6181 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6182 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6183 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6184 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006185 DAG.getConstant(CnstVal, dl, MVT::i32),
6186 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006187 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006188 }
6189
6190 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6191 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6192 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6193 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006194 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006195 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006196 }
6197
6198 // The few faces of FMOV...
6199 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6200 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6201 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6202 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006203 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006204 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006205 }
6206
6207 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6208 VT.getSizeInBits() == 128) {
6209 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6210 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006211 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006212 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006213 }
6214
6215 // The many faces of MVNI...
6216 CnstVal = ~CnstVal;
6217 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6218 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6219 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6220 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006221 DAG.getConstant(CnstVal, dl, MVT::i32),
6222 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006223 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006224 }
6225
6226 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6227 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6228 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6229 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006230 DAG.getConstant(CnstVal, dl, MVT::i32),
6231 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006232 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006233 }
6234
6235 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6236 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6237 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6238 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006239 DAG.getConstant(CnstVal, dl, MVT::i32),
6240 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006241 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006242 }
6243
6244 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6245 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6246 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6247 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006248 DAG.getConstant(CnstVal, dl, MVT::i32),
6249 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006250 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006251 }
6252
6253 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6254 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6255 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6256 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006257 DAG.getConstant(CnstVal, dl, MVT::i32),
6258 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006259 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006260 }
6261
6262 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6263 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6264 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6265 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006266 DAG.getConstant(CnstVal, dl, MVT::i32),
6267 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006268 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006269 }
6270
6271 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6272 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6273 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6274 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006275 DAG.getConstant(CnstVal, dl, MVT::i32),
6276 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006277 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006278 }
6279
6280 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6281 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6282 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6283 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006284 DAG.getConstant(CnstVal, dl, MVT::i32),
6285 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006286 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006287 }
6288 }
6289
6290 if (SecondTry)
6291 goto FailedModImm;
6292 SecondTry = true;
6293 CnstBits = UndefBits;
6294 goto AttemptModImm;
6295 }
6296FailedModImm:
6297
6298 // Scan through the operands to find some interesting properties we can
6299 // exploit:
6300 // 1) If only one value is used, we can use a DUP, or
6301 // 2) if only the low element is not undef, we can just insert that, or
6302 // 3) if only one constant value is used (w/ some non-constant lanes),
6303 // we can splat the constant value into the whole vector then fill
6304 // in the non-constant lanes.
6305 // 4) FIXME: If different constant values are used, but we can intelligently
6306 // select the values we'll be overwriting for the non-constant
6307 // lanes such that we can directly materialize the vector
6308 // some other way (MOVI, e.g.), we can be sneaky.
6309 unsigned NumElts = VT.getVectorNumElements();
6310 bool isOnlyLowElement = true;
6311 bool usesOnlyOneValue = true;
6312 bool usesOnlyOneConstantValue = true;
6313 bool isConstant = true;
6314 unsigned NumConstantLanes = 0;
6315 SDValue Value;
6316 SDValue ConstantValue;
6317 for (unsigned i = 0; i < NumElts; ++i) {
6318 SDValue V = Op.getOperand(i);
6319 if (V.getOpcode() == ISD::UNDEF)
6320 continue;
6321 if (i > 0)
6322 isOnlyLowElement = false;
6323 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6324 isConstant = false;
6325
6326 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6327 ++NumConstantLanes;
6328 if (!ConstantValue.getNode())
6329 ConstantValue = V;
6330 else if (ConstantValue != V)
6331 usesOnlyOneConstantValue = false;
6332 }
6333
6334 if (!Value.getNode())
6335 Value = V;
6336 else if (V != Value)
6337 usesOnlyOneValue = false;
6338 }
6339
6340 if (!Value.getNode())
6341 return DAG.getUNDEF(VT);
6342
6343 if (isOnlyLowElement)
6344 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6345
6346 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6347 // i32 and try again.
6348 if (usesOnlyOneValue) {
6349 if (!isConstant) {
6350 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6351 Value.getValueType() != VT)
6352 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6353
6354 // This is actually a DUPLANExx operation, which keeps everything vectory.
6355
6356 // DUPLANE works on 128-bit vectors, widen it if necessary.
6357 SDValue Lane = Value.getOperand(1);
6358 Value = Value.getOperand(0);
6359 if (Value.getValueType().getSizeInBits() == 64)
6360 Value = WidenVector(Value, DAG);
6361
6362 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6363 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6364 }
6365
6366 if (VT.getVectorElementType().isFloatingPoint()) {
6367 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006368 EVT EltTy = VT.getVectorElementType();
6369 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6370 "Unsupported floating-point vector type");
6371 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006372 for (unsigned i = 0; i < NumElts; ++i)
6373 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6374 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6375 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6376 Val = LowerBUILD_VECTOR(Val, DAG);
6377 if (Val.getNode())
6378 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6379 }
6380 }
6381
6382 // If there was only one constant value used and for more than one lane,
6383 // start by splatting that value, then replace the non-constant lanes. This
6384 // is better than the default, which will perform a separate initialization
6385 // for each lane.
6386 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6387 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6388 // Now insert the non-constant lanes.
6389 for (unsigned i = 0; i < NumElts; ++i) {
6390 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006391 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006392 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6393 // Note that type legalization likely mucked about with the VT of the
6394 // source operand, so we may have to convert it here before inserting.
6395 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6396 }
6397 }
6398 return Val;
6399 }
6400
6401 // If all elements are constants and the case above didn't get hit, fall back
6402 // to the default expansion, which will generate a load from the constant
6403 // pool.
6404 if (isConstant)
6405 return SDValue();
6406
6407 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6408 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006409 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006410 return shuffle;
6411 }
6412
6413 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6414 // know the default expansion would otherwise fall back on something even
6415 // worse. For a vector with one or two non-undef values, that's
6416 // scalar_to_vector for the elements followed by a shuffle (provided the
6417 // shuffle is valid for the target) and materialization element by element
6418 // on the stack followed by a load for everything else.
6419 if (!isConstant && !usesOnlyOneValue) {
6420 SDValue Vec = DAG.getUNDEF(VT);
6421 SDValue Op0 = Op.getOperand(0);
6422 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6423 unsigned i = 0;
6424 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6425 // a) Avoid a RMW dependency on the full vector register, and
6426 // b) Allow the register coalescer to fold away the copy if the
6427 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006428 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6429 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6430 if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6431 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006432 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6433 MachineSDNode *N =
6434 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006435 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006436 Vec = SDValue(N, 0);
6437 ++i;
6438 }
6439 for (; i < NumElts; ++i) {
6440 SDValue V = Op.getOperand(i);
6441 if (V.getOpcode() == ISD::UNDEF)
6442 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006443 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006444 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6445 }
6446 return Vec;
6447 }
6448
6449 // Just use the default expansion. We failed to find a better alternative.
6450 return SDValue();
6451}
6452
6453SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6454 SelectionDAG &DAG) const {
6455 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6456
Tim Northovere4b8e132014-07-15 10:00:26 +00006457 // Check for non-constant or out of range lane.
6458 EVT VT = Op.getOperand(0).getValueType();
6459 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6460 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006461 return SDValue();
6462
Tim Northover3b0846e2014-05-24 12:50:23 +00006463
6464 // Insertion/extraction are legal for V128 types.
6465 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006466 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6467 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006468 return Op;
6469
6470 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006471 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006472 return SDValue();
6473
6474 // For V64 types, we perform insertion by expanding the value
6475 // to a V128 type and perform the insertion on that.
6476 SDLoc DL(Op);
6477 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6478 EVT WideTy = WideVec.getValueType();
6479
6480 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6481 Op.getOperand(1), Op.getOperand(2));
6482 // Re-narrow the resultant vector.
6483 return NarrowVector(Node, DAG);
6484}
6485
6486SDValue
6487AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6488 SelectionDAG &DAG) const {
6489 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6490
Tim Northovere4b8e132014-07-15 10:00:26 +00006491 // Check for non-constant or out of range lane.
6492 EVT VT = Op.getOperand(0).getValueType();
6493 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6494 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006495 return SDValue();
6496
Tim Northover3b0846e2014-05-24 12:50:23 +00006497
6498 // Insertion/extraction are legal for V128 types.
6499 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006500 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6501 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006502 return Op;
6503
6504 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006505 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006506 return SDValue();
6507
6508 // For V64 types, we perform extraction by expanding the value
6509 // to a V128 type and perform the extraction on that.
6510 SDLoc DL(Op);
6511 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6512 EVT WideTy = WideVec.getValueType();
6513
6514 EVT ExtrTy = WideTy.getVectorElementType();
6515 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6516 ExtrTy = MVT::i32;
6517
6518 // For extractions, we just return the result directly.
6519 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6520 Op.getOperand(1));
6521}
6522
6523SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6524 SelectionDAG &DAG) const {
6525 EVT VT = Op.getOperand(0).getValueType();
6526 SDLoc dl(Op);
6527 // Just in case...
6528 if (!VT.isVector())
6529 return SDValue();
6530
6531 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6532 if (!Cst)
6533 return SDValue();
6534 unsigned Val = Cst->getZExtValue();
6535
6536 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006537
6538 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6539 if (Val == 0)
6540 return Op;
6541
Tim Northover3b0846e2014-05-24 12:50:23 +00006542 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6543 // that directly.
6544 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6545 return Op;
6546
6547 return SDValue();
6548}
6549
6550bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6551 EVT VT) const {
6552 if (VT.getVectorNumElements() == 4 &&
6553 (VT.is128BitVector() || VT.is64BitVector())) {
6554 unsigned PFIndexes[4];
6555 for (unsigned i = 0; i != 4; ++i) {
6556 if (M[i] < 0)
6557 PFIndexes[i] = 8;
6558 else
6559 PFIndexes[i] = M[i];
6560 }
6561
6562 // Compute the index in the perfect shuffle table.
6563 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6564 PFIndexes[2] * 9 + PFIndexes[3];
6565 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6566 unsigned Cost = (PFEntry >> 30);
6567
6568 if (Cost <= 4)
6569 return true;
6570 }
6571
6572 bool DummyBool;
6573 int DummyInt;
6574 unsigned DummyUnsigned;
6575
6576 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6577 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6578 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6579 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6580 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6581 isZIPMask(M, VT, DummyUnsigned) ||
6582 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6583 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6584 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6585 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6586 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6587}
6588
6589/// getVShiftImm - Check if this is a valid build_vector for the immediate
6590/// operand of a vector shift operation, where all the elements of the
6591/// build_vector must have the same constant integer value.
6592static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6593 // Ignore bit_converts.
6594 while (Op.getOpcode() == ISD::BITCAST)
6595 Op = Op.getOperand(0);
6596 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6597 APInt SplatBits, SplatUndef;
6598 unsigned SplatBitSize;
6599 bool HasAnyUndefs;
6600 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6601 HasAnyUndefs, ElementBits) ||
6602 SplatBitSize > ElementBits)
6603 return false;
6604 Cnt = SplatBits.getSExtValue();
6605 return true;
6606}
6607
6608/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6609/// operand of a vector shift left operation. That value must be in the range:
6610/// 0 <= Value < ElementBits for a left shift; or
6611/// 0 <= Value <= ElementBits for a long left shift.
6612static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6613 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006614 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006615 if (!getVShiftImm(Op, ElementBits, Cnt))
6616 return false;
6617 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6618}
6619
6620/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006621/// operand of a vector shift right operation. The value must be in the range:
6622/// 1 <= Value <= ElementBits for a right shift; or
6623static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006624 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006625 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006626 if (!getVShiftImm(Op, ElementBits, Cnt))
6627 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006628 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6629}
6630
6631SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6632 SelectionDAG &DAG) const {
6633 EVT VT = Op.getValueType();
6634 SDLoc DL(Op);
6635 int64_t Cnt;
6636
6637 if (!Op.getOperand(1).getValueType().isVector())
6638 return Op;
6639 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6640
6641 switch (Op.getOpcode()) {
6642 default:
6643 llvm_unreachable("unexpected shift opcode");
6644
6645 case ISD::SHL:
6646 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006647 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6648 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006649 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006650 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6651 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006652 Op.getOperand(0), Op.getOperand(1));
6653 case ISD::SRA:
6654 case ISD::SRL:
6655 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006656 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006657 unsigned Opc =
6658 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006659 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6660 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006661 }
6662
6663 // Right shift register. Note, there is not a shift right register
6664 // instruction, but the shift left register instruction takes a signed
6665 // value, where negative numbers specify a right shift.
6666 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6667 : Intrinsic::aarch64_neon_ushl;
6668 // negate the shift amount
6669 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6670 SDValue NegShiftLeft =
6671 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006672 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6673 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006674 return NegShiftLeft;
6675 }
6676
6677 return SDValue();
6678}
6679
6680static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6681 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6682 SDLoc dl, SelectionDAG &DAG) {
6683 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006684 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6685 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006686
6687 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6688 APInt CnstBits(VT.getSizeInBits(), 0);
6689 APInt UndefBits(VT.getSizeInBits(), 0);
6690 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6691 bool IsZero = IsCnst && (CnstBits == 0);
6692
6693 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6694 switch (CC) {
6695 default:
6696 return SDValue();
6697 case AArch64CC::NE: {
6698 SDValue Fcmeq;
6699 if (IsZero)
6700 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6701 else
6702 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6703 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6704 }
6705 case AArch64CC::EQ:
6706 if (IsZero)
6707 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6708 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6709 case AArch64CC::GE:
6710 if (IsZero)
6711 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6712 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6713 case AArch64CC::GT:
6714 if (IsZero)
6715 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6716 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6717 case AArch64CC::LS:
6718 if (IsZero)
6719 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6720 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6721 case AArch64CC::LT:
6722 if (!NoNans)
6723 return SDValue();
6724 // If we ignore NaNs then we can use to the MI implementation.
6725 // Fallthrough.
6726 case AArch64CC::MI:
6727 if (IsZero)
6728 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6729 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6730 }
6731 }
6732
6733 switch (CC) {
6734 default:
6735 return SDValue();
6736 case AArch64CC::NE: {
6737 SDValue Cmeq;
6738 if (IsZero)
6739 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6740 else
6741 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6742 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6743 }
6744 case AArch64CC::EQ:
6745 if (IsZero)
6746 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6747 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6748 case AArch64CC::GE:
6749 if (IsZero)
6750 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6751 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6752 case AArch64CC::GT:
6753 if (IsZero)
6754 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6755 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6756 case AArch64CC::LE:
6757 if (IsZero)
6758 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6759 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6760 case AArch64CC::LS:
6761 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6762 case AArch64CC::LO:
6763 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6764 case AArch64CC::LT:
6765 if (IsZero)
6766 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6767 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6768 case AArch64CC::HI:
6769 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6770 case AArch64CC::HS:
6771 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6772 }
6773}
6774
6775SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6776 SelectionDAG &DAG) const {
6777 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6778 SDValue LHS = Op.getOperand(0);
6779 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006780 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006781 SDLoc dl(Op);
6782
6783 if (LHS.getValueType().getVectorElementType().isInteger()) {
6784 assert(LHS.getValueType() == RHS.getValueType());
6785 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006786 SDValue Cmp =
6787 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6788 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006789 }
6790
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006791 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6792 return SDValue();
6793
Tim Northover3b0846e2014-05-24 12:50:23 +00006794 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6795 LHS.getValueType().getVectorElementType() == MVT::f64);
6796
6797 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6798 // clean. Some of them require two branches to implement.
6799 AArch64CC::CondCode CC1, CC2;
6800 bool ShouldInvert;
6801 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6802
6803 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6804 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006805 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006806 if (!Cmp.getNode())
6807 return SDValue();
6808
6809 if (CC2 != AArch64CC::AL) {
6810 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006811 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006812 if (!Cmp2.getNode())
6813 return SDValue();
6814
Tim Northover45aa89c2015-02-08 00:50:47 +00006815 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006816 }
6817
Tim Northover45aa89c2015-02-08 00:50:47 +00006818 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6819
Tim Northover3b0846e2014-05-24 12:50:23 +00006820 if (ShouldInvert)
6821 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6822
6823 return Cmp;
6824}
6825
6826/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6827/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6828/// specified in the intrinsic calls.
6829bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6830 const CallInst &I,
6831 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006832 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006833 switch (Intrinsic) {
6834 case Intrinsic::aarch64_neon_ld2:
6835 case Intrinsic::aarch64_neon_ld3:
6836 case Intrinsic::aarch64_neon_ld4:
6837 case Intrinsic::aarch64_neon_ld1x2:
6838 case Intrinsic::aarch64_neon_ld1x3:
6839 case Intrinsic::aarch64_neon_ld1x4:
6840 case Intrinsic::aarch64_neon_ld2lane:
6841 case Intrinsic::aarch64_neon_ld3lane:
6842 case Intrinsic::aarch64_neon_ld4lane:
6843 case Intrinsic::aarch64_neon_ld2r:
6844 case Intrinsic::aarch64_neon_ld3r:
6845 case Intrinsic::aarch64_neon_ld4r: {
6846 Info.opc = ISD::INTRINSIC_W_CHAIN;
6847 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006848 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006849 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6850 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6851 Info.offset = 0;
6852 Info.align = 0;
6853 Info.vol = false; // volatile loads with NEON intrinsics not supported
6854 Info.readMem = true;
6855 Info.writeMem = false;
6856 return true;
6857 }
6858 case Intrinsic::aarch64_neon_st2:
6859 case Intrinsic::aarch64_neon_st3:
6860 case Intrinsic::aarch64_neon_st4:
6861 case Intrinsic::aarch64_neon_st1x2:
6862 case Intrinsic::aarch64_neon_st1x3:
6863 case Intrinsic::aarch64_neon_st1x4:
6864 case Intrinsic::aarch64_neon_st2lane:
6865 case Intrinsic::aarch64_neon_st3lane:
6866 case Intrinsic::aarch64_neon_st4lane: {
6867 Info.opc = ISD::INTRINSIC_VOID;
6868 // Conservatively set memVT to the entire set of vectors stored.
6869 unsigned NumElts = 0;
6870 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6871 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6872 if (!ArgTy->isVectorTy())
6873 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006874 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006875 }
6876 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6877 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6878 Info.offset = 0;
6879 Info.align = 0;
6880 Info.vol = false; // volatile stores with NEON intrinsics not supported
6881 Info.readMem = false;
6882 Info.writeMem = true;
6883 return true;
6884 }
6885 case Intrinsic::aarch64_ldaxr:
6886 case Intrinsic::aarch64_ldxr: {
6887 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6888 Info.opc = ISD::INTRINSIC_W_CHAIN;
6889 Info.memVT = MVT::getVT(PtrTy->getElementType());
6890 Info.ptrVal = I.getArgOperand(0);
6891 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006892 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006893 Info.vol = true;
6894 Info.readMem = true;
6895 Info.writeMem = false;
6896 return true;
6897 }
6898 case Intrinsic::aarch64_stlxr:
6899 case Intrinsic::aarch64_stxr: {
6900 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6901 Info.opc = ISD::INTRINSIC_W_CHAIN;
6902 Info.memVT = MVT::getVT(PtrTy->getElementType());
6903 Info.ptrVal = I.getArgOperand(1);
6904 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006905 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006906 Info.vol = true;
6907 Info.readMem = false;
6908 Info.writeMem = true;
6909 return true;
6910 }
6911 case Intrinsic::aarch64_ldaxp:
6912 case Intrinsic::aarch64_ldxp: {
6913 Info.opc = ISD::INTRINSIC_W_CHAIN;
6914 Info.memVT = MVT::i128;
6915 Info.ptrVal = I.getArgOperand(0);
6916 Info.offset = 0;
6917 Info.align = 16;
6918 Info.vol = true;
6919 Info.readMem = true;
6920 Info.writeMem = false;
6921 return true;
6922 }
6923 case Intrinsic::aarch64_stlxp:
6924 case Intrinsic::aarch64_stxp: {
6925 Info.opc = ISD::INTRINSIC_W_CHAIN;
6926 Info.memVT = MVT::i128;
6927 Info.ptrVal = I.getArgOperand(2);
6928 Info.offset = 0;
6929 Info.align = 16;
6930 Info.vol = true;
6931 Info.readMem = false;
6932 Info.writeMem = true;
6933 return true;
6934 }
6935 default:
6936 break;
6937 }
6938
6939 return false;
6940}
6941
6942// Truncations from 64-bit GPR to 32-bit GPR is free.
6943bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6944 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6945 return false;
6946 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6947 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006948 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006949}
6950bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006951 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006952 return false;
6953 unsigned NumBits1 = VT1.getSizeInBits();
6954 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006955 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006956}
6957
Chad Rosier54390052015-02-23 19:15:16 +00006958/// Check if it is profitable to hoist instruction in then/else to if.
6959/// Not profitable if I and it's user can form a FMA instruction
6960/// because we prefer FMSUB/FMADD.
6961bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6962 if (I->getOpcode() != Instruction::FMul)
6963 return true;
6964
6965 if (I->getNumUses() != 1)
6966 return true;
6967
6968 Instruction *User = I->user_back();
6969
6970 if (User &&
6971 !(User->getOpcode() == Instruction::FSub ||
6972 User->getOpcode() == Instruction::FAdd))
6973 return true;
6974
6975 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006976 const DataLayout &DL = I->getModule()->getDataLayout();
6977 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006978
6979 if (isFMAFasterThanFMulAndFAdd(VT) &&
6980 isOperationLegalOrCustom(ISD::FMA, VT) &&
6981 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6982 return false;
6983
6984 return true;
6985}
6986
Tim Northover3b0846e2014-05-24 12:50:23 +00006987// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6988// 64-bit GPR.
6989bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6990 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6991 return false;
6992 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6993 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006994 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006995}
6996bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006997 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006998 return false;
6999 unsigned NumBits1 = VT1.getSizeInBits();
7000 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007001 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007002}
7003
7004bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7005 EVT VT1 = Val.getValueType();
7006 if (isZExtFree(VT1, VT2)) {
7007 return true;
7008 }
7009
7010 if (Val.getOpcode() != ISD::LOAD)
7011 return false;
7012
7013 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007014 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7015 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7016 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007017}
7018
Quentin Colombet6843ac42015-03-31 20:52:32 +00007019bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7020 if (isa<FPExtInst>(Ext))
7021 return false;
7022
7023 // Vector types are next free.
7024 if (Ext->getType()->isVectorTy())
7025 return false;
7026
7027 for (const Use &U : Ext->uses()) {
7028 // The extension is free if we can fold it with a left shift in an
7029 // addressing mode or an arithmetic operation: add, sub, and cmp.
7030
7031 // Is there a shift?
7032 const Instruction *Instr = cast<Instruction>(U.getUser());
7033
7034 // Is this a constant shift?
7035 switch (Instr->getOpcode()) {
7036 case Instruction::Shl:
7037 if (!isa<ConstantInt>(Instr->getOperand(1)))
7038 return false;
7039 break;
7040 case Instruction::GetElementPtr: {
7041 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007042 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007043 std::advance(GTI, U.getOperandNo());
7044 Type *IdxTy = *GTI;
7045 // This extension will end up with a shift because of the scaling factor.
7046 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7047 // Get the shift amount based on the scaling factor:
7048 // log2(sizeof(IdxTy)) - log2(8).
7049 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007050 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007051 // Is the constant foldable in the shift of the addressing mode?
7052 // I.e., shift amount is between 1 and 4 inclusive.
7053 if (ShiftAmt == 0 || ShiftAmt > 4)
7054 return false;
7055 break;
7056 }
7057 case Instruction::Trunc:
7058 // Check if this is a noop.
7059 // trunc(sext ty1 to ty2) to ty1.
7060 if (Instr->getType() == Ext->getOperand(0)->getType())
7061 continue;
7062 // FALL THROUGH.
7063 default:
7064 return false;
7065 }
7066
7067 // At this point we can use the bfm family, so this extension is free
7068 // for that use.
7069 }
7070 return true;
7071}
7072
Tim Northover3b0846e2014-05-24 12:50:23 +00007073bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7074 unsigned &RequiredAligment) const {
7075 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7076 return false;
7077 // Cyclone supports unaligned accesses.
7078 RequiredAligment = 0;
7079 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7080 return NumBits == 32 || NumBits == 64;
7081}
7082
7083bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7084 unsigned &RequiredAligment) const {
7085 if (!LoadedType.isSimple() ||
7086 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7087 return false;
7088 // Cyclone supports unaligned accesses.
7089 RequiredAligment = 0;
7090 unsigned NumBits = LoadedType.getSizeInBits();
7091 return NumBits == 32 || NumBits == 64;
7092}
7093
Hao Liu7ec8ee32015-06-26 02:32:07 +00007094/// \brief Lower an interleaved load into a ldN intrinsic.
7095///
7096/// E.g. Lower an interleaved load (Factor = 2):
7097/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7098/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7099/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7100///
7101/// Into:
7102/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7103/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7104/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7105bool AArch64TargetLowering::lowerInterleavedLoad(
7106 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7107 ArrayRef<unsigned> Indices, unsigned Factor) const {
7108 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7109 "Invalid interleave factor");
7110 assert(!Shuffles.empty() && "Empty shufflevector input");
7111 assert(Shuffles.size() == Indices.size() &&
7112 "Unmatched number of shufflevectors and indices");
7113
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007114 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007115
7116 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007117 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007118
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007119 // Skip if we do not have NEON and skip illegal vector types.
7120 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007121 return false;
7122
7123 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7124 // load integer vectors first and then convert to pointer vectors.
7125 Type *EltTy = VecTy->getVectorElementType();
7126 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007127 VecTy =
7128 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007129
7130 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7131 Type *Tys[2] = {VecTy, PtrTy};
7132 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7133 Intrinsic::aarch64_neon_ld3,
7134 Intrinsic::aarch64_neon_ld4};
7135 Function *LdNFunc =
7136 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7137
7138 IRBuilder<> Builder(LI);
7139 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7140
7141 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7142
7143 // Replace uses of each shufflevector with the corresponding vector loaded
7144 // by ldN.
7145 for (unsigned i = 0; i < Shuffles.size(); i++) {
7146 ShuffleVectorInst *SVI = Shuffles[i];
7147 unsigned Index = Indices[i];
7148
7149 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7150
7151 // Convert the integer vector to pointer vector if the element is pointer.
7152 if (EltTy->isPointerTy())
7153 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7154
7155 SVI->replaceAllUsesWith(SubVec);
7156 }
7157
7158 return true;
7159}
7160
7161/// \brief Get a mask consisting of sequential integers starting from \p Start.
7162///
7163/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7164static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7165 unsigned NumElts) {
7166 SmallVector<Constant *, 16> Mask;
7167 for (unsigned i = 0; i < NumElts; i++)
7168 Mask.push_back(Builder.getInt32(Start + i));
7169
7170 return ConstantVector::get(Mask);
7171}
7172
7173/// \brief Lower an interleaved store into a stN intrinsic.
7174///
7175/// E.g. Lower an interleaved store (Factor = 3):
7176/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7177/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7178/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7179///
7180/// Into:
7181/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7182/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7183/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7184/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7185///
7186/// Note that the new shufflevectors will be removed and we'll only generate one
7187/// st3 instruction in CodeGen.
7188bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7189 ShuffleVectorInst *SVI,
7190 unsigned Factor) const {
7191 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7192 "Invalid interleave factor");
7193
7194 VectorType *VecTy = SVI->getType();
7195 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7196 "Invalid interleaved store");
7197
7198 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7199 Type *EltTy = VecTy->getVectorElementType();
7200 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7201
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007202 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007203 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007204
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007205 // Skip if we do not have NEON and skip illegal vector types.
7206 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007207 return false;
7208
7209 Value *Op0 = SVI->getOperand(0);
7210 Value *Op1 = SVI->getOperand(1);
7211 IRBuilder<> Builder(SI);
7212
7213 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7214 // vectors to integer vectors.
7215 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007216 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007217 unsigned NumOpElts =
7218 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7219
7220 // Convert to the corresponding integer vector.
7221 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7222 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7223 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7224
7225 SubVecTy = VectorType::get(IntTy, NumSubElts);
7226 }
7227
7228 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7229 Type *Tys[2] = {SubVecTy, PtrTy};
7230 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7231 Intrinsic::aarch64_neon_st3,
7232 Intrinsic::aarch64_neon_st4};
7233 Function *StNFunc =
7234 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7235
7236 SmallVector<Value *, 5> Ops;
7237
7238 // Split the shufflevector operands into sub vectors for the new stN call.
7239 for (unsigned i = 0; i < Factor; i++)
7240 Ops.push_back(Builder.CreateShuffleVector(
7241 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7242
7243 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7244 Builder.CreateCall(StNFunc, Ops);
7245 return true;
7246}
7247
Tim Northover3b0846e2014-05-24 12:50:23 +00007248static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7249 unsigned AlignCheck) {
7250 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7251 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7252}
7253
7254EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7255 unsigned SrcAlign, bool IsMemset,
7256 bool ZeroMemset,
7257 bool MemcpyStrSrc,
7258 MachineFunction &MF) const {
7259 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7260 // instruction to materialize the v2i64 zero and one store (with restrictive
7261 // addressing mode). Just do two i64 store of zero-registers.
7262 bool Fast;
7263 const Function *F = MF.getFunction();
7264 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007265 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007266 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007267 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007268 return MVT::f128;
7269
Lang Hames90333852015-04-09 03:40:33 +00007270 if (Size >= 8 &&
7271 (memOpAlign(SrcAlign, DstAlign, 8) ||
7272 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7273 return MVT::i64;
7274
7275 if (Size >= 4 &&
7276 (memOpAlign(SrcAlign, DstAlign, 4) ||
7277 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007278 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007279
7280 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007281}
7282
7283// 12-bit optionally shifted immediates are legal for adds.
7284bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7285 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7286 return true;
7287 return false;
7288}
7289
7290// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7291// immediates is the same as for an add or a sub.
7292bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7293 if (Immed < 0)
7294 Immed *= -1;
7295 return isLegalAddImmediate(Immed);
7296}
7297
7298/// isLegalAddressingMode - Return true if the addressing mode represented
7299/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007300bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7301 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007302 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007303 // AArch64 has five basic addressing modes:
7304 // reg
7305 // reg + 9-bit signed offset
7306 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7307 // reg1 + reg2
7308 // reg + SIZE_IN_BYTES * reg
7309
7310 // No global is ever allowed as a base.
7311 if (AM.BaseGV)
7312 return false;
7313
7314 // No reg+reg+imm addressing.
7315 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7316 return false;
7317
7318 // check reg + imm case:
7319 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7320 uint64_t NumBytes = 0;
7321 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007322 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007323 NumBytes = NumBits / 8;
7324 if (!isPowerOf2_64(NumBits))
7325 NumBytes = 0;
7326 }
7327
7328 if (!AM.Scale) {
7329 int64_t Offset = AM.BaseOffs;
7330
7331 // 9-bit signed offset
7332 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7333 return true;
7334
7335 // 12-bit unsigned offset
7336 unsigned shift = Log2_64(NumBytes);
7337 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7338 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7339 (Offset >> shift) << shift == Offset)
7340 return true;
7341 return false;
7342 }
7343
7344 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7345
7346 if (!AM.Scale || AM.Scale == 1 ||
7347 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7348 return true;
7349 return false;
7350}
7351
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007352int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7353 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007354 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007355 // Scaling factors are not free at all.
7356 // Operands | Rt Latency
7357 // -------------------------------------------
7358 // Rt, [Xn, Xm] | 4
7359 // -------------------------------------------
7360 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7361 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007362 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007363 // Scale represents reg2 * scale, thus account for 1 if
7364 // it is not equal to 0 or 1.
7365 return AM.Scale != 0 && AM.Scale != 1;
7366 return -1;
7367}
7368
7369bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7370 VT = VT.getScalarType();
7371
7372 if (!VT.isSimple())
7373 return false;
7374
7375 switch (VT.getSimpleVT().SimpleTy) {
7376 case MVT::f32:
7377 case MVT::f64:
7378 return true;
7379 default:
7380 break;
7381 }
7382
7383 return false;
7384}
7385
7386const MCPhysReg *
7387AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7388 // LR is a callee-save register, but we must treat it as clobbered by any call
7389 // site. Hence we include LR in the scratch registers, which are in turn added
7390 // as implicit-defs for stackmaps and patchpoints.
7391 static const MCPhysReg ScratchRegs[] = {
7392 AArch64::X16, AArch64::X17, AArch64::LR, 0
7393 };
7394 return ScratchRegs;
7395}
7396
7397bool
7398AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7399 EVT VT = N->getValueType(0);
7400 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7401 // it with shift to let it be lowered to UBFX.
7402 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7403 isa<ConstantSDNode>(N->getOperand(1))) {
7404 uint64_t TruncMask = N->getConstantOperandVal(1);
7405 if (isMask_64(TruncMask) &&
7406 N->getOperand(0).getOpcode() == ISD::SRL &&
7407 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7408 return false;
7409 }
7410 return true;
7411}
7412
7413bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7414 Type *Ty) const {
7415 assert(Ty->isIntegerTy());
7416
7417 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7418 if (BitSize == 0)
7419 return false;
7420
7421 int64_t Val = Imm.getSExtValue();
7422 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7423 return true;
7424
7425 if ((int64_t)Val < 0)
7426 Val = ~Val;
7427 if (BitSize == 32)
7428 Val &= (1LL << 32) - 1;
7429
7430 unsigned LZ = countLeadingZeros((uint64_t)Val);
7431 unsigned Shift = (63 - LZ) / 16;
7432 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007433 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007434}
7435
7436// Generate SUBS and CSEL for integer abs.
7437static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7438 EVT VT = N->getValueType(0);
7439
7440 SDValue N0 = N->getOperand(0);
7441 SDValue N1 = N->getOperand(1);
7442 SDLoc DL(N);
7443
7444 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7445 // and change it to SUB and CSEL.
7446 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7447 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7448 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7449 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7450 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007451 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007452 N0.getOperand(0));
7453 // Generate SUBS & CSEL.
7454 SDValue Cmp =
7455 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007456 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007457 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007458 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007459 SDValue(Cmp.getNode(), 1));
7460 }
7461 return SDValue();
7462}
7463
7464// performXorCombine - Attempts to handle integer ABS.
7465static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7466 TargetLowering::DAGCombinerInfo &DCI,
7467 const AArch64Subtarget *Subtarget) {
7468 if (DCI.isBeforeLegalizeOps())
7469 return SDValue();
7470
7471 return performIntegerAbsCombine(N, DAG);
7472}
7473
Chad Rosier17020f92014-07-23 14:57:52 +00007474SDValue
7475AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7476 SelectionDAG &DAG,
7477 std::vector<SDNode *> *Created) const {
7478 // fold (sdiv X, pow2)
7479 EVT VT = N->getValueType(0);
7480 if ((VT != MVT::i32 && VT != MVT::i64) ||
7481 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7482 return SDValue();
7483
7484 SDLoc DL(N);
7485 SDValue N0 = N->getOperand(0);
7486 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007487 SDValue Zero = DAG.getConstant(0, DL, VT);
7488 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007489
7490 // Add (N0 < 0) ? Pow2 - 1 : 0;
7491 SDValue CCVal;
7492 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7493 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7494 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7495
7496 if (Created) {
7497 Created->push_back(Cmp.getNode());
7498 Created->push_back(Add.getNode());
7499 Created->push_back(CSel.getNode());
7500 }
7501
7502 // Divide by pow2.
7503 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007504 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007505
7506 // If we're dividing by a positive value, we're done. Otherwise, we must
7507 // negate the result.
7508 if (Divisor.isNonNegative())
7509 return SRA;
7510
7511 if (Created)
7512 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007513 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007514}
7515
Tim Northover3b0846e2014-05-24 12:50:23 +00007516static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7517 TargetLowering::DAGCombinerInfo &DCI,
7518 const AArch64Subtarget *Subtarget) {
7519 if (DCI.isBeforeLegalizeOps())
7520 return SDValue();
7521
7522 // Multiplication of a power of two plus/minus one can be done more
7523 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7524 // future CPUs have a cheaper MADD instruction, this may need to be
7525 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7526 // 64-bit is 5 cycles, so this is always a win.
7527 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7528 APInt Value = C->getAPIntValue();
7529 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007530 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007531 if (Value.isNonNegative()) {
7532 // (mul x, 2^N + 1) => (add (shl x, N), x)
7533 APInt VM1 = Value - 1;
7534 if (VM1.isPowerOf2()) {
7535 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007536 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7537 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7538 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007539 N->getOperand(0));
7540 }
7541 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7542 APInt VP1 = Value + 1;
7543 if (VP1.isPowerOf2()) {
7544 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007545 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7546 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7547 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007548 N->getOperand(0));
7549 }
7550 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007551 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7552 APInt VNP1 = -Value + 1;
7553 if (VNP1.isPowerOf2()) {
7554 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007555 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7556 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7557 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007558 ShiftedVal);
7559 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007560 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7561 APInt VNM1 = -Value - 1;
7562 if (VNM1.isPowerOf2()) {
7563 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007564 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7565 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007566 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007567 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7568 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007569 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007570 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007571 }
7572 return SDValue();
7573}
7574
Jim Grosbachf7502c42014-07-18 00:40:52 +00007575static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7576 SelectionDAG &DAG) {
7577 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7578 // optimize away operation when it's from a constant.
7579 //
7580 // The general transformation is:
7581 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7582 // AND(VECTOR_CMP(x,y), constant2)
7583 // constant2 = UNARYOP(constant)
7584
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007585 // Early exit if this isn't a vector operation, the operand of the
7586 // unary operation isn't a bitwise AND, or if the sizes of the operations
7587 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007588 EVT VT = N->getValueType(0);
7589 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007590 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7591 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007592 return SDValue();
7593
Jim Grosbach724e4382014-07-23 20:41:43 +00007594 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007595 // make the transformation for non-constant splats as well, but it's unclear
7596 // that would be a benefit as it would not eliminate any operations, just
7597 // perform one more step in scalar code before moving to the vector unit.
7598 if (BuildVectorSDNode *BV =
7599 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007600 // Bail out if the vector isn't a constant.
7601 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007602 return SDValue();
7603
7604 // Everything checks out. Build up the new and improved node.
7605 SDLoc DL(N);
7606 EVT IntVT = BV->getValueType(0);
7607 // Create a new constant of the appropriate type for the transformed
7608 // DAG.
7609 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7610 // The AND node needs bitcasts to/from an integer vector type around it.
7611 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7612 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7613 N->getOperand(0)->getOperand(0), MaskConst);
7614 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7615 return Res;
7616 }
7617
7618 return SDValue();
7619}
7620
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007621static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7622 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007623 // First try to optimize away the conversion when it's conditionally from
7624 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007625 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007626 return Res;
7627
Tim Northover3b0846e2014-05-24 12:50:23 +00007628 EVT VT = N->getValueType(0);
7629 if (VT != MVT::f32 && VT != MVT::f64)
7630 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007631
Tim Northover3b0846e2014-05-24 12:50:23 +00007632 // Only optimize when the source and destination types have the same width.
7633 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7634 return SDValue();
7635
7636 // If the result of an integer load is only used by an integer-to-float
7637 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007638 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007639 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007640 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007641 // Do not change the width of a volatile load.
7642 !cast<LoadSDNode>(N0)->isVolatile()) {
7643 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7644 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7645 LN0->getPointerInfo(), LN0->isVolatile(),
7646 LN0->isNonTemporal(), LN0->isInvariant(),
7647 LN0->getAlignment());
7648
7649 // Make sure successors of the original load stay after it by updating them
7650 // to use the new Chain.
7651 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7652
7653 unsigned Opcode =
7654 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7655 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7656 }
7657
7658 return SDValue();
7659}
7660
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007661/// Fold a floating-point multiply by power of two into floating-point to
7662/// fixed-point conversion.
7663static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7664 const AArch64Subtarget *Subtarget) {
7665 if (!Subtarget->hasNEON())
7666 return SDValue();
7667
7668 SDValue Op = N->getOperand(0);
7669 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7670 return SDValue();
7671
7672 SDValue ConstVec = Op->getOperand(1);
7673 if (!isa<BuildVectorSDNode>(ConstVec))
7674 return SDValue();
7675
7676 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7677 uint32_t FloatBits = FloatTy.getSizeInBits();
7678 if (FloatBits != 32 && FloatBits != 64)
7679 return SDValue();
7680
7681 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7682 uint32_t IntBits = IntTy.getSizeInBits();
7683 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7684 return SDValue();
7685
7686 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7687 if (IntBits > FloatBits)
7688 return SDValue();
7689
7690 BitVector UndefElements;
7691 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7692 int32_t Bits = IntBits == 64 ? 64 : 32;
7693 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7694 if (C == -1 || C == 0 || C > Bits)
7695 return SDValue();
7696
7697 MVT ResTy;
7698 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7699 switch (NumLanes) {
7700 default:
7701 return SDValue();
7702 case 2:
7703 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7704 break;
7705 case 4:
7706 ResTy = MVT::v4i32;
7707 break;
7708 }
7709
7710 SDLoc DL(N);
7711 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7712 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7713 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7714 SDValue FixConv =
7715 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7716 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7717 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7718 // We can handle smaller integers by generating an extra trunc.
7719 if (IntBits < FloatBits)
7720 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7721
7722 return FixConv;
7723}
7724
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007725/// Fold a floating-point divide by power of two into fixed-point to
7726/// floating-point conversion.
7727static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7728 const AArch64Subtarget *Subtarget) {
7729 if (!Subtarget->hasNEON())
7730 return SDValue();
7731
7732 SDValue Op = N->getOperand(0);
7733 unsigned Opc = Op->getOpcode();
7734 if (!Op.getValueType().isVector() ||
7735 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7736 return SDValue();
7737
7738 SDValue ConstVec = N->getOperand(1);
7739 if (!isa<BuildVectorSDNode>(ConstVec))
7740 return SDValue();
7741
7742 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7743 int32_t IntBits = IntTy.getSizeInBits();
7744 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7745 return SDValue();
7746
7747 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7748 int32_t FloatBits = FloatTy.getSizeInBits();
7749 if (FloatBits != 32 && FloatBits != 64)
7750 return SDValue();
7751
7752 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7753 if (IntBits > FloatBits)
7754 return SDValue();
7755
7756 BitVector UndefElements;
7757 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7758 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7759 if (C == -1 || C == 0 || C > FloatBits)
7760 return SDValue();
7761
7762 MVT ResTy;
7763 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7764 switch (NumLanes) {
7765 default:
7766 return SDValue();
7767 case 2:
7768 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7769 break;
7770 case 4:
7771 ResTy = MVT::v4i32;
7772 break;
7773 }
7774
7775 SDLoc DL(N);
7776 SDValue ConvInput = Op.getOperand(0);
7777 bool IsSigned = Opc == ISD::SINT_TO_FP;
7778 if (IntBits < FloatBits)
7779 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7780 ResTy, ConvInput);
7781
7782 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7783 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7784 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7785 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7786 DAG.getConstant(C, DL, MVT::i32));
7787}
7788
Tim Northover3b0846e2014-05-24 12:50:23 +00007789/// An EXTR instruction is made up of two shifts, ORed together. This helper
7790/// searches for and classifies those shifts.
7791static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7792 bool &FromHi) {
7793 if (N.getOpcode() == ISD::SHL)
7794 FromHi = false;
7795 else if (N.getOpcode() == ISD::SRL)
7796 FromHi = true;
7797 else
7798 return false;
7799
7800 if (!isa<ConstantSDNode>(N.getOperand(1)))
7801 return false;
7802
7803 ShiftAmount = N->getConstantOperandVal(1);
7804 Src = N->getOperand(0);
7805 return true;
7806}
7807
7808/// EXTR instruction extracts a contiguous chunk of bits from two existing
7809/// registers viewed as a high/low pair. This function looks for the pattern:
7810/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7811/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7812/// independent.
7813static SDValue tryCombineToEXTR(SDNode *N,
7814 TargetLowering::DAGCombinerInfo &DCI) {
7815 SelectionDAG &DAG = DCI.DAG;
7816 SDLoc DL(N);
7817 EVT VT = N->getValueType(0);
7818
7819 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7820
7821 if (VT != MVT::i32 && VT != MVT::i64)
7822 return SDValue();
7823
7824 SDValue LHS;
7825 uint32_t ShiftLHS = 0;
7826 bool LHSFromHi = 0;
7827 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7828 return SDValue();
7829
7830 SDValue RHS;
7831 uint32_t ShiftRHS = 0;
7832 bool RHSFromHi = 0;
7833 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7834 return SDValue();
7835
7836 // If they're both trying to come from the high part of the register, they're
7837 // not really an EXTR.
7838 if (LHSFromHi == RHSFromHi)
7839 return SDValue();
7840
7841 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7842 return SDValue();
7843
7844 if (LHSFromHi) {
7845 std::swap(LHS, RHS);
7846 std::swap(ShiftLHS, ShiftRHS);
7847 }
7848
7849 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007850 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007851}
7852
7853static SDValue tryCombineToBSL(SDNode *N,
7854 TargetLowering::DAGCombinerInfo &DCI) {
7855 EVT VT = N->getValueType(0);
7856 SelectionDAG &DAG = DCI.DAG;
7857 SDLoc DL(N);
7858
7859 if (!VT.isVector())
7860 return SDValue();
7861
7862 SDValue N0 = N->getOperand(0);
7863 if (N0.getOpcode() != ISD::AND)
7864 return SDValue();
7865
7866 SDValue N1 = N->getOperand(1);
7867 if (N1.getOpcode() != ISD::AND)
7868 return SDValue();
7869
7870 // We only have to look for constant vectors here since the general, variable
7871 // case can be handled in TableGen.
7872 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7873 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7874 for (int i = 1; i >= 0; --i)
7875 for (int j = 1; j >= 0; --j) {
7876 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7877 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7878 if (!BVN0 || !BVN1)
7879 continue;
7880
7881 bool FoundMatch = true;
7882 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7883 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7884 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7885 if (!CN0 || !CN1 ||
7886 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7887 FoundMatch = false;
7888 break;
7889 }
7890 }
7891
7892 if (FoundMatch)
7893 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7894 N0->getOperand(1 - i), N1->getOperand(1 - j));
7895 }
7896
7897 return SDValue();
7898}
7899
7900static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7901 const AArch64Subtarget *Subtarget) {
7902 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7903 if (!EnableAArch64ExtrGeneration)
7904 return SDValue();
7905 SelectionDAG &DAG = DCI.DAG;
7906 EVT VT = N->getValueType(0);
7907
7908 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7909 return SDValue();
7910
7911 SDValue Res = tryCombineToEXTR(N, DCI);
7912 if (Res.getNode())
7913 return Res;
7914
7915 Res = tryCombineToBSL(N, DCI);
7916 if (Res.getNode())
7917 return Res;
7918
7919 return SDValue();
7920}
7921
7922static SDValue performBitcastCombine(SDNode *N,
7923 TargetLowering::DAGCombinerInfo &DCI,
7924 SelectionDAG &DAG) {
7925 // Wait 'til after everything is legalized to try this. That way we have
7926 // legal vector types and such.
7927 if (DCI.isBeforeLegalizeOps())
7928 return SDValue();
7929
7930 // Remove extraneous bitcasts around an extract_subvector.
7931 // For example,
7932 // (v4i16 (bitconvert
7933 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7934 // becomes
7935 // (extract_subvector ((v8i16 ...), (i64 4)))
7936
7937 // Only interested in 64-bit vectors as the ultimate result.
7938 EVT VT = N->getValueType(0);
7939 if (!VT.isVector())
7940 return SDValue();
7941 if (VT.getSimpleVT().getSizeInBits() != 64)
7942 return SDValue();
7943 // Is the operand an extract_subvector starting at the beginning or halfway
7944 // point of the vector? A low half may also come through as an
7945 // EXTRACT_SUBREG, so look for that, too.
7946 SDValue Op0 = N->getOperand(0);
7947 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7948 !(Op0->isMachineOpcode() &&
7949 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7950 return SDValue();
7951 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7952 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7953 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7954 return SDValue();
7955 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7956 if (idx != AArch64::dsub)
7957 return SDValue();
7958 // The dsub reference is equivalent to a lane zero subvector reference.
7959 idx = 0;
7960 }
7961 // Look through the bitcast of the input to the extract.
7962 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7963 return SDValue();
7964 SDValue Source = Op0->getOperand(0)->getOperand(0);
7965 // If the source type has twice the number of elements as our destination
7966 // type, we know this is an extract of the high or low half of the vector.
7967 EVT SVT = Source->getValueType(0);
7968 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7969 return SDValue();
7970
7971 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7972
7973 // Create the simplified form to just extract the low or high half of the
7974 // vector directly rather than bothering with the bitcasts.
7975 SDLoc dl(N);
7976 unsigned NumElements = VT.getVectorNumElements();
7977 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007978 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007979 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7980 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007981 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007982 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7983 Source, SubReg),
7984 0);
7985 }
7986}
7987
7988static SDValue performConcatVectorsCombine(SDNode *N,
7989 TargetLowering::DAGCombinerInfo &DCI,
7990 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007991 SDLoc dl(N);
7992 EVT VT = N->getValueType(0);
7993 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7994
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007995 // Optimize concat_vectors of truncated vectors, where the intermediate
7996 // type is illegal, to avoid said illegality, e.g.,
7997 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7998 // (v2i16 (truncate (v2i64)))))
7999 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008000 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8001 // (v4i32 (bitcast (v2i64))),
8002 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008003 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8004 // on both input and result type, so we might generate worse code.
8005 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8006 if (N->getNumOperands() == 2 &&
8007 N0->getOpcode() == ISD::TRUNCATE &&
8008 N1->getOpcode() == ISD::TRUNCATE) {
8009 SDValue N00 = N0->getOperand(0);
8010 SDValue N10 = N1->getOperand(0);
8011 EVT N00VT = N00.getValueType();
8012
8013 if (N00VT == N10.getValueType() &&
8014 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8015 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008016 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8017 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8018 for (size_t i = 0; i < Mask.size(); ++i)
8019 Mask[i] = i * 2;
8020 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8021 DAG.getVectorShuffle(
8022 MidVT, dl,
8023 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8024 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008025 }
8026 }
8027
Tim Northover3b0846e2014-05-24 12:50:23 +00008028 // Wait 'til after everything is legalized to try this. That way we have
8029 // legal vector types and such.
8030 if (DCI.isBeforeLegalizeOps())
8031 return SDValue();
8032
Tim Northover3b0846e2014-05-24 12:50:23 +00008033 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8034 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8035 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008036 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008037 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008038 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008039 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008040 }
8041
8042 // Canonicalise concat_vectors so that the right-hand vector has as few
8043 // bit-casts as possible before its real operation. The primary matching
8044 // destination for these operations will be the narrowing "2" instructions,
8045 // which depend on the operation being performed on this right-hand vector.
8046 // For example,
8047 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8048 // becomes
8049 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8050
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008051 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008052 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008053 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008054 MVT RHSTy = RHS.getValueType().getSimpleVT();
8055 // If the RHS is not a vector, this is not the pattern we're looking for.
8056 if (!RHSTy.isVector())
8057 return SDValue();
8058
8059 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8060
8061 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8062 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008063 return DAG.getNode(ISD::BITCAST, dl, VT,
8064 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8065 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8066 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008067}
8068
8069static SDValue tryCombineFixedPointConvert(SDNode *N,
8070 TargetLowering::DAGCombinerInfo &DCI,
8071 SelectionDAG &DAG) {
8072 // Wait 'til after everything is legalized to try this. That way we have
8073 // legal vector types and such.
8074 if (DCI.isBeforeLegalizeOps())
8075 return SDValue();
8076 // Transform a scalar conversion of a value from a lane extract into a
8077 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8078 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8079 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8080 //
8081 // The second form interacts better with instruction selection and the
8082 // register allocator to avoid cross-class register copies that aren't
8083 // coalescable due to a lane reference.
8084
8085 // Check the operand and see if it originates from a lane extract.
8086 SDValue Op1 = N->getOperand(1);
8087 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8088 // Yep, no additional predication needed. Perform the transform.
8089 SDValue IID = N->getOperand(0);
8090 SDValue Shift = N->getOperand(2);
8091 SDValue Vec = Op1.getOperand(0);
8092 SDValue Lane = Op1.getOperand(1);
8093 EVT ResTy = N->getValueType(0);
8094 EVT VecResTy;
8095 SDLoc DL(N);
8096
8097 // The vector width should be 128 bits by the time we get here, even
8098 // if it started as 64 bits (the extract_vector handling will have
8099 // done so).
8100 assert(Vec.getValueType().getSizeInBits() == 128 &&
8101 "unexpected vector size on extract_vector_elt!");
8102 if (Vec.getValueType() == MVT::v4i32)
8103 VecResTy = MVT::v4f32;
8104 else if (Vec.getValueType() == MVT::v2i64)
8105 VecResTy = MVT::v2f64;
8106 else
Craig Topper2a30d782014-06-18 05:05:13 +00008107 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008108
8109 SDValue Convert =
8110 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8111 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8112 }
8113 return SDValue();
8114}
8115
8116// AArch64 high-vector "long" operations are formed by performing the non-high
8117// version on an extract_subvector of each operand which gets the high half:
8118//
8119// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8120//
8121// However, there are cases which don't have an extract_high explicitly, but
8122// have another operation that can be made compatible with one for free. For
8123// example:
8124//
8125// (dupv64 scalar) --> (extract_high (dup128 scalar))
8126//
8127// This routine does the actual conversion of such DUPs, once outer routines
8128// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008129// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8130// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008131static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008132 switch (N.getOpcode()) {
8133 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008134 case AArch64ISD::DUPLANE8:
8135 case AArch64ISD::DUPLANE16:
8136 case AArch64ISD::DUPLANE32:
8137 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008138 case AArch64ISD::MOVI:
8139 case AArch64ISD::MOVIshift:
8140 case AArch64ISD::MOVIedit:
8141 case AArch64ISD::MOVImsl:
8142 case AArch64ISD::MVNIshift:
8143 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008144 break;
8145 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008146 // FMOV could be supported, but isn't very useful, as it would only occur
8147 // if you passed a bitcast' floating point immediate to an eligible long
8148 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008149 return SDValue();
8150 }
8151
8152 MVT NarrowTy = N.getSimpleValueType();
8153 if (!NarrowTy.is64BitVector())
8154 return SDValue();
8155
8156 MVT ElementTy = NarrowTy.getVectorElementType();
8157 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008158 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008159
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008160 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008161 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8162 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008163 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008164}
8165
8166static bool isEssentiallyExtractSubvector(SDValue N) {
8167 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8168 return true;
8169
8170 return N.getOpcode() == ISD::BITCAST &&
8171 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8172}
8173
8174/// \brief Helper structure to keep track of ISD::SET_CC operands.
8175struct GenericSetCCInfo {
8176 const SDValue *Opnd0;
8177 const SDValue *Opnd1;
8178 ISD::CondCode CC;
8179};
8180
8181/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8182struct AArch64SetCCInfo {
8183 const SDValue *Cmp;
8184 AArch64CC::CondCode CC;
8185};
8186
8187/// \brief Helper structure to keep track of SetCC information.
8188union SetCCInfo {
8189 GenericSetCCInfo Generic;
8190 AArch64SetCCInfo AArch64;
8191};
8192
8193/// \brief Helper structure to be able to read SetCC information. If set to
8194/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8195/// GenericSetCCInfo.
8196struct SetCCInfoAndKind {
8197 SetCCInfo Info;
8198 bool IsAArch64;
8199};
8200
8201/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8202/// an
8203/// AArch64 lowered one.
8204/// \p SetCCInfo is filled accordingly.
8205/// \post SetCCInfo is meanginfull only when this function returns true.
8206/// \return True when Op is a kind of SET_CC operation.
8207static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8208 // If this is a setcc, this is straight forward.
8209 if (Op.getOpcode() == ISD::SETCC) {
8210 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8211 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8212 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8213 SetCCInfo.IsAArch64 = false;
8214 return true;
8215 }
8216 // Otherwise, check if this is a matching csel instruction.
8217 // In other words:
8218 // - csel 1, 0, cc
8219 // - csel 0, 1, !cc
8220 if (Op.getOpcode() != AArch64ISD::CSEL)
8221 return false;
8222 // Set the information about the operands.
8223 // TODO: we want the operands of the Cmp not the csel
8224 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8225 SetCCInfo.IsAArch64 = true;
8226 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8227 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8228
8229 // Check that the operands matches the constraints:
8230 // (1) Both operands must be constants.
8231 // (2) One must be 1 and the other must be 0.
8232 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8233 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8234
8235 // Check (1).
8236 if (!TValue || !FValue)
8237 return false;
8238
8239 // Check (2).
8240 if (!TValue->isOne()) {
8241 // Update the comparison when we are interested in !cc.
8242 std::swap(TValue, FValue);
8243 SetCCInfo.Info.AArch64.CC =
8244 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8245 }
8246 return TValue->isOne() && FValue->isNullValue();
8247}
8248
8249// Returns true if Op is setcc or zext of setcc.
8250static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8251 if (isSetCC(Op, Info))
8252 return true;
8253 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8254 isSetCC(Op->getOperand(0), Info));
8255}
8256
8257// The folding we want to perform is:
8258// (add x, [zext] (setcc cc ...) )
8259// -->
8260// (csel x, (add x, 1), !cc ...)
8261//
8262// The latter will get matched to a CSINC instruction.
8263static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8264 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8265 SDValue LHS = Op->getOperand(0);
8266 SDValue RHS = Op->getOperand(1);
8267 SetCCInfoAndKind InfoAndKind;
8268
8269 // If neither operand is a SET_CC, give up.
8270 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8271 std::swap(LHS, RHS);
8272 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8273 return SDValue();
8274 }
8275
8276 // FIXME: This could be generatized to work for FP comparisons.
8277 EVT CmpVT = InfoAndKind.IsAArch64
8278 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8279 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8280 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8281 return SDValue();
8282
8283 SDValue CCVal;
8284 SDValue Cmp;
8285 SDLoc dl(Op);
8286 if (InfoAndKind.IsAArch64) {
8287 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008288 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8289 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008290 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8291 } else
8292 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8293 *InfoAndKind.Info.Generic.Opnd1,
8294 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8295 CCVal, DAG, dl);
8296
8297 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008298 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008299 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8300}
8301
8302// The basic add/sub long vector instructions have variants with "2" on the end
8303// which act on the high-half of their inputs. They are normally matched by
8304// patterns like:
8305//
8306// (add (zeroext (extract_high LHS)),
8307// (zeroext (extract_high RHS)))
8308// -> uaddl2 vD, vN, vM
8309//
8310// However, if one of the extracts is something like a duplicate, this
8311// instruction can still be used profitably. This function puts the DAG into a
8312// more appropriate form for those patterns to trigger.
8313static SDValue performAddSubLongCombine(SDNode *N,
8314 TargetLowering::DAGCombinerInfo &DCI,
8315 SelectionDAG &DAG) {
8316 if (DCI.isBeforeLegalizeOps())
8317 return SDValue();
8318
8319 MVT VT = N->getSimpleValueType(0);
8320 if (!VT.is128BitVector()) {
8321 if (N->getOpcode() == ISD::ADD)
8322 return performSetccAddFolding(N, DAG);
8323 return SDValue();
8324 }
8325
8326 // Make sure both branches are extended in the same way.
8327 SDValue LHS = N->getOperand(0);
8328 SDValue RHS = N->getOperand(1);
8329 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8330 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8331 LHS.getOpcode() != RHS.getOpcode())
8332 return SDValue();
8333
8334 unsigned ExtType = LHS.getOpcode();
8335
8336 // It's not worth doing if at least one of the inputs isn't already an
8337 // extract, but we don't know which it'll be so we have to try both.
8338 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8339 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8340 if (!RHS.getNode())
8341 return SDValue();
8342
8343 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8344 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8345 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8346 if (!LHS.getNode())
8347 return SDValue();
8348
8349 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8350 }
8351
8352 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8353}
8354
8355// Massage DAGs which we can use the high-half "long" operations on into
8356// something isel will recognize better. E.g.
8357//
8358// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8359// (aarch64_neon_umull (extract_high (v2i64 vec)))
8360// (extract_high (v2i64 (dup128 scalar)))))
8361//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008362static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008363 TargetLowering::DAGCombinerInfo &DCI,
8364 SelectionDAG &DAG) {
8365 if (DCI.isBeforeLegalizeOps())
8366 return SDValue();
8367
Hal Finkelcd8664c2015-12-11 23:11:52 +00008368 SDValue LHS = N->getOperand(1);
8369 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008370 assert(LHS.getValueType().is64BitVector() &&
8371 RHS.getValueType().is64BitVector() &&
8372 "unexpected shape for long operation");
8373
8374 // Either node could be a DUP, but it's not worth doing both of them (you'd
8375 // just as well use the non-high version) so look for a corresponding extract
8376 // operation on the other "wing".
8377 if (isEssentiallyExtractSubvector(LHS)) {
8378 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8379 if (!RHS.getNode())
8380 return SDValue();
8381 } else if (isEssentiallyExtractSubvector(RHS)) {
8382 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8383 if (!LHS.getNode())
8384 return SDValue();
8385 }
8386
Hal Finkelcd8664c2015-12-11 23:11:52 +00008387 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8388 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008389}
8390
8391static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8392 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8393 unsigned ElemBits = ElemTy.getSizeInBits();
8394
8395 int64_t ShiftAmount;
8396 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8397 APInt SplatValue, SplatUndef;
8398 unsigned SplatBitSize;
8399 bool HasAnyUndefs;
8400 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8401 HasAnyUndefs, ElemBits) ||
8402 SplatBitSize != ElemBits)
8403 return SDValue();
8404
8405 ShiftAmount = SplatValue.getSExtValue();
8406 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8407 ShiftAmount = CVN->getSExtValue();
8408 } else
8409 return SDValue();
8410
8411 unsigned Opcode;
8412 bool IsRightShift;
8413 switch (IID) {
8414 default:
8415 llvm_unreachable("Unknown shift intrinsic");
8416 case Intrinsic::aarch64_neon_sqshl:
8417 Opcode = AArch64ISD::SQSHL_I;
8418 IsRightShift = false;
8419 break;
8420 case Intrinsic::aarch64_neon_uqshl:
8421 Opcode = AArch64ISD::UQSHL_I;
8422 IsRightShift = false;
8423 break;
8424 case Intrinsic::aarch64_neon_srshl:
8425 Opcode = AArch64ISD::SRSHR_I;
8426 IsRightShift = true;
8427 break;
8428 case Intrinsic::aarch64_neon_urshl:
8429 Opcode = AArch64ISD::URSHR_I;
8430 IsRightShift = true;
8431 break;
8432 case Intrinsic::aarch64_neon_sqshlu:
8433 Opcode = AArch64ISD::SQSHLU_I;
8434 IsRightShift = false;
8435 break;
8436 }
8437
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008438 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8439 SDLoc dl(N);
8440 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8441 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8442 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8443 SDLoc dl(N);
8444 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8445 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8446 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008447
8448 return SDValue();
8449}
8450
8451// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8452// the intrinsics must be legal and take an i32, this means there's almost
8453// certainly going to be a zext in the DAG which we can eliminate.
8454static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8455 SDValue AndN = N->getOperand(2);
8456 if (AndN.getOpcode() != ISD::AND)
8457 return SDValue();
8458
8459 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8460 if (!CMask || CMask->getZExtValue() != Mask)
8461 return SDValue();
8462
8463 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8464 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8465}
8466
Ahmed Bougachafab58922015-03-10 20:45:38 +00008467static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8468 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008469 SDLoc dl(N);
8470 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8471 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008472 N->getOperand(1).getSimpleValueType(),
8473 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008474 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008475}
8476
Tim Northover3b0846e2014-05-24 12:50:23 +00008477static SDValue performIntrinsicCombine(SDNode *N,
8478 TargetLowering::DAGCombinerInfo &DCI,
8479 const AArch64Subtarget *Subtarget) {
8480 SelectionDAG &DAG = DCI.DAG;
8481 unsigned IID = getIntrinsicID(N);
8482 switch (IID) {
8483 default:
8484 break;
8485 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8486 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8487 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008488 case Intrinsic::aarch64_neon_saddv:
8489 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8490 case Intrinsic::aarch64_neon_uaddv:
8491 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8492 case Intrinsic::aarch64_neon_sminv:
8493 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8494 case Intrinsic::aarch64_neon_uminv:
8495 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8496 case Intrinsic::aarch64_neon_smaxv:
8497 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8498 case Intrinsic::aarch64_neon_umaxv:
8499 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008500 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008501 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008502 N->getOperand(1), N->getOperand(2));
8503 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008504 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008505 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008506 case Intrinsic::aarch64_neon_fmaxnm:
8507 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8508 N->getOperand(1), N->getOperand(2));
8509 case Intrinsic::aarch64_neon_fminnm:
8510 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8511 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008512 case Intrinsic::aarch64_neon_smull:
8513 case Intrinsic::aarch64_neon_umull:
8514 case Intrinsic::aarch64_neon_pmull:
8515 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008516 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008517 case Intrinsic::aarch64_neon_sqshl:
8518 case Intrinsic::aarch64_neon_uqshl:
8519 case Intrinsic::aarch64_neon_sqshlu:
8520 case Intrinsic::aarch64_neon_srshl:
8521 case Intrinsic::aarch64_neon_urshl:
8522 return tryCombineShiftImm(IID, N, DAG);
8523 case Intrinsic::aarch64_crc32b:
8524 case Intrinsic::aarch64_crc32cb:
8525 return tryCombineCRC32(0xff, N, DAG);
8526 case Intrinsic::aarch64_crc32h:
8527 case Intrinsic::aarch64_crc32ch:
8528 return tryCombineCRC32(0xffff, N, DAG);
8529 }
8530 return SDValue();
8531}
8532
8533static SDValue performExtendCombine(SDNode *N,
8534 TargetLowering::DAGCombinerInfo &DCI,
8535 SelectionDAG &DAG) {
8536 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8537 // we can convert that DUP into another extract_high (of a bigger DUP), which
8538 // helps the backend to decide that an sabdl2 would be useful, saving a real
8539 // extract_high operation.
8540 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008541 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008542 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008543 unsigned IID = getIntrinsicID(ABDNode);
8544 if (IID == Intrinsic::aarch64_neon_sabd ||
8545 IID == Intrinsic::aarch64_neon_uabd) {
8546 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8547 if (!NewABD.getNode())
8548 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008549
Hal Finkelcd8664c2015-12-11 23:11:52 +00008550 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8551 NewABD);
8552 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008553 }
8554
8555 // This is effectively a custom type legalization for AArch64.
8556 //
8557 // Type legalization will split an extend of a small, legal, type to a larger
8558 // illegal type by first splitting the destination type, often creating
8559 // illegal source types, which then get legalized in isel-confusing ways,
8560 // leading to really terrible codegen. E.g.,
8561 // %result = v8i32 sext v8i8 %value
8562 // becomes
8563 // %losrc = extract_subreg %value, ...
8564 // %hisrc = extract_subreg %value, ...
8565 // %lo = v4i32 sext v4i8 %losrc
8566 // %hi = v4i32 sext v4i8 %hisrc
8567 // Things go rapidly downhill from there.
8568 //
8569 // For AArch64, the [sz]ext vector instructions can only go up one element
8570 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8571 // take two instructions.
8572 //
8573 // This implies that the most efficient way to do the extend from v8i8
8574 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8575 // the normal splitting to happen for the v8i16->v8i32.
8576
8577 // This is pre-legalization to catch some cases where the default
8578 // type legalization will create ill-tempered code.
8579 if (!DCI.isBeforeLegalizeOps())
8580 return SDValue();
8581
8582 // We're only interested in cleaning things up for non-legal vector types
8583 // here. If both the source and destination are legal, things will just
8584 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008585 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008586 EVT ResVT = N->getValueType(0);
8587 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8588 return SDValue();
8589 // If the vector type isn't a simple VT, it's beyond the scope of what
8590 // we're worried about here. Let legalization do its thing and hope for
8591 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008592 SDValue Src = N->getOperand(0);
8593 EVT SrcVT = Src->getValueType(0);
8594 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008595 return SDValue();
8596
Tim Northover3b0846e2014-05-24 12:50:23 +00008597 // If the source VT is a 64-bit vector, we can play games and get the
8598 // better results we want.
8599 if (SrcVT.getSizeInBits() != 64)
8600 return SDValue();
8601
8602 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8603 unsigned ElementCount = SrcVT.getVectorNumElements();
8604 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8605 SDLoc DL(N);
8606 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8607
8608 // Now split the rest of the operation into two halves, each with a 64
8609 // bit source.
8610 EVT LoVT, HiVT;
8611 SDValue Lo, Hi;
8612 unsigned NumElements = ResVT.getVectorNumElements();
8613 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8614 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8615 ResVT.getVectorElementType(), NumElements / 2);
8616
8617 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8618 LoVT.getVectorNumElements());
8619 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008620 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008621 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008622 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008623 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8624 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8625
8626 // Now combine the parts back together so we still have a single result
8627 // like the combiner expects.
8628 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8629}
8630
8631/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8632/// value. The load store optimizer pass will merge them to store pair stores.
8633/// This has better performance than a splat of the scalar followed by a split
8634/// vector store. Even if the stores are not merged it is four stores vs a dup,
8635/// followed by an ext.b and two stores.
8636static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8637 SDValue StVal = St->getValue();
8638 EVT VT = StVal.getValueType();
8639
8640 // Don't replace floating point stores, they possibly won't be transformed to
8641 // stp because of the store pair suppress pass.
8642 if (VT.isFloatingPoint())
8643 return SDValue();
8644
8645 // Check for insert vector elements.
8646 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8647 return SDValue();
8648
8649 // We can express a splat as store pair(s) for 2 or 4 elements.
8650 unsigned NumVecElts = VT.getVectorNumElements();
8651 if (NumVecElts != 4 && NumVecElts != 2)
8652 return SDValue();
8653 SDValue SplatVal = StVal.getOperand(1);
8654 unsigned RemainInsertElts = NumVecElts - 1;
8655
8656 // Check that this is a splat.
8657 while (--RemainInsertElts) {
8658 SDValue NextInsertElt = StVal.getOperand(0);
8659 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8660 return SDValue();
8661 if (NextInsertElt.getOperand(1) != SplatVal)
8662 return SDValue();
8663 StVal = NextInsertElt;
8664 }
8665 unsigned OrigAlignment = St->getAlignment();
8666 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8667 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8668
8669 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008670 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008671 // Most of the time the three stores should be replaced by store pair
8672 // instructions (stp).
8673 SDLoc DL(St);
8674 SDValue BasePtr = St->getBasePtr();
8675 SDValue NewST1 =
8676 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8677 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8678
8679 unsigned Offset = EltOffset;
8680 while (--NumVecElts) {
8681 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008682 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008683 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8684 St->getPointerInfo(), St->isVolatile(),
8685 St->isNonTemporal(), Alignment);
8686 Offset += EltOffset;
8687 }
8688 return NewST1;
8689}
8690
Tim Northover339c83e2015-11-10 00:44:23 +00008691static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8692 SelectionDAG &DAG,
8693 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008694 if (!DCI.isBeforeLegalize())
8695 return SDValue();
8696
8697 StoreSDNode *S = cast<StoreSDNode>(N);
8698 if (S->isVolatile())
8699 return SDValue();
8700
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008701 // FIXME: The logic for deciding if an unaligned store should be split should
8702 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8703 // a call to that function here.
8704
Tim Northover3b0846e2014-05-24 12:50:23 +00008705 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008706 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008707 if (!Subtarget->isCyclone())
8708 return SDValue();
8709
Sanjay Patel924879a2015-08-04 15:49:57 +00008710 // Don't split at -Oz.
8711 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008712 return SDValue();
8713
8714 SDValue StVal = S->getValue();
8715 EVT VT = StVal.getValueType();
8716
8717 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8718 // those up regresses performance on micro-benchmarks and olden/bh.
8719 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8720 return SDValue();
8721
8722 // Split unaligned 16B stores. They are terrible for performance.
8723 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8724 // extensions can use this to mark that it does not want splitting to happen
8725 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8726 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8727 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8728 S->getAlignment() <= 2)
8729 return SDValue();
8730
8731 // If we get a splat of a scalar convert this vector store to a store of
8732 // scalars. They will be merged into store pairs thereby removing two
8733 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008734 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008735 return ReplacedSplat;
8736
8737 SDLoc DL(S);
8738 unsigned NumElts = VT.getVectorNumElements() / 2;
8739 // Split VT into two.
8740 EVT HalfVT =
8741 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8742 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008743 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008744 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008745 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008746 SDValue BasePtr = S->getBasePtr();
8747 SDValue NewST1 =
8748 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8749 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8750 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008751 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008752 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8753 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8754 S->getAlignment());
8755}
8756
8757/// Target-specific DAG combine function for post-increment LD1 (lane) and
8758/// post-increment LD1R.
8759static SDValue performPostLD1Combine(SDNode *N,
8760 TargetLowering::DAGCombinerInfo &DCI,
8761 bool IsLaneOp) {
8762 if (DCI.isBeforeLegalizeOps())
8763 return SDValue();
8764
8765 SelectionDAG &DAG = DCI.DAG;
8766 EVT VT = N->getValueType(0);
8767
8768 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8769 SDNode *LD = N->getOperand(LoadIdx).getNode();
8770 // If it is not LOAD, can not do such combine.
8771 if (LD->getOpcode() != ISD::LOAD)
8772 return SDValue();
8773
8774 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8775 EVT MemVT = LoadSDN->getMemoryVT();
8776 // Check if memory operand is the same type as the vector element.
8777 if (MemVT != VT.getVectorElementType())
8778 return SDValue();
8779
8780 // Check if there are other uses. If so, do not combine as it will introduce
8781 // an extra load.
8782 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8783 ++UI) {
8784 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8785 continue;
8786 if (*UI != N)
8787 return SDValue();
8788 }
8789
8790 SDValue Addr = LD->getOperand(1);
8791 SDValue Vector = N->getOperand(0);
8792 // Search for a use of the address operand that is an increment.
8793 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8794 Addr.getNode()->use_end(); UI != UE; ++UI) {
8795 SDNode *User = *UI;
8796 if (User->getOpcode() != ISD::ADD
8797 || UI.getUse().getResNo() != Addr.getResNo())
8798 continue;
8799
8800 // Check that the add is independent of the load. Otherwise, folding it
8801 // would create a cycle.
8802 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8803 continue;
8804 // Also check that add is not used in the vector operand. This would also
8805 // create a cycle.
8806 if (User->isPredecessorOf(Vector.getNode()))
8807 continue;
8808
8809 // If the increment is a constant, it must match the memory ref size.
8810 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8811 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8812 uint32_t IncVal = CInc->getZExtValue();
8813 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8814 if (IncVal != NumBytes)
8815 continue;
8816 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8817 }
8818
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008819 // Finally, check that the vector doesn't depend on the load.
8820 // Again, this would create a cycle.
8821 // The load depending on the vector is fine, as that's the case for the
8822 // LD1*post we'll eventually generate anyway.
8823 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8824 continue;
8825
Tim Northover3b0846e2014-05-24 12:50:23 +00008826 SmallVector<SDValue, 8> Ops;
8827 Ops.push_back(LD->getOperand(0)); // Chain
8828 if (IsLaneOp) {
8829 Ops.push_back(Vector); // The vector to be inserted
8830 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8831 }
8832 Ops.push_back(Addr);
8833 Ops.push_back(Inc);
8834
8835 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008836 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008837 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8838 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8839 MemVT,
8840 LoadSDN->getMemOperand());
8841
8842 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008843 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008844 NewResults.push_back(SDValue(LD, 0)); // The result of load
8845 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8846 DCI.CombineTo(LD, NewResults);
8847 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8848 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8849
8850 break;
8851 }
8852 return SDValue();
8853}
8854
Tim Northover339c83e2015-11-10 00:44:23 +00008855/// Simplify \Addr given that the top byte of it is ignored by HW during
8856/// address translation.
8857static bool performTBISimplification(SDValue Addr,
8858 TargetLowering::DAGCombinerInfo &DCI,
8859 SelectionDAG &DAG) {
8860 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8861 APInt KnownZero, KnownOne;
8862 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8863 DCI.isBeforeLegalizeOps());
8864 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8865 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8866 DCI.CommitTargetLoweringOpt(TLO);
8867 return true;
8868 }
8869 return false;
8870}
8871
8872static SDValue performSTORECombine(SDNode *N,
8873 TargetLowering::DAGCombinerInfo &DCI,
8874 SelectionDAG &DAG,
8875 const AArch64Subtarget *Subtarget) {
8876 SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8877 if (Split.getNode())
8878 return Split;
8879
8880 if (Subtarget->supportsAddressTopByteIgnored() &&
8881 performTBISimplification(N->getOperand(2), DCI, DAG))
8882 return SDValue(N, 0);
8883
8884 return SDValue();
8885}
8886
8887 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008888/// LoopVectorizer for the across vector reduction. It consists of
8889/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8890/// are reduced, where s is an induction variable from 0 to
8891/// log2(NumVectorElements).
8892static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8893 unsigned Op,
8894 SelectionDAG &DAG) {
8895 EVT VTy = OpV->getOperand(0).getValueType();
8896 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008897 return SDValue();
8898
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008899 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008900 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8901 if (NumVecElts != 4)
8902 return SDValue();
8903 } else {
8904 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8905 return SDValue();
8906 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008907
8908 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008909 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008910 // Iterate over each step of the across vector reduction.
8911 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008912 SDValue CurOp = PreOp.getOperand(0);
8913 SDValue Shuffle = PreOp.getOperand(1);
8914 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008915 // Try to swap the 1st and 2nd operand as add and min/max instructions
8916 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008917 CurOp = PreOp.getOperand(1);
8918 Shuffle = PreOp.getOperand(0);
8919 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8920 return SDValue();
8921 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008922
8923 // Check if the input vector is fed by the operator we want to handle,
8924 // except the last step; the very first input vector is not necessarily
8925 // the same operator we are handling.
8926 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8927 return SDValue();
8928
Chad Rosier6c36eff2015-09-03 18:13:57 +00008929 // Check if it forms one step of the across vector reduction.
8930 // E.g.,
8931 // %cur = add %1, %0
8932 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8933 // %pre = add %cur, %shuffle
8934 if (Shuffle.getOperand(0) != CurOp)
8935 return SDValue();
8936
8937 int NumMaskElts = 1 << CurStep;
8938 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8939 // Check mask values in each step.
8940 // We expect the shuffle mask in each step follows a specific pattern
8941 // denoted here by the <M, U> form, where M is a sequence of integers
8942 // starting from NumMaskElts, increasing by 1, and the number integers
8943 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8944 // of undef in U should be NumVecElts - NumMaskElts.
8945 // E.g., for <8 x i16>, mask values in each step should be :
8946 // step 0 : <1,u,u,u,u,u,u,u>
8947 // step 1 : <2,3,u,u,u,u,u,u>
8948 // step 2 : <4,5,6,7,u,u,u,u>
8949 for (int i = 0; i < NumVecElts; ++i)
8950 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8951 (i >= NumMaskElts && !(Mask[i] < 0)))
8952 return SDValue();
8953
8954 PreOp = CurOp;
8955 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008956 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008957 bool IsIntrinsic = false;
8958
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008959 switch (Op) {
8960 default:
8961 llvm_unreachable("Unexpected operator for across vector reduction");
8962 case ISD::ADD:
8963 Opcode = AArch64ISD::UADDV;
8964 break;
8965 case ISD::SMAX:
8966 Opcode = AArch64ISD::SMAXV;
8967 break;
8968 case ISD::UMAX:
8969 Opcode = AArch64ISD::UMAXV;
8970 break;
8971 case ISD::SMIN:
8972 Opcode = AArch64ISD::SMINV;
8973 break;
8974 case ISD::UMIN:
8975 Opcode = AArch64ISD::UMINV;
8976 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008977 case ISD::FMAXNUM:
8978 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8979 IsIntrinsic = true;
8980 break;
8981 case ISD::FMINNUM:
8982 Opcode = Intrinsic::aarch64_neon_fminnmv;
8983 IsIntrinsic = true;
8984 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008985 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008986 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00008987
8988 return IsIntrinsic
8989 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8990 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8991 : DAG.getNode(
8992 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8993 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8994 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008995}
8996
8997/// Target-specific DAG combine for the across vector min/max reductions.
8998/// This function specifically handles the final clean-up step of the vector
8999/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9000/// pattern, which narrows down and finds the final min/max value from all
9001/// elements of the vector.
9002/// For example, for a <16 x i8> vector :
9003/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9004/// %smax0 = smax %arr, svn0
9005/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9006/// %smax1 = smax %smax0, %svn1
9007/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9008/// %smax2 = smax %smax1, svn2
9009/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9010/// %sc = setcc %smax2, %svn3, gt
9011/// %n0 = extract_vector_elt %sc, #0
9012/// %n1 = extract_vector_elt %smax2, #0
9013/// %n2 = extract_vector_elt $smax2, #1
9014/// %result = select %n0, %n1, n2
9015/// becomes :
9016/// %1 = smaxv %0
9017/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009018static SDValue
9019performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9020 const AArch64Subtarget *Subtarget) {
9021 if (!Subtarget->hasNEON())
9022 return SDValue();
9023
9024 SDValue N0 = N->getOperand(0);
9025 SDValue IfTrue = N->getOperand(1);
9026 SDValue IfFalse = N->getOperand(2);
9027
9028 // Check if the SELECT merges up the final result of the min/max
9029 // from a vector.
9030 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9031 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9032 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9033 return SDValue();
9034
9035 // Expect N0 is fed by SETCC.
9036 SDValue SetCC = N0.getOperand(0);
9037 EVT SetCCVT = SetCC.getValueType();
9038 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9039 SetCCVT.getVectorElementType() != MVT::i1)
9040 return SDValue();
9041
9042 SDValue VectorOp = SetCC.getOperand(0);
9043 unsigned Op = VectorOp->getOpcode();
9044 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009045 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9046 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009047 return SDValue();
9048
9049 EVT VTy = VectorOp.getValueType();
9050 if (!VTy.isVector())
9051 return SDValue();
9052
Jun Bum Lim0aace132015-10-09 14:11:25 +00009053 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009054 return SDValue();
9055
Jun Bum Lim0aace132015-10-09 14:11:25 +00009056 EVT EltTy = VTy.getVectorElementType();
9057 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9058 if (EltTy != MVT::f32)
9059 return SDValue();
9060 } else {
9061 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9062 return SDValue();
9063 }
9064
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009065 // Check if extracting from the same vector.
9066 // For example,
9067 // %sc = setcc %vector, %svn1, gt
9068 // %n0 = extract_vector_elt %sc, #0
9069 // %n1 = extract_vector_elt %vector, #0
9070 // %n2 = extract_vector_elt $vector, #1
9071 if (!(VectorOp == IfTrue->getOperand(0) &&
9072 VectorOp == IfFalse->getOperand(0)))
9073 return SDValue();
9074
9075 // Check if the condition code is matched with the operator type.
9076 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9077 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9078 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9079 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009080 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9081 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9082 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9083 CC != ISD::SETGE) ||
9084 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9085 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9086 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009087 return SDValue();
9088
9089 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009090 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009091 return SDValue();
9092
9093 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009094 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009095 return SDValue();
9096
9097 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009098 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009099 return SDValue();
9100
9101 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9102}
9103
9104/// Target-specific DAG combine for the across vector add reduction.
9105/// This function specifically handles the final clean-up step of the vector
9106/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9107/// pattern, which adds all elements of a vector together.
9108/// For example, for a <4 x i32> vector :
9109/// %1 = vector_shuffle %0, <2,3,u,u>
9110/// %2 = add %0, %1
9111/// %3 = vector_shuffle %2, <1,u,u,u>
9112/// %4 = add %2, %3
9113/// %result = extract_vector_elt %4, 0
9114/// becomes :
9115/// %0 = uaddv %0
9116/// %result = extract_vector_elt %0, 0
9117static SDValue
9118performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9119 const AArch64Subtarget *Subtarget) {
9120 if (!Subtarget->hasNEON())
9121 return SDValue();
9122 SDValue N0 = N->getOperand(0);
9123 SDValue N1 = N->getOperand(1);
9124
9125 // Check if the input vector is fed by the ADD.
9126 if (N0->getOpcode() != ISD::ADD)
9127 return SDValue();
9128
9129 // The vector extract idx must constant zero because we only expect the final
9130 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009131 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009132 return SDValue();
9133
9134 EVT VTy = N0.getValueType();
9135 if (!VTy.isVector())
9136 return SDValue();
9137
9138 EVT EltTy = VTy.getVectorElementType();
9139 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9140 return SDValue();
9141
Jun Bum Lim0aace132015-10-09 14:11:25 +00009142 if (VTy.getSizeInBits() < 64)
9143 return SDValue();
9144
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009145 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009146}
9147
Tim Northover3b0846e2014-05-24 12:50:23 +00009148/// Target-specific DAG combine function for NEON load/store intrinsics
9149/// to merge base address updates.
9150static SDValue performNEONPostLDSTCombine(SDNode *N,
9151 TargetLowering::DAGCombinerInfo &DCI,
9152 SelectionDAG &DAG) {
9153 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9154 return SDValue();
9155
9156 unsigned AddrOpIdx = N->getNumOperands() - 1;
9157 SDValue Addr = N->getOperand(AddrOpIdx);
9158
9159 // Search for a use of the address operand that is an increment.
9160 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9161 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9162 SDNode *User = *UI;
9163 if (User->getOpcode() != ISD::ADD ||
9164 UI.getUse().getResNo() != Addr.getResNo())
9165 continue;
9166
9167 // Check that the add is independent of the load/store. Otherwise, folding
9168 // it would create a cycle.
9169 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9170 continue;
9171
9172 // Find the new opcode for the updating load/store.
9173 bool IsStore = false;
9174 bool IsLaneOp = false;
9175 bool IsDupOp = false;
9176 unsigned NewOpc = 0;
9177 unsigned NumVecs = 0;
9178 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9179 switch (IntNo) {
9180 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9181 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9182 NumVecs = 2; break;
9183 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9184 NumVecs = 3; break;
9185 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9186 NumVecs = 4; break;
9187 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9188 NumVecs = 2; IsStore = true; break;
9189 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9190 NumVecs = 3; IsStore = true; break;
9191 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9192 NumVecs = 4; IsStore = true; break;
9193 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9194 NumVecs = 2; break;
9195 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9196 NumVecs = 3; break;
9197 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9198 NumVecs = 4; break;
9199 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9200 NumVecs = 2; IsStore = true; break;
9201 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9202 NumVecs = 3; IsStore = true; break;
9203 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9204 NumVecs = 4; IsStore = true; break;
9205 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9206 NumVecs = 2; IsDupOp = true; break;
9207 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9208 NumVecs = 3; IsDupOp = true; break;
9209 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9210 NumVecs = 4; IsDupOp = true; break;
9211 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9212 NumVecs = 2; IsLaneOp = true; break;
9213 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9214 NumVecs = 3; IsLaneOp = true; break;
9215 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9216 NumVecs = 4; IsLaneOp = true; break;
9217 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9218 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9219 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9220 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9221 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9222 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9223 }
9224
9225 EVT VecTy;
9226 if (IsStore)
9227 VecTy = N->getOperand(2).getValueType();
9228 else
9229 VecTy = N->getValueType(0);
9230
9231 // If the increment is a constant, it must match the memory ref size.
9232 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9233 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9234 uint32_t IncVal = CInc->getZExtValue();
9235 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9236 if (IsLaneOp || IsDupOp)
9237 NumBytes /= VecTy.getVectorNumElements();
9238 if (IncVal != NumBytes)
9239 continue;
9240 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9241 }
9242 SmallVector<SDValue, 8> Ops;
9243 Ops.push_back(N->getOperand(0)); // Incoming chain
9244 // Load lane and store have vector list as input.
9245 if (IsLaneOp || IsStore)
9246 for (unsigned i = 2; i < AddrOpIdx; ++i)
9247 Ops.push_back(N->getOperand(i));
9248 Ops.push_back(Addr); // Base register
9249 Ops.push_back(Inc);
9250
9251 // Return Types.
9252 EVT Tys[6];
9253 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9254 unsigned n;
9255 for (n = 0; n < NumResultVecs; ++n)
9256 Tys[n] = VecTy;
9257 Tys[n++] = MVT::i64; // Type of write back register
9258 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009259 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009260
9261 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9262 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9263 MemInt->getMemoryVT(),
9264 MemInt->getMemOperand());
9265
9266 // Update the uses.
9267 std::vector<SDValue> NewResults;
9268 for (unsigned i = 0; i < NumResultVecs; ++i) {
9269 NewResults.push_back(SDValue(UpdN.getNode(), i));
9270 }
9271 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9272 DCI.CombineTo(N, NewResults);
9273 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9274
9275 break;
9276 }
9277 return SDValue();
9278}
9279
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009280// Checks to see if the value is the prescribed width and returns information
9281// about its extension mode.
9282static
9283bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9284 ExtType = ISD::NON_EXTLOAD;
9285 switch(V.getNode()->getOpcode()) {
9286 default:
9287 return false;
9288 case ISD::LOAD: {
9289 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9290 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9291 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9292 ExtType = LoadNode->getExtensionType();
9293 return true;
9294 }
9295 return false;
9296 }
9297 case ISD::AssertSext: {
9298 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9299 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9300 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9301 ExtType = ISD::SEXTLOAD;
9302 return true;
9303 }
9304 return false;
9305 }
9306 case ISD::AssertZext: {
9307 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9308 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9309 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9310 ExtType = ISD::ZEXTLOAD;
9311 return true;
9312 }
9313 return false;
9314 }
9315 case ISD::Constant:
9316 case ISD::TargetConstant: {
Reid Kleckner39ad7c92014-08-29 22:14:26 +00009317 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
Aaron Ballman8ca53882014-09-02 12:19:02 +00009318 1LL << (width - 1))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009319 return true;
9320 return false;
9321 }
9322 }
9323
9324 return true;
9325}
9326
9327// This function does a whole lot of voodoo to determine if the tests are
9328// equivalent without and with a mask. Essentially what happens is that given a
9329// DAG resembling:
9330//
9331// +-------------+ +-------------+ +-------------+ +-------------+
9332// | Input | | AddConstant | | CompConstant| | CC |
9333// +-------------+ +-------------+ +-------------+ +-------------+
9334// | | | |
9335// V V | +----------+
9336// +-------------+ +----+ | |
9337// | ADD | |0xff| | |
9338// +-------------+ +----+ | |
9339// | | | |
9340// V V | |
9341// +-------------+ | |
9342// | AND | | |
9343// +-------------+ | |
9344// | | |
9345// +-----+ | |
9346// | | |
9347// V V V
9348// +-------------+
9349// | CMP |
9350// +-------------+
9351//
9352// The AND node may be safely removed for some combinations of inputs. In
9353// particular we need to take into account the extension type of the Input,
9354// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9355// width of the input (this can work for any width inputs, the above graph is
9356// specific to 8 bits.
9357//
9358// The specific equations were worked out by generating output tables for each
9359// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9360// problem was simplified by working with 4 bit inputs, which means we only
9361// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9362// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9363// patterns present in both extensions (0,7). For every distinct set of
9364// AddConstant and CompConstants bit patterns we can consider the masked and
9365// unmasked versions to be equivalent if the result of this function is true for
9366// all 16 distinct bit patterns of for the current extension type of Input (w0).
9367//
9368// sub w8, w0, w1
9369// and w10, w8, #0x0f
9370// cmp w8, w2
9371// cset w9, AArch64CC
9372// cmp w10, w2
9373// cset w11, AArch64CC
9374// cmp w9, w11
9375// cset w0, eq
9376// ret
9377//
9378// Since the above function shows when the outputs are equivalent it defines
9379// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9380// would be expensive to run during compiles. The equations below were written
9381// in a test harness that confirmed they gave equivalent outputs to the above
9382// for all inputs function, so they can be used determine if the removal is
9383// legal instead.
9384//
9385// isEquivalentMaskless() is the code for testing if the AND can be removed
9386// factored out of the DAG recognition as the DAG can take several forms.
9387
9388static
9389bool isEquivalentMaskless(unsigned CC, unsigned width,
9390 ISD::LoadExtType ExtType, signed AddConstant,
9391 signed CompConstant) {
9392 // By being careful about our equations and only writing the in term
9393 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9394 // make them generally applicable to all bit widths.
9395 signed MaxUInt = (1 << width);
9396
9397 // For the purposes of these comparisons sign extending the type is
9398 // equivalent to zero extending the add and displacing it by half the integer
9399 // width. Provided we are careful and make sure our equations are valid over
9400 // the whole range we can just adjust the input and avoid writing equations
9401 // for sign extended inputs.
9402 if (ExtType == ISD::SEXTLOAD)
9403 AddConstant -= (1 << (width-1));
9404
9405 switch(CC) {
9406 case AArch64CC::LE:
9407 case AArch64CC::GT: {
9408 if ((AddConstant == 0) ||
9409 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9410 (AddConstant >= 0 && CompConstant < 0) ||
9411 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9412 return true;
9413 } break;
9414 case AArch64CC::LT:
9415 case AArch64CC::GE: {
9416 if ((AddConstant == 0) ||
9417 (AddConstant >= 0 && CompConstant <= 0) ||
9418 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9419 return true;
9420 } break;
9421 case AArch64CC::HI:
9422 case AArch64CC::LS: {
9423 if ((AddConstant >= 0 && CompConstant < 0) ||
9424 (AddConstant <= 0 && CompConstant >= -1 &&
9425 CompConstant < AddConstant + MaxUInt))
9426 return true;
9427 } break;
9428 case AArch64CC::PL:
9429 case AArch64CC::MI: {
9430 if ((AddConstant == 0) ||
9431 (AddConstant > 0 && CompConstant <= 0) ||
9432 (AddConstant < 0 && CompConstant <= AddConstant))
9433 return true;
9434 } break;
9435 case AArch64CC::LO:
9436 case AArch64CC::HS: {
9437 if ((AddConstant >= 0 && CompConstant <= 0) ||
9438 (AddConstant <= 0 && CompConstant >= 0 &&
9439 CompConstant <= AddConstant + MaxUInt))
9440 return true;
9441 } break;
9442 case AArch64CC::EQ:
9443 case AArch64CC::NE: {
9444 if ((AddConstant > 0 && CompConstant < 0) ||
9445 (AddConstant < 0 && CompConstant >= 0 &&
9446 CompConstant < AddConstant + MaxUInt) ||
9447 (AddConstant >= 0 && CompConstant >= 0 &&
9448 CompConstant >= AddConstant) ||
9449 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9450
9451 return true;
9452 } break;
9453 case AArch64CC::VS:
9454 case AArch64CC::VC:
9455 case AArch64CC::AL:
9456 case AArch64CC::NV:
9457 return true;
9458 case AArch64CC::Invalid:
9459 break;
9460 }
9461
9462 return false;
9463}
9464
9465static
9466SDValue performCONDCombine(SDNode *N,
9467 TargetLowering::DAGCombinerInfo &DCI,
9468 SelectionDAG &DAG, unsigned CCIndex,
9469 unsigned CmpIndex) {
9470 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9471 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9472 unsigned CondOpcode = SubsNode->getOpcode();
9473
9474 if (CondOpcode != AArch64ISD::SUBS)
9475 return SDValue();
9476
9477 // There is a SUBS feeding this condition. Is it fed by a mask we can
9478 // use?
9479
9480 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9481 unsigned MaskBits = 0;
9482
9483 if (AndNode->getOpcode() != ISD::AND)
9484 return SDValue();
9485
9486 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9487 uint32_t CNV = CN->getZExtValue();
9488 if (CNV == 255)
9489 MaskBits = 8;
9490 else if (CNV == 65535)
9491 MaskBits = 16;
9492 }
9493
9494 if (!MaskBits)
9495 return SDValue();
9496
9497 SDValue AddValue = AndNode->getOperand(0);
9498
9499 if (AddValue.getOpcode() != ISD::ADD)
9500 return SDValue();
9501
9502 // The basic dag structure is correct, grab the inputs and validate them.
9503
9504 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9505 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9506 SDValue SubsInputValue = SubsNode->getOperand(1);
9507
9508 // The mask is present and the provenance of all the values is a smaller type,
9509 // lets see if the mask is superfluous.
9510
9511 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9512 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9513 return SDValue();
9514
9515 ISD::LoadExtType ExtType;
9516
9517 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9518 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9519 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9520 return SDValue();
9521
9522 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9523 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9524 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9525 return SDValue();
9526
9527 // The AND is not necessary, remove it.
9528
9529 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9530 SubsNode->getValueType(1));
9531 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9532
9533 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9534 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9535
9536 return SDValue(N, 0);
9537}
9538
Tim Northover3b0846e2014-05-24 12:50:23 +00009539// Optimize compare with zero and branch.
9540static SDValue performBRCONDCombine(SDNode *N,
9541 TargetLowering::DAGCombinerInfo &DCI,
9542 SelectionDAG &DAG) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009543 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9544 if (NV.getNode())
9545 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009546 SDValue Chain = N->getOperand(0);
9547 SDValue Dest = N->getOperand(1);
9548 SDValue CCVal = N->getOperand(2);
9549 SDValue Cmp = N->getOperand(3);
9550
9551 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9552 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9553 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9554 return SDValue();
9555
9556 unsigned CmpOpc = Cmp.getOpcode();
9557 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9558 return SDValue();
9559
9560 // Only attempt folding if there is only one use of the flag and no use of the
9561 // value.
9562 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9563 return SDValue();
9564
9565 SDValue LHS = Cmp.getOperand(0);
9566 SDValue RHS = Cmp.getOperand(1);
9567
9568 assert(LHS.getValueType() == RHS.getValueType() &&
9569 "Expected the value type to be the same for both operands!");
9570 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9571 return SDValue();
9572
Artyom Skrobov314ee042015-11-25 19:41:11 +00009573 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009574 std::swap(LHS, RHS);
9575
Artyom Skrobov314ee042015-11-25 19:41:11 +00009576 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009577 return SDValue();
9578
9579 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9580 LHS.getOpcode() == ISD::SRL)
9581 return SDValue();
9582
9583 // Fold the compare into the branch instruction.
9584 SDValue BR;
9585 if (CC == AArch64CC::EQ)
9586 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9587 else
9588 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9589
9590 // Do not add new nodes to DAG combiner worklist.
9591 DCI.CombineTo(N, BR, false);
9592
9593 return SDValue();
9594}
9595
Geoff Berry9e934b02016-01-04 18:55:47 +00009596// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9597// as well as whether the test should be inverted. This code is required to
9598// catch these cases (as opposed to standard dag combines) because
9599// AArch64ISD::TBZ is matched during legalization.
9600static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9601 SelectionDAG &DAG) {
9602
9603 if (!Op->hasOneUse())
9604 return Op;
9605
9606 // We don't handle undef/constant-fold cases below, as they should have
9607 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9608 // etc.)
9609
9610 // (tbz (trunc x), b) -> (tbz x, b)
9611 // This case is just here to enable more of the below cases to be caught.
9612 if (Op->getOpcode() == ISD::TRUNCATE &&
9613 Bit < Op->getValueType(0).getSizeInBits()) {
9614 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9615 }
9616
9617 if (Op->getNumOperands() != 2)
9618 return Op;
9619
9620 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9621 if (!C)
9622 return Op;
9623
9624 switch (Op->getOpcode()) {
9625 default:
9626 return Op;
9627
9628 // (tbz (and x, m), b) -> (tbz x, b)
9629 case ISD::AND:
9630 if ((C->getZExtValue() >> Bit) & 1)
9631 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9632 return Op;
9633
9634 // (tbz (shl x, c), b) -> (tbz x, b-c)
9635 case ISD::SHL:
9636 if (C->getZExtValue() <= Bit &&
9637 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9638 Bit = Bit - C->getZExtValue();
9639 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9640 }
9641 return Op;
9642
9643 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9644 case ISD::SRA:
9645 Bit = Bit + C->getZExtValue();
9646 if (Bit >= Op->getValueType(0).getSizeInBits())
9647 Bit = Op->getValueType(0).getSizeInBits() - 1;
9648 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9649
9650 // (tbz (srl x, c), b) -> (tbz x, b+c)
9651 case ISD::SRL:
9652 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9653 Bit = Bit + C->getZExtValue();
9654 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9655 }
9656 return Op;
9657
9658 // (tbz (xor x, -1), b) -> (tbnz x, b)
9659 case ISD::XOR:
9660 if ((C->getZExtValue() >> Bit) & 1)
9661 Invert = !Invert;
9662 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9663 }
9664}
9665
9666// Optimize test single bit zero/non-zero and branch.
9667static SDValue performTBZCombine(SDNode *N,
9668 TargetLowering::DAGCombinerInfo &DCI,
9669 SelectionDAG &DAG) {
9670 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9671 bool Invert = false;
9672 SDValue TestSrc = N->getOperand(1);
9673 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9674
9675 if (TestSrc == NewTestSrc)
9676 return SDValue();
9677
9678 unsigned NewOpc = N->getOpcode();
9679 if (Invert) {
9680 if (NewOpc == AArch64ISD::TBZ)
9681 NewOpc = AArch64ISD::TBNZ;
9682 else {
9683 assert(NewOpc == AArch64ISD::TBNZ);
9684 NewOpc = AArch64ISD::TBZ;
9685 }
9686 }
9687
9688 SDLoc DL(N);
9689 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9690 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9691}
9692
Tim Northover3b0846e2014-05-24 12:50:23 +00009693// vselect (v1i1 setcc) ->
9694// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9695// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9696// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9697// such VSELECT.
9698static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9699 SDValue N0 = N->getOperand(0);
9700 EVT CCVT = N0.getValueType();
9701
9702 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9703 CCVT.getVectorElementType() != MVT::i1)
9704 return SDValue();
9705
9706 EVT ResVT = N->getValueType(0);
9707 EVT CmpVT = N0.getOperand(0).getValueType();
9708 // Only combine when the result type is of the same size as the compared
9709 // operands.
9710 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9711 return SDValue();
9712
9713 SDValue IfTrue = N->getOperand(1);
9714 SDValue IfFalse = N->getOperand(2);
9715 SDValue SetCC =
9716 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9717 N0.getOperand(0), N0.getOperand(1),
9718 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9719 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9720 IfTrue, IfFalse);
9721}
9722
9723/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9724/// the compare-mask instructions rather than going via NZCV, even if LHS and
9725/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9726/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009727static SDValue performSelectCombine(SDNode *N,
9728 TargetLowering::DAGCombinerInfo &DCI) {
9729 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009730 SDValue N0 = N->getOperand(0);
9731 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009732
Ahmed Bougachac004c602015-04-27 21:43:12 +00009733 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009734 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009735
Ahmed Bougachac004c602015-04-27 21:43:12 +00009736 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9737 // scalar SetCCResultType. We also don't expect vectors, because we assume
9738 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9739 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9740 "Scalar-SETCC feeding SELECT has unexpected result type!");
9741
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009742 // If NumMaskElts == 0, the comparison is larger than select result. The
9743 // largest real NEON comparison is 64-bits per lane, which means the result is
9744 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009745 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009746
9747 // Don't try to do this optimization when the setcc itself has i1 operands.
9748 // There are no legal vectors of i1, so this would be pointless.
9749 if (SrcVT == MVT::i1)
9750 return SDValue();
9751
Tim Northover3c0915e2014-08-29 15:34:58 +00009752 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009753 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009754 return SDValue();
9755
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009756 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009757 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9758
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009759 // Also bail out if the vector CCVT isn't the same size as ResVT.
9760 // This can happen if the SETCC operand size doesn't divide the ResVT size
9761 // (e.g., f64 vs v3f32).
9762 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9763 return SDValue();
9764
Ahmed Bougachac004c602015-04-27 21:43:12 +00009765 // Make sure we didn't create illegal types, if we're not supposed to.
9766 assert(DCI.isBeforeLegalize() ||
9767 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9768
Tim Northover3b0846e2014-05-24 12:50:23 +00009769 // First perform a vector comparison, where lane 0 is the one we're interested
9770 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009771 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009772 SDValue LHS =
9773 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9774 SDValue RHS =
9775 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9776 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9777
9778 // Now duplicate the comparison mask we want across all other lanes.
9779 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9780 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009781 Mask = DAG.getNode(ISD::BITCAST, DL,
9782 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009783
9784 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9785}
9786
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009787/// Get rid of unnecessary NVCASTs (that don't change the type).
9788static SDValue performNVCASTCombine(SDNode *N) {
9789 if (N->getValueType(0) == N->getOperand(0).getValueType())
9790 return N->getOperand(0);
9791
9792 return SDValue();
9793}
9794
Tim Northover3b0846e2014-05-24 12:50:23 +00009795SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9796 DAGCombinerInfo &DCI) const {
9797 SelectionDAG &DAG = DCI.DAG;
9798 switch (N->getOpcode()) {
9799 default:
9800 break;
9801 case ISD::ADD:
9802 case ISD::SUB:
9803 return performAddSubLongCombine(N, DCI, DAG);
9804 case ISD::XOR:
9805 return performXorCombine(N, DAG, DCI, Subtarget);
9806 case ISD::MUL:
9807 return performMulCombine(N, DAG, DCI, Subtarget);
9808 case ISD::SINT_TO_FP:
9809 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009810 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009811 case ISD::FP_TO_SINT:
9812 case ISD::FP_TO_UINT:
9813 return performFpToIntCombine(N, DAG, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009814 case ISD::FDIV:
9815 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009816 case ISD::OR:
9817 return performORCombine(N, DCI, Subtarget);
9818 case ISD::INTRINSIC_WO_CHAIN:
9819 return performIntrinsicCombine(N, DCI, Subtarget);
9820 case ISD::ANY_EXTEND:
9821 case ISD::ZERO_EXTEND:
9822 case ISD::SIGN_EXTEND:
9823 return performExtendCombine(N, DCI, DAG);
9824 case ISD::BITCAST:
9825 return performBitcastCombine(N, DCI, DAG);
9826 case ISD::CONCAT_VECTORS:
9827 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009828 case ISD::SELECT: {
9829 SDValue RV = performSelectCombine(N, DCI);
9830 if (!RV.getNode())
9831 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9832 return RV;
9833 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009834 case ISD::VSELECT:
9835 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009836 case ISD::LOAD:
9837 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9838 return SDValue(N, 0);
9839 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009840 case ISD::STORE:
9841 return performSTORECombine(N, DCI, DAG, Subtarget);
9842 case AArch64ISD::BRCOND:
9843 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009844 case AArch64ISD::TBNZ:
9845 case AArch64ISD::TBZ:
9846 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009847 case AArch64ISD::CSEL:
9848 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009849 case AArch64ISD::DUP:
9850 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009851 case AArch64ISD::NVCAST:
9852 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009853 case ISD::INSERT_VECTOR_ELT:
9854 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009855 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009856 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009857 case ISD::INTRINSIC_VOID:
9858 case ISD::INTRINSIC_W_CHAIN:
9859 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9860 case Intrinsic::aarch64_neon_ld2:
9861 case Intrinsic::aarch64_neon_ld3:
9862 case Intrinsic::aarch64_neon_ld4:
9863 case Intrinsic::aarch64_neon_ld1x2:
9864 case Intrinsic::aarch64_neon_ld1x3:
9865 case Intrinsic::aarch64_neon_ld1x4:
9866 case Intrinsic::aarch64_neon_ld2lane:
9867 case Intrinsic::aarch64_neon_ld3lane:
9868 case Intrinsic::aarch64_neon_ld4lane:
9869 case Intrinsic::aarch64_neon_ld2r:
9870 case Intrinsic::aarch64_neon_ld3r:
9871 case Intrinsic::aarch64_neon_ld4r:
9872 case Intrinsic::aarch64_neon_st2:
9873 case Intrinsic::aarch64_neon_st3:
9874 case Intrinsic::aarch64_neon_st4:
9875 case Intrinsic::aarch64_neon_st1x2:
9876 case Intrinsic::aarch64_neon_st1x3:
9877 case Intrinsic::aarch64_neon_st1x4:
9878 case Intrinsic::aarch64_neon_st2lane:
9879 case Intrinsic::aarch64_neon_st3lane:
9880 case Intrinsic::aarch64_neon_st4lane:
9881 return performNEONPostLDSTCombine(N, DCI, DAG);
9882 default:
9883 break;
9884 }
9885 }
9886 return SDValue();
9887}
9888
9889// Check if the return value is used as only a return value, as otherwise
9890// we can't perform a tail-call. In particular, we need to check for
9891// target ISD nodes that are returns and any other "odd" constructs
9892// that the generic analysis code won't necessarily catch.
9893bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9894 SDValue &Chain) const {
9895 if (N->getNumValues() != 1)
9896 return false;
9897 if (!N->hasNUsesOfValue(1, 0))
9898 return false;
9899
9900 SDValue TCChain = Chain;
9901 SDNode *Copy = *N->use_begin();
9902 if (Copy->getOpcode() == ISD::CopyToReg) {
9903 // If the copy has a glue operand, we conservatively assume it isn't safe to
9904 // perform a tail call.
9905 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9906 MVT::Glue)
9907 return false;
9908 TCChain = Copy->getOperand(0);
9909 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9910 return false;
9911
9912 bool HasRet = false;
9913 for (SDNode *Node : Copy->uses()) {
9914 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9915 return false;
9916 HasRet = true;
9917 }
9918
9919 if (!HasRet)
9920 return false;
9921
9922 Chain = TCChain;
9923 return true;
9924}
9925
9926// Return whether the an instruction can potentially be optimized to a tail
9927// call. This will cause the optimizers to attempt to move, or duplicate,
9928// return instructions to help enable tail call optimizations for this
9929// instruction.
9930bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9931 if (!CI->isTailCall())
9932 return false;
9933
9934 return true;
9935}
9936
9937bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9938 SDValue &Offset,
9939 ISD::MemIndexedMode &AM,
9940 bool &IsInc,
9941 SelectionDAG &DAG) const {
9942 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9943 return false;
9944
9945 Base = Op->getOperand(0);
9946 // All of the indexed addressing mode instructions take a signed
9947 // 9 bit immediate offset.
9948 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9949 int64_t RHSC = (int64_t)RHS->getZExtValue();
9950 if (RHSC >= 256 || RHSC <= -256)
9951 return false;
9952 IsInc = (Op->getOpcode() == ISD::ADD);
9953 Offset = Op->getOperand(1);
9954 return true;
9955 }
9956 return false;
9957}
9958
9959bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9960 SDValue &Offset,
9961 ISD::MemIndexedMode &AM,
9962 SelectionDAG &DAG) const {
9963 EVT VT;
9964 SDValue Ptr;
9965 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9966 VT = LD->getMemoryVT();
9967 Ptr = LD->getBasePtr();
9968 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9969 VT = ST->getMemoryVT();
9970 Ptr = ST->getBasePtr();
9971 } else
9972 return false;
9973
9974 bool IsInc;
9975 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9976 return false;
9977 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9978 return true;
9979}
9980
9981bool AArch64TargetLowering::getPostIndexedAddressParts(
9982 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9983 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9984 EVT VT;
9985 SDValue Ptr;
9986 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9987 VT = LD->getMemoryVT();
9988 Ptr = LD->getBasePtr();
9989 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9990 VT = ST->getMemoryVT();
9991 Ptr = ST->getBasePtr();
9992 } else
9993 return false;
9994
9995 bool IsInc;
9996 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9997 return false;
9998 // Post-indexing updates the base, so it's not a valid transform
9999 // if that's not the same as the load's pointer.
10000 if (Ptr != Base)
10001 return false;
10002 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10003 return true;
10004}
10005
Tim Northoverf8bfe212014-07-18 13:07:05 +000010006static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10007 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010008 SDLoc DL(N);
10009 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010010
10011 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10012 return;
10013
Tim Northoverf8bfe212014-07-18 13:07:05 +000010014 Op = SDValue(
10015 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10016 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010017 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010018 0);
10019 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10020 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10021}
10022
Charlie Turner434d4592015-10-16 15:38:25 +000010023static void ReplaceReductionResults(SDNode *N,
10024 SmallVectorImpl<SDValue> &Results,
10025 SelectionDAG &DAG, unsigned InterOp,
10026 unsigned AcrossOp) {
10027 EVT LoVT, HiVT;
10028 SDValue Lo, Hi;
10029 SDLoc dl(N);
10030 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10031 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10032 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10033 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10034 Results.push_back(SplitVal);
10035}
10036
Tim Northover3b0846e2014-05-24 12:50:23 +000010037void AArch64TargetLowering::ReplaceNodeResults(
10038 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10039 switch (N->getOpcode()) {
10040 default:
10041 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010042 case ISD::BITCAST:
10043 ReplaceBITCASTResults(N, Results, DAG);
10044 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010045 case AArch64ISD::SADDV:
10046 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10047 return;
10048 case AArch64ISD::UADDV:
10049 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10050 return;
10051 case AArch64ISD::SMINV:
10052 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10053 return;
10054 case AArch64ISD::UMINV:
10055 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10056 return;
10057 case AArch64ISD::SMAXV:
10058 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10059 return;
10060 case AArch64ISD::UMAXV:
10061 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10062 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010063 case ISD::FP_TO_UINT:
10064 case ISD::FP_TO_SINT:
10065 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10066 // Let normal code take care of it by not adding anything to Results.
10067 return;
10068 }
10069}
10070
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010071bool AArch64TargetLowering::useLoadStackGuardNode() const {
10072 return true;
10073}
10074
Sanjay Patel1dd15592015-07-28 23:05:48 +000010075unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010076 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10077 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010078 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010079}
10080
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010081TargetLoweringBase::LegalizeTypeAction
10082AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10083 MVT SVT = VT.getSimpleVT();
10084 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10085 // v4i16, v2i32 instead of to promote.
10086 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10087 || SVT == MVT::v1f32)
10088 return TypeWidenVector;
10089
10090 return TargetLoweringBase::getPreferredVectorAction(VT);
10091}
10092
Robin Morisseted3d48f2014-09-03 21:29:59 +000010093// Loads and stores less than 128-bits are already atomic; ones above that
10094// are doomed anyway, so defer to the default libcall and blame the OS when
10095// things go wrong.
10096bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10097 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10098 return Size == 128;
10099}
10100
10101// Loads and stores less than 128-bits are already atomic; ones above that
10102// are doomed anyway, so defer to the default libcall and blame the OS when
10103// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010104TargetLowering::AtomicExpansionKind
10105AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010106 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010107 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010108}
10109
10110// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010111TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010112AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010113 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010114 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010115}
10116
Ahmed Bougacha52468672015-09-11 17:08:28 +000010117bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10118 AtomicCmpXchgInst *AI) const {
Robin Morisset25c8e312014-09-17 00:06:58 +000010119 return true;
10120}
10121
Tim Northover3b0846e2014-05-24 12:50:23 +000010122Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10123 AtomicOrdering Ord) const {
10124 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10125 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +000010126 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010127
10128 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10129 // intrinsic must return {i64, i64} and we have to recombine them into a
10130 // single i128 here.
10131 if (ValTy->getPrimitiveSizeInBits() == 128) {
10132 Intrinsic::ID Int =
10133 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10134 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10135
10136 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10137 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10138
10139 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10140 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10141 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10142 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10143 return Builder.CreateOr(
10144 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10145 }
10146
10147 Type *Tys[] = { Addr->getType() };
10148 Intrinsic::ID Int =
10149 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10150 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10151
10152 return Builder.CreateTruncOrBitCast(
10153 Builder.CreateCall(Ldxr, Addr),
10154 cast<PointerType>(Addr->getType())->getElementType());
10155}
10156
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010157void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10158 IRBuilder<> &Builder) const {
10159 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10160 Builder.CreateCall(
10161 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10162}
10163
Tim Northover3b0846e2014-05-24 12:50:23 +000010164Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10165 Value *Val, Value *Addr,
10166 AtomicOrdering Ord) const {
10167 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +000010168 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010169
10170 // Since the intrinsics must have legal type, the i128 intrinsics take two
10171 // parameters: "i64, i64". We must marshal Val into the appropriate form
10172 // before the call.
10173 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10174 Intrinsic::ID Int =
10175 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10176 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10177 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10178
10179 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10180 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10181 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010182 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010183 }
10184
10185 Intrinsic::ID Int =
10186 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10187 Type *Tys[] = { Addr->getType() };
10188 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10189
David Blaikieff6409d2015-05-18 22:13:54 +000010190 return Builder.CreateCall(Stxr,
10191 {Builder.CreateZExtOrBitCast(
10192 Val, Stxr->getFunctionType()->getParamType(0)),
10193 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010194}
Tim Northover3c55cca2014-11-27 21:02:42 +000010195
10196bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10197 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10198 return Ty->isArrayTy();
10199}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010200
10201bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10202 EVT) const {
10203 return false;
10204}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010205
10206Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10207 if (!Subtarget->isTargetAndroid())
10208 return TargetLowering::getSafeStackPointerLocation(IRB);
10209
10210 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10211 // definition of TLS_SLOT_SAFESTACK in
10212 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10213 const unsigned TlsOffset = 0x48;
10214 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10215 Function *ThreadPointerFunc =
10216 Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10217 return IRB.CreatePointerCast(
10218 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10219 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10220}
Manman Rencbe4f942015-12-16 21:04:19 +000010221
10222void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10223 // Update IsSplitCSR in AArch64unctionInfo.
10224 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10225 AFI->setIsSplitCSR(true);
10226}
10227
10228void AArch64TargetLowering::insertCopiesSplitCSR(
10229 MachineBasicBlock *Entry,
10230 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10231 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10232 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10233 if (!IStart)
10234 return;
10235
10236 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10237 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010238 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010239 for (const MCPhysReg *I = IStart; *I; ++I) {
10240 const TargetRegisterClass *RC = nullptr;
10241 if (AArch64::GPR64RegClass.contains(*I))
10242 RC = &AArch64::GPR64RegClass;
10243 else if (AArch64::FPR64RegClass.contains(*I))
10244 RC = &AArch64::FPR64RegClass;
10245 else
10246 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10247
10248 unsigned NewVR = MRI->createVirtualRegister(RC);
10249 // Create copy from CSR to a virtual register.
10250 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10251 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10252 // nounwind. If we want to generalize this later, we may need to emit
10253 // CFI pseudo-instructions.
10254 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10255 Attribute::NoUnwind) &&
10256 "Function should be nounwind in insertCopiesSplitCSR!");
10257 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010258 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010259 .addReg(*I);
10260
Manman Ren4632e8e2016-01-15 20:13:28 +000010261 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010262 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010263 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10264 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010265 .addReg(NewVR);
10266 }
10267}