blob: 74a01835171bed95f727879591065d39248f2550 [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
Tim Northover3c55cca2014-11-27 21:02:42 +000014#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000015#include "AArch64MachineFunctionInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000016#include "AArch64ISelLowering.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000018#include "AArch64RegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000020#include "MCTargetDesc/AArch64AddressingModes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000021#include "Utils/AArch64BaseInfo.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000026#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000032#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000033#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000034#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000035#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000037#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000038#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000039#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000040#include "llvm/CodeGen/MachineValueType.h"
41#include "llvm/CodeGen/RuntimeLibcalls.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/CodeGen/SelectionDAGNodes.h"
44#include "llvm/CodeGen/ValueTypes.h"
45#include "llvm/IR/Attributes.h"
46#include "llvm/IR/Constants.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DebugLoc.h"
49#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000050#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000051#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000052#include "llvm/IR/GlobalValue.h"
53#include "llvm/IR/Instruction.h"
54#include "llvm/IR/Instructions.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000055#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000056#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/OperandTraits.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000059#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000060#include "llvm/IR/Use.h"
61#include "llvm/IR/Value.h"
62#include "llvm/MC/MCRegisterInfo.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000065#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000066#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000067#include "llvm/Support/Debug.h"
68#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000069#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000070#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000071#include "llvm/Target/TargetCallingConv.h"
72#include "llvm/Target/TargetInstrInfo.h"
73#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000074#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000075#include <algorithm>
76#include <bitset>
77#include <cassert>
78#include <cctype>
79#include <cstdint>
80#include <cstdlib>
81#include <iterator>
82#include <limits>
83#include <tuple>
84#include <utility>
85#include <vector>
86
Tim Northover3b0846e2014-05-24 12:50:23 +000087using namespace llvm;
88
89#define DEBUG_TYPE "aarch64-lower"
90
91STATISTIC(NumTailCalls, "Number of tail calls");
92STATISTIC(NumShiftInserts, "Number of vector shift inserts");
93
Tim Northover3b0846e2014-05-24 12:50:23 +000094static cl::opt<bool>
95EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000096 cl::desc("Allow AArch64 SLI/SRI formation"),
97 cl::init(false));
98
99// FIXME: The necessary dtprel relocations don't seem to be supported
100// well in the GNU bfd and gold linkers at the moment. Therefore, by
101// default, for now, fall back to GeneralDynamic code generation.
102cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
103 "aarch64-elf-ldtls-generation", cl::Hidden,
104 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
105 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000106
Matthias Braunaf7d7702015-07-16 20:02:37 +0000107/// Value type used for condition codes.
108static const MVT MVT_CC = MVT::i32;
109
Eric Christopher905f12d2015-01-29 00:19:42 +0000110AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
111 const AArch64Subtarget &STI)
112 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000113 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
114 // we have to make something up. Arbitrarily, choose ZeroOrOne.
115 setBooleanContents(ZeroOrOneBooleanContent);
116 // When comparing vectors the result sets the different elements in the
117 // vector to all-one or all-zero.
118 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
119
120 // Set up the register classes.
121 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
122 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
123
124 if (Subtarget->hasFPARMv8()) {
125 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
126 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
127 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
128 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
129 }
130
131 if (Subtarget->hasNEON()) {
132 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
133 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
134 // Someone set us up the NEON.
135 addDRTypeForNEON(MVT::v2f32);
136 addDRTypeForNEON(MVT::v8i8);
137 addDRTypeForNEON(MVT::v4i16);
138 addDRTypeForNEON(MVT::v2i32);
139 addDRTypeForNEON(MVT::v1i64);
140 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000141 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000142
143 addQRTypeForNEON(MVT::v4f32);
144 addQRTypeForNEON(MVT::v2f64);
145 addQRTypeForNEON(MVT::v16i8);
146 addQRTypeForNEON(MVT::v8i16);
147 addQRTypeForNEON(MVT::v4i32);
148 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000149 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000150 }
151
152 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000153 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000154
155 // Provide all sorts of operation actions
156 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
157 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
158 setOperationAction(ISD::SETCC, MVT::i32, Custom);
159 setOperationAction(ISD::SETCC, MVT::i64, Custom);
160 setOperationAction(ISD::SETCC, MVT::f32, Custom);
161 setOperationAction(ISD::SETCC, MVT::f64, Custom);
162 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
163 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
164 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
165 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
166 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
167 setOperationAction(ISD::SELECT, MVT::i32, Custom);
168 setOperationAction(ISD::SELECT, MVT::i64, Custom);
169 setOperationAction(ISD::SELECT, MVT::f32, Custom);
170 setOperationAction(ISD::SELECT, MVT::f64, Custom);
171 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
172 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
173 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
174 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
175 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
176 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
177
178 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
179 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
180 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
181
182 setOperationAction(ISD::FREM, MVT::f32, Expand);
183 setOperationAction(ISD::FREM, MVT::f64, Expand);
184 setOperationAction(ISD::FREM, MVT::f80, Expand);
185
186 // Custom lowering hooks are needed for XOR
187 // to fold it into CSINC/CSINV.
188 setOperationAction(ISD::XOR, MVT::i32, Custom);
189 setOperationAction(ISD::XOR, MVT::i64, Custom);
190
191 // Virtually no operation on f128 is legal, but LLVM can't expand them when
192 // there's a valid register class, so we need custom operations in most cases.
193 setOperationAction(ISD::FABS, MVT::f128, Expand);
194 setOperationAction(ISD::FADD, MVT::f128, Custom);
195 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
196 setOperationAction(ISD::FCOS, MVT::f128, Expand);
197 setOperationAction(ISD::FDIV, MVT::f128, Custom);
198 setOperationAction(ISD::FMA, MVT::f128, Expand);
199 setOperationAction(ISD::FMUL, MVT::f128, Custom);
200 setOperationAction(ISD::FNEG, MVT::f128, Expand);
201 setOperationAction(ISD::FPOW, MVT::f128, Expand);
202 setOperationAction(ISD::FREM, MVT::f128, Expand);
203 setOperationAction(ISD::FRINT, MVT::f128, Expand);
204 setOperationAction(ISD::FSIN, MVT::f128, Expand);
205 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
206 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
207 setOperationAction(ISD::FSUB, MVT::f128, Custom);
208 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
209 setOperationAction(ISD::SETCC, MVT::f128, Custom);
210 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
211 setOperationAction(ISD::SELECT, MVT::f128, Custom);
212 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
213 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
214
215 // Lowering for many of the conversions is actually specified by the non-f128
216 // type. The LowerXXX function will be trivial when f128 isn't involved.
217 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
218 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
219 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
220 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
221 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
222 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
223 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
224 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
225 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
226 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
227 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
228 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
229 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
230 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
231
232 // Variable arguments.
233 setOperationAction(ISD::VASTART, MVT::Other, Custom);
234 setOperationAction(ISD::VAARG, MVT::Other, Custom);
235 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
236 setOperationAction(ISD::VAEND, MVT::Other, Expand);
237
238 // Variable-sized objects.
239 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
240 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
241 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
242
Tim Northover3b0846e2014-05-24 12:50:23 +0000243 // Constant pool entries
244 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
245
246 // BlockAddress
247 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
248
249 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
250 setOperationAction(ISD::ADDC, MVT::i32, Custom);
251 setOperationAction(ISD::ADDE, MVT::i32, Custom);
252 setOperationAction(ISD::SUBC, MVT::i32, Custom);
253 setOperationAction(ISD::SUBE, MVT::i32, Custom);
254 setOperationAction(ISD::ADDC, MVT::i64, Custom);
255 setOperationAction(ISD::ADDE, MVT::i64, Custom);
256 setOperationAction(ISD::SUBC, MVT::i64, Custom);
257 setOperationAction(ISD::SUBE, MVT::i64, Custom);
258
259 // AArch64 lacks both left-rotate and popcount instructions.
260 setOperationAction(ISD::ROTL, MVT::i32, Expand);
261 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000262 for (MVT VT : MVT::vector_valuetypes()) {
263 setOperationAction(ISD::ROTL, VT, Expand);
264 setOperationAction(ISD::ROTR, VT, Expand);
265 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000266
267 // AArch64 doesn't have {U|S}MUL_LOHI.
268 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
269 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
270
Tim Northover3b0846e2014-05-24 12:50:23 +0000271 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
272 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
273
274 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
275 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000276 for (MVT VT : MVT::vector_valuetypes()) {
277 setOperationAction(ISD::SDIVREM, VT, Expand);
278 setOperationAction(ISD::UDIVREM, VT, Expand);
279 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000280 setOperationAction(ISD::SREM, MVT::i32, Expand);
281 setOperationAction(ISD::SREM, MVT::i64, Expand);
282 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
283 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
284 setOperationAction(ISD::UREM, MVT::i32, Expand);
285 setOperationAction(ISD::UREM, MVT::i64, Expand);
286
287 // Custom lower Add/Sub/Mul with overflow.
288 setOperationAction(ISD::SADDO, MVT::i32, Custom);
289 setOperationAction(ISD::SADDO, MVT::i64, Custom);
290 setOperationAction(ISD::UADDO, MVT::i32, Custom);
291 setOperationAction(ISD::UADDO, MVT::i64, Custom);
292 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
293 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
294 setOperationAction(ISD::USUBO, MVT::i32, Custom);
295 setOperationAction(ISD::USUBO, MVT::i64, Custom);
296 setOperationAction(ISD::SMULO, MVT::i32, Custom);
297 setOperationAction(ISD::SMULO, MVT::i64, Custom);
298 setOperationAction(ISD::UMULO, MVT::i32, Custom);
299 setOperationAction(ISD::UMULO, MVT::i64, Custom);
300
301 setOperationAction(ISD::FSIN, MVT::f32, Expand);
302 setOperationAction(ISD::FSIN, MVT::f64, Expand);
303 setOperationAction(ISD::FCOS, MVT::f32, Expand);
304 setOperationAction(ISD::FCOS, MVT::f64, Expand);
305 setOperationAction(ISD::FPOW, MVT::f32, Expand);
306 setOperationAction(ISD::FPOW, MVT::f64, Expand);
307 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
308 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
309
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000310 // f16 is a storage-only type, always promote it to f32.
311 setOperationAction(ISD::SETCC, MVT::f16, Promote);
312 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
313 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
314 setOperationAction(ISD::SELECT, MVT::f16, Promote);
315 setOperationAction(ISD::FADD, MVT::f16, Promote);
316 setOperationAction(ISD::FSUB, MVT::f16, Promote);
317 setOperationAction(ISD::FMUL, MVT::f16, Promote);
318 setOperationAction(ISD::FDIV, MVT::f16, Promote);
319 setOperationAction(ISD::FREM, MVT::f16, Promote);
320 setOperationAction(ISD::FMA, MVT::f16, Promote);
321 setOperationAction(ISD::FNEG, MVT::f16, Promote);
322 setOperationAction(ISD::FABS, MVT::f16, Promote);
323 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
324 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
325 setOperationAction(ISD::FCOS, MVT::f16, Promote);
326 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
327 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
328 setOperationAction(ISD::FPOW, MVT::f16, Promote);
329 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
330 setOperationAction(ISD::FRINT, MVT::f16, Promote);
331 setOperationAction(ISD::FSIN, MVT::f16, Promote);
332 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
333 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
334 setOperationAction(ISD::FEXP, MVT::f16, Promote);
335 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
336 setOperationAction(ISD::FLOG, MVT::f16, Promote);
337 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
338 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
339 setOperationAction(ISD::FROUND, MVT::f16, Promote);
340 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
341 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
342 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000343 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
344 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000345
Oliver Stannard89d15422014-08-27 16:16:04 +0000346 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
347 // known to be safe.
348 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
349 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
350 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
351 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
352 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
353 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
354 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
355 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
356 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
357 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
358 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
359 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
360
361 // Expand all other v4f16 operations.
362 // FIXME: We could generate better code by promoting some operations to
363 // a pair of v4f32s
364 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
365 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
366 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
367 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
368 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
369 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
370 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
371 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
372 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
373 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
374 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
375 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
376 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
377 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
378 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
379 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
380 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
381 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
382 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
383 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
384 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
385 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
386 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
387 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
388 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
389 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
390
391
392 // v8f16 is also a storage-only type, so expand it.
393 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
394 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
395 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
396 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
397 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
398 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
399 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
400 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
401 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
402 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
403 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
404 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
405 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
406 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
407 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
408 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
409 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
410 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
411 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
412 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
413 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
414 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
415 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
416 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
417 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
418 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
419 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
420 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
421 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
422 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
423 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
424
Tim Northover3b0846e2014-05-24 12:50:23 +0000425 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000426 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000427 setOperationAction(ISD::FFLOOR, Ty, Legal);
428 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
429 setOperationAction(ISD::FCEIL, Ty, Legal);
430 setOperationAction(ISD::FRINT, Ty, Legal);
431 setOperationAction(ISD::FTRUNC, Ty, Legal);
432 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000433 setOperationAction(ISD::FMINNUM, Ty, Legal);
434 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000435 setOperationAction(ISD::FMINNAN, Ty, Legal);
436 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000437 }
438
439 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
440
Tim Northovercdf15292016-04-14 17:03:29 +0000441 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
442
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000443 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
444 // This requires the Performance Monitors extension.
445 if (Subtarget->hasPerfMon())
446 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
447
Tim Northover3b0846e2014-05-24 12:50:23 +0000448 if (Subtarget->isTargetMachO()) {
449 // For iOS, we don't want to the normal expansion of a libcall to
450 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
451 // traffic.
452 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
453 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
454 } else {
455 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
456 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
457 }
458
Juergen Ributzka23266502014-12-10 19:43:32 +0000459 // Make floating-point constants legal for the large code model, so they don't
460 // become loads from the constant pool.
461 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
462 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
463 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
464 }
465
Tim Northover3b0846e2014-05-24 12:50:23 +0000466 // AArch64 does not have floating-point extending loads, i1 sign-extending
467 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000468 for (MVT VT : MVT::fp_valuetypes()) {
469 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
470 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
471 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
472 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
473 }
474 for (MVT VT : MVT::integer_valuetypes())
475 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
476
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
478 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
479 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
480 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
481 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
482 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
483 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000484
485 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
486 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
487
Tim Northover3b0846e2014-05-24 12:50:23 +0000488 // Indexed loads and stores are supported.
489 for (unsigned im = (unsigned)ISD::PRE_INC;
490 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
491 setIndexedLoadAction(im, MVT::i8, Legal);
492 setIndexedLoadAction(im, MVT::i16, Legal);
493 setIndexedLoadAction(im, MVT::i32, Legal);
494 setIndexedLoadAction(im, MVT::i64, Legal);
495 setIndexedLoadAction(im, MVT::f64, Legal);
496 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000497 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000498 setIndexedStoreAction(im, MVT::i8, Legal);
499 setIndexedStoreAction(im, MVT::i16, Legal);
500 setIndexedStoreAction(im, MVT::i32, Legal);
501 setIndexedStoreAction(im, MVT::i64, Legal);
502 setIndexedStoreAction(im, MVT::f64, Legal);
503 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000504 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000505 }
506
507 // Trap.
508 setOperationAction(ISD::TRAP, MVT::Other, Legal);
509
510 // We combine OR nodes for bitfield operations.
511 setTargetDAGCombine(ISD::OR);
512
513 // Vector add and sub nodes may conceal a high-half opportunity.
514 // Also, try to fold ADD into CSINC/CSINV..
515 setTargetDAGCombine(ISD::ADD);
516 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000517 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000518 setTargetDAGCombine(ISD::XOR);
519 setTargetDAGCombine(ISD::SINT_TO_FP);
520 setTargetDAGCombine(ISD::UINT_TO_FP);
521
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000522 setTargetDAGCombine(ISD::FP_TO_SINT);
523 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000524 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000525
Tim Northover3b0846e2014-05-24 12:50:23 +0000526 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
527
528 setTargetDAGCombine(ISD::ANY_EXTEND);
529 setTargetDAGCombine(ISD::ZERO_EXTEND);
530 setTargetDAGCombine(ISD::SIGN_EXTEND);
531 setTargetDAGCombine(ISD::BITCAST);
532 setTargetDAGCombine(ISD::CONCAT_VECTORS);
533 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000534 if (Subtarget->supportsAddressTopByteIgnored())
535 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000536
537 setTargetDAGCombine(ISD::MUL);
538
539 setTargetDAGCombine(ISD::SELECT);
540 setTargetDAGCombine(ISD::VSELECT);
541
542 setTargetDAGCombine(ISD::INTRINSIC_VOID);
543 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
544 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000545 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000546
547 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
548 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
549 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
550
551 setStackPointerRegisterToSaveRestore(AArch64::SP);
552
553 setSchedulingPreference(Sched::Hybrid);
554
555 // Enable TBZ/TBNZ
556 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000557 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000558
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000559 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000560 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000561 // Set preferred alignments.
562 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
563 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000564
Evandro Menezese45de8a2016-09-26 15:32:33 +0000565 // Only change the limit for entries in a jump table if specified by
566 // the subtarget, but not at the command line.
567 unsigned MaxJT = STI.getMaximumJumpTableSize();
568 if (MaxJT && getMaximumJumpTableSize() == 0)
569 setMaximumJumpTableSize(MaxJT);
570
Tim Northover3b0846e2014-05-24 12:50:23 +0000571 setHasExtractBitsInsn(true);
572
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000573 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
574
Tim Northover3b0846e2014-05-24 12:50:23 +0000575 if (Subtarget->hasNEON()) {
576 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
577 // silliness like this:
578 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
579 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
580 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
581 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
582 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
583 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
584 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
585 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
586 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
587 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
588 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
589 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
590 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
591 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
592 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
593 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
594 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
595 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
596 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
597 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
598 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
599 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
600 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
601 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
602 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
603
604 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
605 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
606 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
607 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
608 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
609
610 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
611
612 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
613 // elements smaller than i32, so promote the input to i32 first.
614 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
615 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
616 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
617 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000618 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
619 // -> v8f16 conversions.
620 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
621 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
622 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
623 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000624 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
625 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
626 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
627 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
628 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000629 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
630 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
631 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
632 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000633
Craig Topperc5551bf2016-04-26 05:26:51 +0000634 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
635 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
636
Craig Topper3b4842b2016-04-28 01:58:21 +0000637 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
638 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
639 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
640 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
641 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
642 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
643 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
644 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
645
Tim Northover3b0846e2014-05-24 12:50:23 +0000646 // AArch64 doesn't have MUL.2d:
647 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000648 // Custom handling for some quad-vector types to detect MULL.
649 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
650 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
651 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
652
Tim Northover3b0846e2014-05-24 12:50:23 +0000653 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
654 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
655 // Likewise, narrowing and extending vector loads/stores aren't handled
656 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000657 for (MVT VT : MVT::vector_valuetypes()) {
658 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000659
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000660 setOperationAction(ISD::MULHS, VT, Expand);
661 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
662 setOperationAction(ISD::MULHU, VT, Expand);
663 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000664
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000665 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000666
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000667 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000668 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000669 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
670 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
671 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
672 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000673 }
674
675 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000676 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000677 setOperationAction(ISD::FFLOOR, Ty, Legal);
678 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
679 setOperationAction(ISD::FCEIL, Ty, Legal);
680 setOperationAction(ISD::FRINT, Ty, Legal);
681 setOperationAction(ISD::FTRUNC, Ty, Legal);
682 setOperationAction(ISD::FROUND, Ty, Legal);
683 }
684 }
James Molloyf089ab72014-08-06 10:42:18 +0000685
Matthias Braun651cff42016-06-02 18:03:53 +0000686 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000687}
688
Craig Topper18e69f42016-04-15 06:20:21 +0000689void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000690 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000691 setOperationAction(ISD::LOAD, VT, Promote);
692 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000693
Craig Topper18e69f42016-04-15 06:20:21 +0000694 setOperationAction(ISD::STORE, VT, Promote);
695 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000696 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000697 setOperationAction(ISD::LOAD, VT, Promote);
698 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000699
Craig Topper18e69f42016-04-15 06:20:21 +0000700 setOperationAction(ISD::STORE, VT, Promote);
701 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000702 }
703
704 // Mark vector float intrinsics as expand.
705 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000706 setOperationAction(ISD::FSIN, VT, Expand);
707 setOperationAction(ISD::FCOS, VT, Expand);
708 setOperationAction(ISD::FPOWI, VT, Expand);
709 setOperationAction(ISD::FPOW, VT, Expand);
710 setOperationAction(ISD::FLOG, VT, Expand);
711 setOperationAction(ISD::FLOG2, VT, Expand);
712 setOperationAction(ISD::FLOG10, VT, Expand);
713 setOperationAction(ISD::FEXP, VT, Expand);
714 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000715
716 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000717 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000718 }
719
Craig Topper18e69f42016-04-15 06:20:21 +0000720 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
721 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
722 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
723 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
724 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
725 setOperationAction(ISD::SRA, VT, Custom);
726 setOperationAction(ISD::SRL, VT, Custom);
727 setOperationAction(ISD::SHL, VT, Custom);
728 setOperationAction(ISD::AND, VT, Custom);
729 setOperationAction(ISD::OR, VT, Custom);
730 setOperationAction(ISD::SETCC, VT, Custom);
731 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000732
Craig Topper18e69f42016-04-15 06:20:21 +0000733 setOperationAction(ISD::SELECT, VT, Expand);
734 setOperationAction(ISD::SELECT_CC, VT, Expand);
735 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000736 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000737 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000738
739 // CNT supports only B element sizes.
740 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000741 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000742
Craig Topper18e69f42016-04-15 06:20:21 +0000743 setOperationAction(ISD::UDIV, VT, Expand);
744 setOperationAction(ISD::SDIV, VT, Expand);
745 setOperationAction(ISD::UREM, VT, Expand);
746 setOperationAction(ISD::SREM, VT, Expand);
747 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000748
Craig Topper18e69f42016-04-15 06:20:21 +0000749 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
750 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000751
Hal Finkelcd8664c2015-12-11 23:11:52 +0000752 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000753 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000754 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000755 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000756
James Molloy63be1982015-08-14 09:08:50 +0000757 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
758 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000759 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
760 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000761 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000762
Tim Northover3b0846e2014-05-24 12:50:23 +0000763 if (Subtarget->isLittleEndian()) {
764 for (unsigned im = (unsigned)ISD::PRE_INC;
765 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000766 setIndexedLoadAction(im, VT, Legal);
767 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000768 }
769 }
770}
771
772void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
773 addRegisterClass(VT, &AArch64::FPR64RegClass);
774 addTypeForNEON(VT, MVT::v2i32);
775}
776
777void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
778 addRegisterClass(VT, &AArch64::FPR128RegClass);
779 addTypeForNEON(VT, MVT::v4i32);
780}
781
Mehdi Amini44ede332015-07-09 02:09:04 +0000782EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
783 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000784 if (!VT.isVector())
785 return MVT::i32;
786 return VT.changeVectorElementTypeToInteger();
787}
788
789/// computeKnownBitsForTargetNode - Determine which of the bits specified in
790/// Mask are known to be either zero or one and return them in the
791/// KnownZero/KnownOne bitsets.
792void AArch64TargetLowering::computeKnownBitsForTargetNode(
793 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
794 const SelectionDAG &DAG, unsigned Depth) const {
795 switch (Op.getOpcode()) {
796 default:
797 break;
798 case AArch64ISD::CSEL: {
799 APInt KnownZero2, KnownOne2;
800 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
801 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
802 KnownZero &= KnownZero2;
803 KnownOne &= KnownOne2;
804 break;
805 }
806 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000807 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000808 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
809 switch (IntID) {
810 default: return;
811 case Intrinsic::aarch64_ldaxr:
812 case Intrinsic::aarch64_ldxr: {
813 unsigned BitWidth = KnownOne.getBitWidth();
814 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +0000815 unsigned MemBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +0000816 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
817 return;
818 }
819 }
820 break;
821 }
822 case ISD::INTRINSIC_WO_CHAIN:
823 case ISD::INTRINSIC_VOID: {
824 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
825 switch (IntNo) {
826 default:
827 break;
828 case Intrinsic::aarch64_neon_umaxv:
829 case Intrinsic::aarch64_neon_uminv: {
830 // Figure out the datatype of the vector operand. The UMINV instruction
831 // will zero extend the result, so we can mark as known zero all the
832 // bits larger than the element datatype. 32-bit or larget doesn't need
833 // this as those are legal types and will be handled by isel directly.
834 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
835 unsigned BitWidth = KnownZero.getBitWidth();
836 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
837 assert(BitWidth >= 8 && "Unexpected width!");
838 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
839 KnownZero |= Mask;
840 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
841 assert(BitWidth >= 16 && "Unexpected width!");
842 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
843 KnownZero |= Mask;
844 }
845 break;
846 } break;
847 }
848 }
849 }
850}
851
Mehdi Aminieaabc512015-07-09 15:12:23 +0000852MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
853 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000854 return MVT::i64;
855}
856
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000857bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
858 unsigned AddrSpace,
859 unsigned Align,
860 bool *Fast) const {
861 if (Subtarget->requiresStrictAlign())
862 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000863
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000864 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +0000865 // Some CPUs are fine with unaligned stores except for 128-bit ones.
866 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000867 // See comments in performSTORECombine() for more details about
868 // these conditions.
869
870 // Code that uses clang vector extensions can mark that it
871 // wants unaligned accesses to be treated as fast by
872 // underspecifying alignment to be 1 or 2.
873 Align <= 2 ||
874
875 // Disregard v2i64. Memcpy lowering produces those and splitting
876 // them regresses performance on micro-benchmarks and olden/bh.
877 VT == MVT::v2i64;
878 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000879 return true;
880}
881
Tim Northover3b0846e2014-05-24 12:50:23 +0000882FastISel *
883AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
884 const TargetLibraryInfo *libInfo) const {
885 return AArch64::createFastISel(funcInfo, libInfo);
886}
887
888const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000889 switch ((AArch64ISD::NodeType)Opcode) {
890 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000891 case AArch64ISD::CALL: return "AArch64ISD::CALL";
892 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
893 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
894 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
895 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
896 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
897 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
898 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
899 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
900 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
901 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
902 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000903 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000904 case AArch64ISD::ADC: return "AArch64ISD::ADC";
905 case AArch64ISD::SBC: return "AArch64ISD::SBC";
906 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
907 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
908 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
909 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
910 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000911 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
912 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
913 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000914 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000915 case AArch64ISD::DUP: return "AArch64ISD::DUP";
916 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
917 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
918 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
919 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
920 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
921 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
922 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
923 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
924 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
925 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
926 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
927 case AArch64ISD::BICi: return "AArch64ISD::BICi";
928 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
929 case AArch64ISD::BSL: return "AArch64ISD::BSL";
930 case AArch64ISD::NEG: return "AArch64ISD::NEG";
931 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
932 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
933 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
934 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
935 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
936 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
937 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
938 case AArch64ISD::REV16: return "AArch64ISD::REV16";
939 case AArch64ISD::REV32: return "AArch64ISD::REV32";
940 case AArch64ISD::REV64: return "AArch64ISD::REV64";
941 case AArch64ISD::EXT: return "AArch64ISD::EXT";
942 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
943 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
944 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
945 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
946 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
947 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
948 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
949 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
950 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
951 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
952 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
953 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
954 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
955 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
956 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
957 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
958 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
959 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
960 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
961 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
962 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000963 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
964 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
965 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
966 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
967 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
968 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000969 case AArch64ISD::NOT: return "AArch64ISD::NOT";
970 case AArch64ISD::BIT: return "AArch64ISD::BIT";
971 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
972 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
973 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
974 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
975 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000976 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000977 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
978 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000979 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000980 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
981 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
982 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
983 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
984 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
985 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
986 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
987 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
988 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
989 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
990 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
991 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
992 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
993 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
994 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
995 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
996 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
997 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
998 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
999 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1000 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1001 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1002 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1003 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1004 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1005 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1006 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1007 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1008 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001009 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1010 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001011 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001012 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1013 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1014 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001015 }
Matthias Braund04893f2015-05-07 21:33:59 +00001016 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001017}
1018
1019MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001020AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001021 MachineBasicBlock *MBB) const {
1022 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1023 // phi node:
1024
1025 // OrigBB:
1026 // [... previous instrs leading to comparison ...]
1027 // b.ne TrueBB
1028 // b EndBB
1029 // TrueBB:
1030 // ; Fallthrough
1031 // EndBB:
1032 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1033
Tim Northover3b0846e2014-05-24 12:50:23 +00001034 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001035 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001036 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001037 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001038 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001039
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001040 unsigned DestReg = MI.getOperand(0).getReg();
1041 unsigned IfTrueReg = MI.getOperand(1).getReg();
1042 unsigned IfFalseReg = MI.getOperand(2).getReg();
1043 unsigned CondCode = MI.getOperand(3).getImm();
1044 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001045
1046 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1047 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1048 MF->insert(It, TrueBB);
1049 MF->insert(It, EndBB);
1050
1051 // Transfer rest of current basic-block to EndBB
1052 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1053 MBB->end());
1054 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1055
1056 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1057 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1058 MBB->addSuccessor(TrueBB);
1059 MBB->addSuccessor(EndBB);
1060
1061 // TrueBB falls through to the end.
1062 TrueBB->addSuccessor(EndBB);
1063
1064 if (!NZCVKilled) {
1065 TrueBB->addLiveIn(AArch64::NZCV);
1066 EndBB->addLiveIn(AArch64::NZCV);
1067 }
1068
1069 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1070 .addReg(IfTrueReg)
1071 .addMBB(TrueBB)
1072 .addReg(IfFalseReg)
1073 .addMBB(MBB);
1074
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001075 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001076 return EndBB;
1077}
1078
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001079MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1080 MachineInstr &MI, MachineBasicBlock *BB) const {
1081 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001082 default:
1083#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001084 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001085#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001086 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001087
1088 case AArch64::F128CSEL:
1089 return EmitF128CSEL(MI, BB);
1090
1091 case TargetOpcode::STACKMAP:
1092 case TargetOpcode::PATCHPOINT:
1093 return emitPatchPoint(MI, BB);
1094 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001095}
1096
1097//===----------------------------------------------------------------------===//
1098// AArch64 Lowering private implementation.
1099//===----------------------------------------------------------------------===//
1100
1101//===----------------------------------------------------------------------===//
1102// Lowering Code
1103//===----------------------------------------------------------------------===//
1104
1105/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1106/// CC
1107static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1108 switch (CC) {
1109 default:
1110 llvm_unreachable("Unknown condition code!");
1111 case ISD::SETNE:
1112 return AArch64CC::NE;
1113 case ISD::SETEQ:
1114 return AArch64CC::EQ;
1115 case ISD::SETGT:
1116 return AArch64CC::GT;
1117 case ISD::SETGE:
1118 return AArch64CC::GE;
1119 case ISD::SETLT:
1120 return AArch64CC::LT;
1121 case ISD::SETLE:
1122 return AArch64CC::LE;
1123 case ISD::SETUGT:
1124 return AArch64CC::HI;
1125 case ISD::SETUGE:
1126 return AArch64CC::HS;
1127 case ISD::SETULT:
1128 return AArch64CC::LO;
1129 case ISD::SETULE:
1130 return AArch64CC::LS;
1131 }
1132}
1133
1134/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1135static void changeFPCCToAArch64CC(ISD::CondCode CC,
1136 AArch64CC::CondCode &CondCode,
1137 AArch64CC::CondCode &CondCode2) {
1138 CondCode2 = AArch64CC::AL;
1139 switch (CC) {
1140 default:
1141 llvm_unreachable("Unknown FP condition!");
1142 case ISD::SETEQ:
1143 case ISD::SETOEQ:
1144 CondCode = AArch64CC::EQ;
1145 break;
1146 case ISD::SETGT:
1147 case ISD::SETOGT:
1148 CondCode = AArch64CC::GT;
1149 break;
1150 case ISD::SETGE:
1151 case ISD::SETOGE:
1152 CondCode = AArch64CC::GE;
1153 break;
1154 case ISD::SETOLT:
1155 CondCode = AArch64CC::MI;
1156 break;
1157 case ISD::SETOLE:
1158 CondCode = AArch64CC::LS;
1159 break;
1160 case ISD::SETONE:
1161 CondCode = AArch64CC::MI;
1162 CondCode2 = AArch64CC::GT;
1163 break;
1164 case ISD::SETO:
1165 CondCode = AArch64CC::VC;
1166 break;
1167 case ISD::SETUO:
1168 CondCode = AArch64CC::VS;
1169 break;
1170 case ISD::SETUEQ:
1171 CondCode = AArch64CC::EQ;
1172 CondCode2 = AArch64CC::VS;
1173 break;
1174 case ISD::SETUGT:
1175 CondCode = AArch64CC::HI;
1176 break;
1177 case ISD::SETUGE:
1178 CondCode = AArch64CC::PL;
1179 break;
1180 case ISD::SETLT:
1181 case ISD::SETULT:
1182 CondCode = AArch64CC::LT;
1183 break;
1184 case ISD::SETLE:
1185 case ISD::SETULE:
1186 CondCode = AArch64CC::LE;
1187 break;
1188 case ISD::SETNE:
1189 case ISD::SETUNE:
1190 CondCode = AArch64CC::NE;
1191 break;
1192 }
1193}
1194
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001195/// Convert a DAG fp condition code to an AArch64 CC.
1196/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1197/// should be AND'ed instead of OR'ed.
1198static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1199 AArch64CC::CondCode &CondCode,
1200 AArch64CC::CondCode &CondCode2) {
1201 CondCode2 = AArch64CC::AL;
1202 switch (CC) {
1203 default:
1204 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1205 assert(CondCode2 == AArch64CC::AL);
1206 break;
1207 case ISD::SETONE:
1208 // (a one b)
1209 // == ((a olt b) || (a ogt b))
1210 // == ((a ord b) && (a une b))
1211 CondCode = AArch64CC::VC;
1212 CondCode2 = AArch64CC::NE;
1213 break;
1214 case ISD::SETUEQ:
1215 // (a ueq b)
1216 // == ((a uno b) || (a oeq b))
1217 // == ((a ule b) && (a uge b))
1218 CondCode = AArch64CC::PL;
1219 CondCode2 = AArch64CC::LE;
1220 break;
1221 }
1222}
1223
Tim Northover3b0846e2014-05-24 12:50:23 +00001224/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1225/// CC usable with the vector instructions. Fewer operations are available
1226/// without a real NZCV register, so we have to use less efficient combinations
1227/// to get the same effect.
1228static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1229 AArch64CC::CondCode &CondCode,
1230 AArch64CC::CondCode &CondCode2,
1231 bool &Invert) {
1232 Invert = false;
1233 switch (CC) {
1234 default:
1235 // Mostly the scalar mappings work fine.
1236 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1237 break;
1238 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001239 Invert = true;
1240 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001241 case ISD::SETO:
1242 CondCode = AArch64CC::MI;
1243 CondCode2 = AArch64CC::GE;
1244 break;
1245 case ISD::SETUEQ:
1246 case ISD::SETULT:
1247 case ISD::SETULE:
1248 case ISD::SETUGT:
1249 case ISD::SETUGE:
1250 // All of the compare-mask comparisons are ordered, but we can switch
1251 // between the two by a double inversion. E.g. ULE == !OGT.
1252 Invert = true;
1253 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1254 break;
1255 }
1256}
1257
1258static bool isLegalArithImmed(uint64_t C) {
1259 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1260 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1261}
1262
1263static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001264 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001265 EVT VT = LHS.getValueType();
1266
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001267 if (VT.isFloatingPoint()) {
1268 assert(VT != MVT::f128);
1269 if (VT == MVT::f16) {
1270 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1271 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001272 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001273 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001274 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001275 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001276
1277 // The CMP instruction is just an alias for SUBS, and representing it as
1278 // SUBS means that it's possible to get CSE with subtract operations.
1279 // A later phase can perform the optimization of setting the destination
1280 // register to WZR/XZR if it ends up being unused.
1281 unsigned Opcode = AArch64ISD::SUBS;
1282
Artyom Skrobov314ee042015-11-25 19:41:11 +00001283 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001284 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1285 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1286 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1287 // can be set differently by this operation. It comes down to whether
1288 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1289 // everything is fine. If not then the optimization is wrong. Thus general
1290 // comparisons are only valid if op2 != 0.
1291
1292 // So, finally, the only LLVM-native comparisons that don't mention C and V
1293 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1294 // the absence of information about op2.
1295 Opcode = AArch64ISD::ADDS;
1296 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001297 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001298 !isUnsignedIntSetCC(CC)) {
1299 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1300 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1301 // of the signed comparisons.
1302 Opcode = AArch64ISD::ANDS;
1303 RHS = LHS.getOperand(1);
1304 LHS = LHS.getOperand(0);
1305 }
1306
Matthias Braunaf7d7702015-07-16 20:02:37 +00001307 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001308 .getValue(1);
1309}
1310
Matthias Braunaf7d7702015-07-16 20:02:37 +00001311/// \defgroup AArch64CCMP CMP;CCMP matching
1312///
1313/// These functions deal with the formation of CMP;CCMP;... sequences.
1314/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1315/// a comparison. They set the NZCV flags to a predefined value if their
1316/// predicate is false. This allows to express arbitrary conjunctions, for
1317/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1318/// expressed as:
1319/// cmp A
1320/// ccmp B, inv(CB), CA
1321/// check for CB flags
1322///
1323/// In general we can create code for arbitrary "... (and (and A B) C)"
1324/// sequences. We can also implement some "or" expressions, because "(or A B)"
1325/// is equivalent to "not (and (not A) (not B))" and we can implement some
1326/// negation operations:
1327/// We can negate the results of a single comparison by inverting the flags
1328/// used when the predicate fails and inverting the flags tested in the next
1329/// instruction; We can also negate the results of the whole previous
1330/// conditional compare sequence by inverting the flags tested in the next
1331/// instruction. However there is no way to negate the result of a partial
1332/// sequence.
1333///
1334/// Therefore on encountering an "or" expression we can negate the subtree on
1335/// one side and have to be able to push the negate to the leafs of the subtree
1336/// on the other side (see also the comments in code). As complete example:
1337/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1338/// (and (setCC (cmp C)) (setCD (cmp D)))"
1339/// is transformed to
1340/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1341/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1342/// and implemented as:
1343/// cmp C
1344/// ccmp D, inv(CD), CC
1345/// ccmp A, CA, inv(CD)
1346/// ccmp B, CB, inv(CA)
1347/// check for CB flags
1348/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1349/// by conditional compare sequences.
1350/// @{
1351
Geoff Berrye41c2df2015-07-20 22:03:52 +00001352/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001353static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1354 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001355 AArch64CC::CondCode Predicate,
1356 AArch64CC::CondCode OutCC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001357 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001358 unsigned Opcode = 0;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001359 if (LHS.getValueType().isFloatingPoint()) {
1360 assert(LHS.getValueType() != MVT::f128);
1361 if (LHS.getValueType() == MVT::f16) {
1362 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1363 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1364 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001365 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001366 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001367 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001368 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001369 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1370 Opcode = AArch64ISD::CCMN;
1371 RHS = RHS.getOperand(1);
1372 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001373 }
1374 if (Opcode == 0)
1375 Opcode = AArch64ISD::CCMP;
1376
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001377 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1378 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1379 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001380 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1381 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1382}
1383
1384/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1385/// CanPushNegate is set to true if we can push a negate operation through
1386/// the tree in a was that we are left with AND operations and negate operations
1387/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1388/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1389/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001390static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001391 unsigned Depth = 0) {
1392 if (!Val.hasOneUse())
1393 return false;
1394 unsigned Opcode = Val->getOpcode();
1395 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001396 if (Val->getOperand(0).getValueType() == MVT::f128)
1397 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001398 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001399 return true;
1400 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001401 // Protect against exponential runtime and stack overflow.
1402 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001403 return false;
1404 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1405 SDValue O0 = Val->getOperand(0);
1406 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001407 bool CanNegateL;
1408 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001409 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001410 bool CanNegateR;
1411 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001412 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001413
1414 if (Opcode == ISD::OR) {
1415 // For an OR expression we need to be able to negate at least one side or
1416 // we cannot do the transformation at all.
1417 if (!CanNegateL && !CanNegateR)
1418 return false;
1419 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1420 // can negate the x and y subtrees.
1421 CanNegate = CanNegateL && CanNegateR;
1422 } else {
1423 // If the operands are OR expressions then we finally need to negate their
1424 // outputs, we can only do that for the operand with emitted last by
1425 // negating OutCC, not for both operands.
1426 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1427 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1428 if (NeedsNegOutL && NeedsNegOutR)
1429 return false;
1430 // We cannot negate an AND operation (it would become an OR),
1431 CanNegate = false;
1432 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001433 return true;
1434 }
1435 return false;
1436}
1437
1438/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1439/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1440/// Tries to transform the given i1 producing node @p Val to a series compare
1441/// and conditional compare operations. @returns an NZCV flags producing node
1442/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1443/// transformation was not possible.
1444/// On recursive invocations @p PushNegate may be set to true to have negation
1445/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1446/// for the comparisons in the current subtree; @p Depth limits the search
1447/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001448static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1449 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1450 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001451 // We're at a tree leaf, produce a conditional comparison operation.
1452 unsigned Opcode = Val->getOpcode();
1453 if (Opcode == ISD::SETCC) {
1454 SDValue LHS = Val->getOperand(0);
1455 SDValue RHS = Val->getOperand(1);
1456 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1457 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001458 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001459 CC = getSetCCInverse(CC, isInteger);
1460 SDLoc DL(Val);
1461 // Determine OutCC and handle FP special case.
1462 if (isInteger) {
1463 OutCC = changeIntCCToAArch64CC(CC);
1464 } else {
1465 assert(LHS.getValueType().isFloatingPoint());
1466 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001467 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1468 // Some floating point conditions can't be tested with a single condition
1469 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001470 if (ExtraCC != AArch64CC::AL) {
1471 SDValue ExtraCmp;
1472 if (!CCOp.getNode())
1473 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001474 else
1475 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1476 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001477 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001478 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001479 }
1480 }
1481
1482 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001483 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001484 return emitComparison(LHS, RHS, CC, DL, DAG);
1485 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001486 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001487 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001488 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001489 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1490 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001491
1492 // Check if both sides can be transformed.
1493 SDValue LHS = Val->getOperand(0);
1494 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001495
Matthias Braunfdef49b2016-01-23 04:05:22 +00001496 // In case of an OR we need to negate our operands and the result.
1497 // (A v B) <=> not(not(A) ^ not(B))
1498 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001499 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001500 // predicate flags giving us a free negation for one side. The other side
1501 // must be negatable by itself.
1502 if (NegateOpsAndResult) {
1503 // See which side we can negate.
1504 bool CanNegateL;
1505 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1506 assert(isValidL && "Valid conjunction/disjunction tree");
1507 (void)isValidL;
1508
1509#ifndef NDEBUG
1510 bool CanNegateR;
1511 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1512 assert(isValidR && "Valid conjunction/disjunction tree");
1513 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1514#endif
1515
1516 // Order the side which we cannot negate to RHS so we can emit it first.
1517 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001518 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001519 } else {
1520 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001521 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001522 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001523 // Order the side where we need to negate the output flags to RHS so it
1524 // gets emitted first.
1525 if (NeedsNegOutL)
1526 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001527 }
1528
1529 // Emit RHS. If we want to negate the tree we only need to push a negate
1530 // through if we are already in a PushNegate case, otherwise we can negate
1531 // the "flags to test" afterwards.
1532 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001533 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1534 CCOp, Predicate);
1535 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001536 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001537 // Emit LHS. We may need to negate it.
1538 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1539 NegateOpsAndResult, CmpR,
1540 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001541 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001542 // (or absorb the Negate parameter).
1543 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001544 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1545 return CmpL;
1546}
1547
Matthias Braunfdef49b2016-01-23 04:05:22 +00001548/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1549/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1550/// \see emitConjunctionDisjunctionTreeRec().
1551static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1552 AArch64CC::CondCode &OutCC) {
1553 bool CanNegate;
1554 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1555 return SDValue();
1556
1557 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1558 AArch64CC::AL);
1559}
1560
Matthias Braunaf7d7702015-07-16 20:02:37 +00001561/// @}
1562
Tim Northover3b0846e2014-05-24 12:50:23 +00001563static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001564 SDValue &AArch64cc, SelectionDAG &DAG,
1565 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001566 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1567 EVT VT = RHS.getValueType();
1568 uint64_t C = RHSC->getZExtValue();
1569 if (!isLegalArithImmed(C)) {
1570 // Constant does not fit, try adjusting it by one?
1571 switch (CC) {
1572 default:
1573 break;
1574 case ISD::SETLT:
1575 case ISD::SETGE:
1576 if ((VT == MVT::i32 && C != 0x80000000 &&
1577 isLegalArithImmed((uint32_t)(C - 1))) ||
1578 (VT == MVT::i64 && C != 0x80000000ULL &&
1579 isLegalArithImmed(C - 1ULL))) {
1580 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1581 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001582 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001583 }
1584 break;
1585 case ISD::SETULT:
1586 case ISD::SETUGE:
1587 if ((VT == MVT::i32 && C != 0 &&
1588 isLegalArithImmed((uint32_t)(C - 1))) ||
1589 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1590 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1591 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001592 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001593 }
1594 break;
1595 case ISD::SETLE:
1596 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001597 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001598 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001599 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001600 isLegalArithImmed(C + 1ULL))) {
1601 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1602 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001603 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001604 }
1605 break;
1606 case ISD::SETULE:
1607 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001608 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001609 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001610 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001611 isLegalArithImmed(C + 1ULL))) {
1612 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1613 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001614 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001615 }
1616 break;
1617 }
1618 }
1619 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001620 SDValue Cmp;
1621 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001622 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001623 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1624
1625 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1626 // For the i8 operand, the largest immediate is 255, so this can be easily
1627 // encoded in the compare instruction. For the i16 operand, however, the
1628 // largest immediate cannot be encoded in the compare.
1629 // Therefore, use a sign extending load and cmn to avoid materializing the
1630 // -1 constant. For example,
1631 // movz w1, #65535
1632 // ldrh w0, [x0, #0]
1633 // cmp w0, w1
1634 // >
1635 // ldrsh w0, [x0, #0]
1636 // cmn w0, #1
1637 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1638 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001639 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001640 // transformation is profitable.
1641 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1642 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1643 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1644 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1645 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1646 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1647 SDValue SExt =
1648 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1649 DAG.getValueType(MVT::i16));
1650 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1651 RHS.getValueType()),
1652 CC, dl, DAG);
1653 AArch64CC = changeIntCCToAArch64CC(CC);
1654 }
1655 }
1656
1657 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1658 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1659 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1660 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001661 }
1662 }
1663 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001664
1665 if (!Cmp) {
1666 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1667 AArch64CC = changeIntCCToAArch64CC(CC);
1668 }
1669 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001670 return Cmp;
1671}
1672
1673static std::pair<SDValue, SDValue>
1674getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1675 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1676 "Unsupported value type");
1677 SDValue Value, Overflow;
1678 SDLoc DL(Op);
1679 SDValue LHS = Op.getOperand(0);
1680 SDValue RHS = Op.getOperand(1);
1681 unsigned Opc = 0;
1682 switch (Op.getOpcode()) {
1683 default:
1684 llvm_unreachable("Unknown overflow instruction!");
1685 case ISD::SADDO:
1686 Opc = AArch64ISD::ADDS;
1687 CC = AArch64CC::VS;
1688 break;
1689 case ISD::UADDO:
1690 Opc = AArch64ISD::ADDS;
1691 CC = AArch64CC::HS;
1692 break;
1693 case ISD::SSUBO:
1694 Opc = AArch64ISD::SUBS;
1695 CC = AArch64CC::VS;
1696 break;
1697 case ISD::USUBO:
1698 Opc = AArch64ISD::SUBS;
1699 CC = AArch64CC::LO;
1700 break;
1701 // Multiply needs a little bit extra work.
1702 case ISD::SMULO:
1703 case ISD::UMULO: {
1704 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001705 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001706 if (Op.getValueType() == MVT::i32) {
1707 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1708 // For a 32 bit multiply with overflow check we want the instruction
1709 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1710 // need to generate the following pattern:
1711 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1712 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1713 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1714 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1715 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001716 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001717 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1718 // operation. We need to clear out the upper 32 bits, because we used a
1719 // widening multiply that wrote all 64 bits. In the end this should be a
1720 // noop.
1721 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1722 if (IsSigned) {
1723 // The signed overflow check requires more than just a simple check for
1724 // any bit set in the upper 32 bits of the result. These bits could be
1725 // just the sign bits of a negative number. To perform the overflow
1726 // check we have to arithmetic shift right the 32nd bit of the result by
1727 // 31 bits. Then we compare the result to the upper 32 bits.
1728 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001729 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001730 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1731 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001732 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001733 // It is important that LowerBits is last, otherwise the arithmetic
1734 // shift will not be folded into the compare (SUBS).
1735 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1736 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1737 .getValue(1);
1738 } else {
1739 // The overflow check for unsigned multiply is easy. We only need to
1740 // check if any of the upper 32 bits are set. This can be done with a
1741 // CMP (shifted register). For that we need to generate the following
1742 // pattern:
1743 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1744 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001745 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001746 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1747 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001748 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1749 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001750 UpperBits).getValue(1);
1751 }
1752 break;
1753 }
1754 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1755 // For the 64 bit multiply
1756 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1757 if (IsSigned) {
1758 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1759 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001760 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001761 // It is important that LowerBits is last, otherwise the arithmetic
1762 // shift will not be folded into the compare (SUBS).
1763 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1764 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1765 .getValue(1);
1766 } else {
1767 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1768 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1769 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001770 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1771 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001772 UpperBits).getValue(1);
1773 }
1774 break;
1775 }
1776 } // switch (...)
1777
1778 if (Opc) {
1779 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1780
1781 // Emit the AArch64 operation with overflow check.
1782 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1783 Overflow = Value.getValue(1);
1784 }
1785 return std::make_pair(Value, Overflow);
1786}
1787
1788SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1789 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001790 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001791 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001792}
1793
1794static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1795 SDValue Sel = Op.getOperand(0);
1796 SDValue Other = Op.getOperand(1);
1797
1798 // If neither operand is a SELECT_CC, give up.
1799 if (Sel.getOpcode() != ISD::SELECT_CC)
1800 std::swap(Sel, Other);
1801 if (Sel.getOpcode() != ISD::SELECT_CC)
1802 return Op;
1803
1804 // The folding we want to perform is:
1805 // (xor x, (select_cc a, b, cc, 0, -1) )
1806 // -->
1807 // (csel x, (xor x, -1), cc ...)
1808 //
1809 // The latter will get matched to a CSINV instruction.
1810
1811 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1812 SDValue LHS = Sel.getOperand(0);
1813 SDValue RHS = Sel.getOperand(1);
1814 SDValue TVal = Sel.getOperand(2);
1815 SDValue FVal = Sel.getOperand(3);
1816 SDLoc dl(Sel);
1817
1818 // FIXME: This could be generalized to non-integer comparisons.
1819 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1820 return Op;
1821
1822 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1823 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1824
Eric Christopher572e03a2015-06-19 01:53:21 +00001825 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001826 if (!CFVal || !CTVal)
1827 return Op;
1828
1829 // We can commute the SELECT_CC by inverting the condition. This
1830 // might be needed to make this fit into a CSINV pattern.
1831 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1832 std::swap(TVal, FVal);
1833 std::swap(CTVal, CFVal);
1834 CC = ISD::getSetCCInverse(CC, true);
1835 }
1836
1837 // If the constants line up, perform the transform!
1838 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1839 SDValue CCVal;
1840 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1841
1842 FVal = Other;
1843 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001844 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001845
1846 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1847 CCVal, Cmp);
1848 }
1849
1850 return Op;
1851}
1852
1853static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1854 EVT VT = Op.getValueType();
1855
1856 // Let legalize expand this if it isn't a legal type yet.
1857 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1858 return SDValue();
1859
1860 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1861
1862 unsigned Opc;
1863 bool ExtraOp = false;
1864 switch (Op.getOpcode()) {
1865 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001866 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001867 case ISD::ADDC:
1868 Opc = AArch64ISD::ADDS;
1869 break;
1870 case ISD::SUBC:
1871 Opc = AArch64ISD::SUBS;
1872 break;
1873 case ISD::ADDE:
1874 Opc = AArch64ISD::ADCS;
1875 ExtraOp = true;
1876 break;
1877 case ISD::SUBE:
1878 Opc = AArch64ISD::SBCS;
1879 ExtraOp = true;
1880 break;
1881 }
1882
1883 if (!ExtraOp)
1884 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1885 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1886 Op.getOperand(2));
1887}
1888
1889static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1890 // Let legalize expand this if it isn't a legal type yet.
1891 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1892 return SDValue();
1893
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001894 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001895 AArch64CC::CondCode CC;
1896 // The actual operation that sets the overflow or carry flag.
1897 SDValue Value, Overflow;
1898 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1899
1900 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001901 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1902 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001903
1904 // We use an inverted condition, because the conditional select is inverted
1905 // too. This will allow it to be selected to a single instruction:
1906 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001907 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1908 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001909 CCVal, Overflow);
1910
1911 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001912 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001913}
1914
1915// Prefetch operands are:
1916// 1: Address to prefetch
1917// 2: bool isWrite
1918// 3: int locality (0 = no locality ... 3 = extreme locality)
1919// 4: bool isDataCache
1920static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1921 SDLoc DL(Op);
1922 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1923 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001924 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001925
1926 bool IsStream = !Locality;
1927 // When the locality number is set
1928 if (Locality) {
1929 // The front-end should have filtered out the out-of-range values
1930 assert(Locality <= 3 && "Prefetch locality out-of-range");
1931 // The locality degree is the opposite of the cache speed.
1932 // Put the number the other way around.
1933 // The encoding starts at 0 for level 1
1934 Locality = 3 - Locality;
1935 }
1936
1937 // built the mask value encoding the expected behavior.
1938 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001939 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001940 (Locality << 1) | // Cache level bits
1941 (unsigned)IsStream; // Stream bit
1942 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001943 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001944}
1945
1946SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1947 SelectionDAG &DAG) const {
1948 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1949
1950 RTLIB::Libcall LC;
1951 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1952
1953 return LowerF128Call(Op, DAG, LC);
1954}
1955
1956SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1957 SelectionDAG &DAG) const {
1958 if (Op.getOperand(0).getValueType() != MVT::f128) {
1959 // It's legal except when f128 is involved
1960 return Op;
1961 }
1962
1963 RTLIB::Libcall LC;
1964 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1965
1966 // FP_ROUND node has a second operand indicating whether it is known to be
1967 // precise. That doesn't take part in the LibCall so we can't directly use
1968 // LowerF128Call.
1969 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001970 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1971 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001972}
1973
1974static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1975 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1976 // Any additional optimization in this function should be recorded
1977 // in the cost tables.
1978 EVT InVT = Op.getOperand(0).getValueType();
1979 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001980 unsigned NumElts = InVT.getVectorNumElements();
1981
1982 // f16 vectors are promoted to f32 before a conversion.
1983 if (InVT.getVectorElementType() == MVT::f16) {
1984 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1985 SDLoc dl(Op);
1986 return DAG.getNode(
1987 Op.getOpcode(), dl, Op.getValueType(),
1988 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1989 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001990
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001991 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001992 SDLoc dl(Op);
1993 SDValue Cv =
1994 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1995 Op.getOperand(0));
1996 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001997 }
1998
1999 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002000 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002001 MVT ExtVT =
2002 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2003 VT.getVectorNumElements());
2004 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002005 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2006 }
2007
2008 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002009 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002010}
2011
2012SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2013 SelectionDAG &DAG) const {
2014 if (Op.getOperand(0).getValueType().isVector())
2015 return LowerVectorFP_TO_INT(Op, DAG);
2016
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002017 // f16 conversions are promoted to f32.
2018 if (Op.getOperand(0).getValueType() == MVT::f16) {
2019 SDLoc dl(Op);
2020 return DAG.getNode(
2021 Op.getOpcode(), dl, Op.getValueType(),
2022 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2023 }
2024
Tim Northover3b0846e2014-05-24 12:50:23 +00002025 if (Op.getOperand(0).getValueType() != MVT::f128) {
2026 // It's legal except when f128 is involved
2027 return Op;
2028 }
2029
2030 RTLIB::Libcall LC;
2031 if (Op.getOpcode() == ISD::FP_TO_SINT)
2032 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2033 else
2034 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2035
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002036 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002037 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002038}
2039
2040static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2041 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2042 // Any additional optimization in this function should be recorded
2043 // in the cost tables.
2044 EVT VT = Op.getValueType();
2045 SDLoc dl(Op);
2046 SDValue In = Op.getOperand(0);
2047 EVT InVT = In.getValueType();
2048
Tim Northoveref0d7602014-06-15 09:27:06 +00002049 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2050 MVT CastVT =
2051 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2052 InVT.getVectorNumElements());
2053 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002054 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002055 }
2056
Tim Northoveref0d7602014-06-15 09:27:06 +00002057 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2058 unsigned CastOpc =
2059 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2060 EVT CastVT = VT.changeVectorElementTypeToInteger();
2061 In = DAG.getNode(CastOpc, dl, CastVT, In);
2062 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002063 }
2064
Tim Northoveref0d7602014-06-15 09:27:06 +00002065 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002066}
2067
2068SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2069 SelectionDAG &DAG) const {
2070 if (Op.getValueType().isVector())
2071 return LowerVectorINT_TO_FP(Op, DAG);
2072
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002073 // f16 conversions are promoted to f32.
2074 if (Op.getValueType() == MVT::f16) {
2075 SDLoc dl(Op);
2076 return DAG.getNode(
2077 ISD::FP_ROUND, dl, MVT::f16,
2078 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002079 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002080 }
2081
Tim Northover3b0846e2014-05-24 12:50:23 +00002082 // i128 conversions are libcalls.
2083 if (Op.getOperand(0).getValueType() == MVT::i128)
2084 return SDValue();
2085
2086 // Other conversions are legal, unless it's to the completely software-based
2087 // fp128.
2088 if (Op.getValueType() != MVT::f128)
2089 return Op;
2090
2091 RTLIB::Libcall LC;
2092 if (Op.getOpcode() == ISD::SINT_TO_FP)
2093 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2094 else
2095 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2096
2097 return LowerF128Call(Op, DAG, LC);
2098}
2099
2100SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2101 SelectionDAG &DAG) const {
2102 // For iOS, we want to call an alternative entry point: __sincos_stret,
2103 // which returns the values in two S / D registers.
2104 SDLoc dl(Op);
2105 SDValue Arg = Op.getOperand(0);
2106 EVT ArgVT = Arg.getValueType();
2107 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2108
2109 ArgListTy Args;
2110 ArgListEntry Entry;
2111
2112 Entry.Node = Arg;
2113 Entry.Ty = ArgTy;
2114 Entry.isSExt = false;
2115 Entry.isZExt = false;
2116 Args.push_back(Entry);
2117
2118 const char *LibcallName =
2119 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002120 SDValue Callee =
2121 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002122
Reid Kleckner343c3952014-11-20 23:51:47 +00002123 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002124 TargetLowering::CallLoweringInfo CLI(DAG);
2125 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00002126 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002127
2128 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2129 return CallResult.first;
2130}
2131
Tim Northoverf8bfe212014-07-18 13:07:05 +00002132static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2133 if (Op.getValueType() != MVT::f16)
2134 return SDValue();
2135
2136 assert(Op.getOperand(0).getValueType() == MVT::i16);
2137 SDLoc DL(Op);
2138
2139 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2140 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2141 return SDValue(
2142 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002143 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002144 0);
2145}
2146
Chad Rosierd9d0f862014-10-08 02:31:24 +00002147static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2148 if (OrigVT.getSizeInBits() >= 64)
2149 return OrigVT;
2150
2151 assert(OrigVT.isSimple() && "Expecting a simple value type");
2152
2153 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2154 switch (OrigSimpleTy) {
2155 default: llvm_unreachable("Unexpected Vector Type");
2156 case MVT::v2i8:
2157 case MVT::v2i16:
2158 return MVT::v2i32;
2159 case MVT::v4i8:
2160 return MVT::v4i16;
2161 }
2162}
2163
2164static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2165 const EVT &OrigTy,
2166 const EVT &ExtTy,
2167 unsigned ExtOpcode) {
2168 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2169 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2170 // 64-bits we need to insert a new extension so that it will be 64-bits.
2171 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2172 if (OrigTy.getSizeInBits() >= 64)
2173 return N;
2174
2175 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2176 EVT NewVT = getExtensionTo64Bits(OrigTy);
2177
2178 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2179}
2180
2181static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2182 bool isSigned) {
2183 EVT VT = N->getValueType(0);
2184
2185 if (N->getOpcode() != ISD::BUILD_VECTOR)
2186 return false;
2187
Pete Cooper3af9a252015-06-26 18:17:36 +00002188 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002189 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002190 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002191 unsigned HalfSize = EltSize / 2;
2192 if (isSigned) {
2193 if (!isIntN(HalfSize, C->getSExtValue()))
2194 return false;
2195 } else {
2196 if (!isUIntN(HalfSize, C->getZExtValue()))
2197 return false;
2198 }
2199 continue;
2200 }
2201 return false;
2202 }
2203
2204 return true;
2205}
2206
2207static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2208 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2209 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2210 N->getOperand(0)->getValueType(0),
2211 N->getValueType(0),
2212 N->getOpcode());
2213
2214 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2215 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002216 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002217 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002218 unsigned NumElts = VT.getVectorNumElements();
2219 MVT TruncVT = MVT::getIntegerVT(EltSize);
2220 SmallVector<SDValue, 8> Ops;
2221 for (unsigned i = 0; i != NumElts; ++i) {
2222 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2223 const APInt &CInt = C->getAPIntValue();
2224 // Element types smaller than 32 bits are not legal, so use i32 elements.
2225 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002226 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002227 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002228 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002229}
2230
2231static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2232 if (N->getOpcode() == ISD::SIGN_EXTEND)
2233 return true;
2234 if (isExtendedBUILD_VECTOR(N, DAG, true))
2235 return true;
2236 return false;
2237}
2238
2239static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2240 if (N->getOpcode() == ISD::ZERO_EXTEND)
2241 return true;
2242 if (isExtendedBUILD_VECTOR(N, DAG, false))
2243 return true;
2244 return false;
2245}
2246
2247static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2248 unsigned Opcode = N->getOpcode();
2249 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2250 SDNode *N0 = N->getOperand(0).getNode();
2251 SDNode *N1 = N->getOperand(1).getNode();
2252 return N0->hasOneUse() && N1->hasOneUse() &&
2253 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2254 }
2255 return false;
2256}
2257
2258static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2259 unsigned Opcode = N->getOpcode();
2260 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2261 SDNode *N0 = N->getOperand(0).getNode();
2262 SDNode *N1 = N->getOperand(1).getNode();
2263 return N0->hasOneUse() && N1->hasOneUse() &&
2264 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2265 }
2266 return false;
2267}
2268
2269static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2270 // Multiplications are only custom-lowered for 128-bit vectors so that
2271 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2272 EVT VT = Op.getValueType();
2273 assert(VT.is128BitVector() && VT.isInteger() &&
2274 "unexpected type for custom-lowering ISD::MUL");
2275 SDNode *N0 = Op.getOperand(0).getNode();
2276 SDNode *N1 = Op.getOperand(1).getNode();
2277 unsigned NewOpc = 0;
2278 bool isMLA = false;
2279 bool isN0SExt = isSignExtended(N0, DAG);
2280 bool isN1SExt = isSignExtended(N1, DAG);
2281 if (isN0SExt && isN1SExt)
2282 NewOpc = AArch64ISD::SMULL;
2283 else {
2284 bool isN0ZExt = isZeroExtended(N0, DAG);
2285 bool isN1ZExt = isZeroExtended(N1, DAG);
2286 if (isN0ZExt && isN1ZExt)
2287 NewOpc = AArch64ISD::UMULL;
2288 else if (isN1SExt || isN1ZExt) {
2289 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2290 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2291 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2292 NewOpc = AArch64ISD::SMULL;
2293 isMLA = true;
2294 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2295 NewOpc = AArch64ISD::UMULL;
2296 isMLA = true;
2297 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2298 std::swap(N0, N1);
2299 NewOpc = AArch64ISD::UMULL;
2300 isMLA = true;
2301 }
2302 }
2303
2304 if (!NewOpc) {
2305 if (VT == MVT::v2i64)
2306 // Fall through to expand this. It is not legal.
2307 return SDValue();
2308 else
2309 // Other vector multiplications are legal.
2310 return Op;
2311 }
2312 }
2313
2314 // Legalize to a S/UMULL instruction
2315 SDLoc DL(Op);
2316 SDValue Op0;
2317 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2318 if (!isMLA) {
2319 Op0 = skipExtensionForVectorMULL(N0, DAG);
2320 assert(Op0.getValueType().is64BitVector() &&
2321 Op1.getValueType().is64BitVector() &&
2322 "unexpected types for extended operands to VMULL");
2323 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2324 }
2325 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2326 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2327 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2328 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2329 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2330 EVT Op1VT = Op1.getValueType();
2331 return DAG.getNode(N0->getOpcode(), DL, VT,
2332 DAG.getNode(NewOpc, DL, VT,
2333 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2334 DAG.getNode(NewOpc, DL, VT,
2335 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2336}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002337
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002338SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2339 SelectionDAG &DAG) const {
2340 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2341 SDLoc dl(Op);
2342 switch (IntNo) {
2343 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002344 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002345 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2346 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2347 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002348 case Intrinsic::aarch64_neon_smax:
2349 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2350 Op.getOperand(1), Op.getOperand(2));
2351 case Intrinsic::aarch64_neon_umax:
2352 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2353 Op.getOperand(1), Op.getOperand(2));
2354 case Intrinsic::aarch64_neon_smin:
2355 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2356 Op.getOperand(1), Op.getOperand(2));
2357 case Intrinsic::aarch64_neon_umin:
2358 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2359 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002360 }
2361}
2362
Tim Northover3b0846e2014-05-24 12:50:23 +00002363SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2364 SelectionDAG &DAG) const {
2365 switch (Op.getOpcode()) {
2366 default:
2367 llvm_unreachable("unimplemented operand");
2368 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002369 case ISD::BITCAST:
2370 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002371 case ISD::GlobalAddress:
2372 return LowerGlobalAddress(Op, DAG);
2373 case ISD::GlobalTLSAddress:
2374 return LowerGlobalTLSAddress(Op, DAG);
2375 case ISD::SETCC:
2376 return LowerSETCC(Op, DAG);
2377 case ISD::BR_CC:
2378 return LowerBR_CC(Op, DAG);
2379 case ISD::SELECT:
2380 return LowerSELECT(Op, DAG);
2381 case ISD::SELECT_CC:
2382 return LowerSELECT_CC(Op, DAG);
2383 case ISD::JumpTable:
2384 return LowerJumpTable(Op, DAG);
2385 case ISD::ConstantPool:
2386 return LowerConstantPool(Op, DAG);
2387 case ISD::BlockAddress:
2388 return LowerBlockAddress(Op, DAG);
2389 case ISD::VASTART:
2390 return LowerVASTART(Op, DAG);
2391 case ISD::VACOPY:
2392 return LowerVACOPY(Op, DAG);
2393 case ISD::VAARG:
2394 return LowerVAARG(Op, DAG);
2395 case ISD::ADDC:
2396 case ISD::ADDE:
2397 case ISD::SUBC:
2398 case ISD::SUBE:
2399 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2400 case ISD::SADDO:
2401 case ISD::UADDO:
2402 case ISD::SSUBO:
2403 case ISD::USUBO:
2404 case ISD::SMULO:
2405 case ISD::UMULO:
2406 return LowerXALUO(Op, DAG);
2407 case ISD::FADD:
2408 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2409 case ISD::FSUB:
2410 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2411 case ISD::FMUL:
2412 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2413 case ISD::FDIV:
2414 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2415 case ISD::FP_ROUND:
2416 return LowerFP_ROUND(Op, DAG);
2417 case ISD::FP_EXTEND:
2418 return LowerFP_EXTEND(Op, DAG);
2419 case ISD::FRAMEADDR:
2420 return LowerFRAMEADDR(Op, DAG);
2421 case ISD::RETURNADDR:
2422 return LowerRETURNADDR(Op, DAG);
2423 case ISD::INSERT_VECTOR_ELT:
2424 return LowerINSERT_VECTOR_ELT(Op, DAG);
2425 case ISD::EXTRACT_VECTOR_ELT:
2426 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2427 case ISD::BUILD_VECTOR:
2428 return LowerBUILD_VECTOR(Op, DAG);
2429 case ISD::VECTOR_SHUFFLE:
2430 return LowerVECTOR_SHUFFLE(Op, DAG);
2431 case ISD::EXTRACT_SUBVECTOR:
2432 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2433 case ISD::SRA:
2434 case ISD::SRL:
2435 case ISD::SHL:
2436 return LowerVectorSRA_SRL_SHL(Op, DAG);
2437 case ISD::SHL_PARTS:
2438 return LowerShiftLeftParts(Op, DAG);
2439 case ISD::SRL_PARTS:
2440 case ISD::SRA_PARTS:
2441 return LowerShiftRightParts(Op, DAG);
2442 case ISD::CTPOP:
2443 return LowerCTPOP(Op, DAG);
2444 case ISD::FCOPYSIGN:
2445 return LowerFCOPYSIGN(Op, DAG);
2446 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002447 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002448 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002449 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002450 case ISD::XOR:
2451 return LowerXOR(Op, DAG);
2452 case ISD::PREFETCH:
2453 return LowerPREFETCH(Op, DAG);
2454 case ISD::SINT_TO_FP:
2455 case ISD::UINT_TO_FP:
2456 return LowerINT_TO_FP(Op, DAG);
2457 case ISD::FP_TO_SINT:
2458 case ISD::FP_TO_UINT:
2459 return LowerFP_TO_INT(Op, DAG);
2460 case ISD::FSINCOS:
2461 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002462 case ISD::MUL:
2463 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002464 case ISD::INTRINSIC_WO_CHAIN:
2465 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002466 }
2467}
2468
Tim Northover3b0846e2014-05-24 12:50:23 +00002469//===----------------------------------------------------------------------===//
2470// Calling Convention Implementation
2471//===----------------------------------------------------------------------===//
2472
2473#include "AArch64GenCallingConv.inc"
2474
Robin Morisset039781e2014-08-29 21:53:01 +00002475/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002476CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2477 bool IsVarArg) const {
2478 switch (CC) {
2479 default:
2480 llvm_unreachable("Unsupported calling convention.");
2481 case CallingConv::WebKit_JS:
2482 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002483 case CallingConv::GHC:
2484 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002485 case CallingConv::C:
2486 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002487 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002488 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002489 case CallingConv::Swift:
Tim Northover3b0846e2014-05-24 12:50:23 +00002490 if (!Subtarget->isTargetDarwin())
2491 return CC_AArch64_AAPCS;
2492 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2493 }
2494}
2495
Tim Northover406024a2016-08-10 21:44:01 +00002496CCAssignFn *
2497AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2498 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2499 : RetCC_AArch64_AAPCS;
2500}
2501
Tim Northover3b0846e2014-05-24 12:50:23 +00002502SDValue AArch64TargetLowering::LowerFormalArguments(
2503 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002504 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2505 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002506 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002507 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002508
2509 // Assign locations to all of the incoming arguments.
2510 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002511 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2512 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002513
2514 // At this point, Ins[].VT may already be promoted to i32. To correctly
2515 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2516 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2517 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2518 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2519 // LocVT.
2520 unsigned NumArgs = Ins.size();
2521 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2522 unsigned CurArgIdx = 0;
2523 for (unsigned i = 0; i != NumArgs; ++i) {
2524 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002525 if (Ins[i].isOrigArg()) {
2526 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2527 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002528
Andrew Trick05938a52015-02-16 18:10:47 +00002529 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002530 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2531 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002532 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2533 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2534 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2535 ValVT = MVT::i8;
2536 else if (ActualMVT == MVT::i16)
2537 ValVT = MVT::i16;
2538 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002539 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2540 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002541 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002542 assert(!Res && "Call operand has unhandled type");
2543 (void)Res;
2544 }
2545 assert(ArgLocs.size() == Ins.size());
2546 SmallVector<SDValue, 16> ArgValues;
2547 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2548 CCValAssign &VA = ArgLocs[i];
2549
2550 if (Ins[i].Flags.isByVal()) {
2551 // Byval is used for HFAs in the PCS, but the system should work in a
2552 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002553 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002554 int Size = Ins[i].Flags.getByValSize();
2555 unsigned NumRegs = (Size + 7) / 8;
2556
2557 // FIXME: This works on big-endian for composite byvals, which are the common
2558 // case. It should also work for fundamental types too.
2559 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002560 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002561 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002562 InVals.push_back(FrameIdxN);
2563
2564 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002565 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002566
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002567 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002568 // Arguments stored in registers.
2569 EVT RegVT = VA.getLocVT();
2570
2571 SDValue ArgValue;
2572 const TargetRegisterClass *RC;
2573
2574 if (RegVT == MVT::i32)
2575 RC = &AArch64::GPR32RegClass;
2576 else if (RegVT == MVT::i64)
2577 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002578 else if (RegVT == MVT::f16)
2579 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002580 else if (RegVT == MVT::f32)
2581 RC = &AArch64::FPR32RegClass;
2582 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2583 RC = &AArch64::FPR64RegClass;
2584 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2585 RC = &AArch64::FPR128RegClass;
2586 else
2587 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2588
2589 // Transform the arguments in physical registers into virtual ones.
2590 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2591 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2592
2593 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2594 // to 64 bits. Insert an assert[sz]ext to capture this, then
2595 // truncate to the right size.
2596 switch (VA.getLocInfo()) {
2597 default:
2598 llvm_unreachable("Unknown loc info!");
2599 case CCValAssign::Full:
2600 break;
2601 case CCValAssign::BCvt:
2602 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2603 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002604 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002605 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002606 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002607 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2608 // nodes after our lowering.
2609 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002610 break;
2611 }
2612
2613 InVals.push_back(ArgValue);
2614
2615 } else { // VA.isRegLoc()
2616 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2617 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002618 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002619
2620 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002621 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2622 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002623 BEAlign = 8 - ArgSize;
2624
Matthias Braun941a7052016-07-28 18:40:00 +00002625 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002626
2627 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002628 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002629 SDValue ArgValue;
2630
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002631 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002632 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002633 MVT MemVT = VA.getValVT();
2634
Tim Northover47e003c2014-05-26 17:21:53 +00002635 switch (VA.getLocInfo()) {
2636 default:
2637 break;
Tim Northover6890add2014-06-03 13:54:53 +00002638 case CCValAssign::BCvt:
2639 MemVT = VA.getLocVT();
2640 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002641 case CCValAssign::SExt:
2642 ExtType = ISD::SEXTLOAD;
2643 break;
2644 case CCValAssign::ZExt:
2645 ExtType = ISD::ZEXTLOAD;
2646 break;
2647 case CCValAssign::AExt:
2648 ExtType = ISD::EXTLOAD;
2649 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002650 }
2651
Alex Lorenze40c8a22015-08-11 23:09:45 +00002652 ArgValue = DAG.getExtLoad(
2653 ExtType, DL, VA.getLocVT(), Chain, FIN,
2654 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002655 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002656
Tim Northover3b0846e2014-05-24 12:50:23 +00002657 InVals.push_back(ArgValue);
2658 }
2659 }
2660
2661 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002662 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002663 if (isVarArg) {
2664 if (!Subtarget->isTargetDarwin()) {
2665 // The AAPCS variadic function ABI is identical to the non-variadic
2666 // one. As a result there may be more arguments in registers and we should
2667 // save them for future reference.
2668 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2669 }
2670
Tim Northover3b0846e2014-05-24 12:50:23 +00002671 // This will point to the next argument passed via stack.
2672 unsigned StackOffset = CCInfo.getNextStackOffset();
2673 // We currently pass all varargs at 8-byte alignment.
2674 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002675 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002676 }
2677
Tim Northover3b0846e2014-05-24 12:50:23 +00002678 unsigned StackArgSize = CCInfo.getNextStackOffset();
2679 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2680 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2681 // This is a non-standard ABI so by fiat I say we're allowed to make full
2682 // use of the stack area to be popped, which must be aligned to 16 bytes in
2683 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002684 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002685
2686 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2687 // a multiple of 16.
2688 FuncInfo->setArgumentStackToRestore(StackArgSize);
2689
2690 // This realignment carries over to the available bytes below. Our own
2691 // callers will guarantee the space is free by giving an aligned value to
2692 // CALLSEQ_START.
2693 }
2694 // Even if we're not expected to free up the space, it's useful to know how
2695 // much is there while considering tail calls (because we can reuse it).
2696 FuncInfo->setBytesInStackArgArea(StackArgSize);
2697
2698 return Chain;
2699}
2700
2701void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002702 SelectionDAG &DAG,
2703 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002704 SDValue &Chain) const {
2705 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002706 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002707 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002708 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002709
2710 SmallVector<SDValue, 8> MemOps;
2711
2712 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2713 AArch64::X3, AArch64::X4, AArch64::X5,
2714 AArch64::X6, AArch64::X7 };
2715 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002716 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002717
2718 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2719 int GPRIdx = 0;
2720 if (GPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002721 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002722
Mehdi Amini44ede332015-07-09 02:09:04 +00002723 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002724
2725 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2726 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2727 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002728 SDValue Store = DAG.getStore(
2729 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002730 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002731 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002732 FIN =
2733 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002734 }
2735 }
2736 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2737 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2738
2739 if (Subtarget->hasFPARMv8()) {
2740 static const MCPhysReg FPRArgRegs[] = {
2741 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2742 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2743 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002744 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002745
2746 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2747 int FPRIdx = 0;
2748 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002749 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002750
Mehdi Amini44ede332015-07-09 02:09:04 +00002751 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002752
2753 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2754 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2755 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2756
Alex Lorenze40c8a22015-08-11 23:09:45 +00002757 SDValue Store = DAG.getStore(
2758 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002759 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00002760 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002761 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2762 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002763 }
2764 }
2765 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2766 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2767 }
2768
2769 if (!MemOps.empty()) {
2770 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2771 }
2772}
2773
2774/// LowerCallResult - Lower the result values of a call into the
2775/// appropriate copies out of appropriate physical registers.
2776SDValue AArch64TargetLowering::LowerCallResult(
2777 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002778 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2779 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002780 SDValue ThisVal) const {
2781 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2782 ? RetCC_AArch64_WebKit_JS
2783 : RetCC_AArch64_AAPCS;
2784 // Assign locations to each value returned by this call.
2785 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002786 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2787 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002788 CCInfo.AnalyzeCallResult(Ins, RetCC);
2789
2790 // Copy all of the result registers out of their specified physreg.
2791 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2792 CCValAssign VA = RVLocs[i];
2793
2794 // Pass 'this' value directly from the argument to return value, to avoid
2795 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00002796 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002797 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2798 "unexpected return calling convention register assignment");
2799 InVals.push_back(ThisVal);
2800 continue;
2801 }
2802
2803 SDValue Val =
2804 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2805 Chain = Val.getValue(1);
2806 InFlag = Val.getValue(2);
2807
2808 switch (VA.getLocInfo()) {
2809 default:
2810 llvm_unreachable("Unknown loc info!");
2811 case CCValAssign::Full:
2812 break;
2813 case CCValAssign::BCvt:
2814 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2815 break;
2816 }
2817
2818 InVals.push_back(Val);
2819 }
2820
2821 return Chain;
2822}
2823
Matthias Braun1af14142016-09-13 19:27:38 +00002824/// Return true if the calling convention is one that we can guarantee TCO for.
2825static bool canGuaranteeTCO(CallingConv::ID CC) {
2826 return CC == CallingConv::Fast;
2827}
2828
2829/// Return true if we might ever do TCO for calls with this calling convention.
2830static bool mayTailCallThisCC(CallingConv::ID CC) {
2831 switch (CC) {
2832 case CallingConv::C:
2833 case CallingConv::PreserveMost:
2834 case CallingConv::Swift:
2835 return true;
2836 default:
2837 return canGuaranteeTCO(CC);
2838 }
2839}
2840
Tim Northover3b0846e2014-05-24 12:50:23 +00002841bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2842 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00002843 const SmallVectorImpl<ISD::OutputArg> &Outs,
2844 const SmallVectorImpl<SDValue> &OutVals,
2845 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00002846 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00002847 return false;
2848
Matthias Braun8d414362016-03-30 22:46:04 +00002849 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002850 const Function *CallerF = MF.getFunction();
2851 CallingConv::ID CallerCC = CallerF->getCallingConv();
2852 bool CCMatch = CallerCC == CalleeCC;
2853
2854 // Byval parameters hand the function a pointer directly into the stack area
2855 // we want to reuse during a tail call. Working around this *is* possible (see
2856 // X86) but less efficient and uglier in LowerCall.
2857 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2858 e = CallerF->arg_end();
2859 i != e; ++i)
2860 if (i->hasByValAttr())
2861 return false;
2862
Matthias Braun1af14142016-09-13 19:27:38 +00002863 if (getTargetMachine().Options.GuaranteedTailCallOpt)
2864 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002865
Oliver Stannard12993dd2014-08-18 12:42:15 +00002866 // Externally-defined functions with weak linkage should not be
2867 // tail-called on AArch64 when the OS does not support dynamic
2868 // pre-emption of symbols, as the AAELF spec requires normal calls
2869 // to undefined weak functions to be replaced with a NOP or jump to the
2870 // next instruction. The behaviour of branch instructions in this
2871 // situation (as used for tail calls) is implementation-defined, so we
2872 // cannot rely on the linker replacing the tail call with a return.
2873 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2874 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002875 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002876 if (GV->hasExternalWeakLinkage() &&
2877 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002878 return false;
2879 }
2880
Tim Northover3b0846e2014-05-24 12:50:23 +00002881 // Now we search for cases where we can use a tail call without changing the
2882 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2883 // concept.
2884
2885 // I want anyone implementing a new calling convention to think long and hard
2886 // about this assert.
2887 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2888 "Unexpected variadic calling convention");
2889
Matthias Braun8d414362016-03-30 22:46:04 +00002890 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00002891 if (isVarArg && !Outs.empty()) {
2892 // At least two cases here: if caller is fastcc then we can't have any
2893 // memory arguments (we'd be expected to clean up the stack afterwards). If
2894 // caller is C then we could potentially use its argument area.
2895
2896 // FIXME: for now we take the most conservative of these in both cases:
2897 // disallow all variadic memory operands.
2898 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002899 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002900
2901 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002902 for (const CCValAssign &ArgLoc : ArgLocs)
2903 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002904 return false;
2905 }
2906
Matthias Braun8d414362016-03-30 22:46:04 +00002907 // Check that the call results are passed in the same way.
2908 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2909 CCAssignFnForCall(CalleeCC, isVarArg),
2910 CCAssignFnForCall(CallerCC, isVarArg)))
2911 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00002912 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00002913 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2914 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00002915 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00002916 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2917 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00002918 return false;
2919 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002920
2921 // Nothing more to check if the callee is taking no arguments
2922 if (Outs.empty())
2923 return true;
2924
2925 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002926 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002927
2928 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2929
2930 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2931
Matthias Braun74a0bd32016-04-13 21:43:16 +00002932 // If the stack arguments for this call do not fit into our own save area then
2933 // the call cannot be made tail.
2934 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2935 return false;
2936
Matthias Braun46b0f032016-04-14 01:10:42 +00002937 const MachineRegisterInfo &MRI = MF.getRegInfo();
2938 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2939 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00002940
2941 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00002942}
2943
2944SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2945 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00002946 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00002947 int ClobberedFI) const {
2948 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00002949 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2950 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002951
2952 // Include the original chain at the beginning of the list. When this is
2953 // used by target LowerCall hooks, this helps legalize find the
2954 // CALLSEQ_BEGIN node.
2955 ArgChains.push_back(Chain);
2956
2957 // Add a chain value for each stack argument corresponding
2958 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2959 UE = DAG.getEntryNode().getNode()->use_end();
2960 U != UE; ++U)
2961 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2962 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2963 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002964 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00002965 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00002966 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002967
2968 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2969 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2970 ArgChains.push_back(SDValue(L, 1));
2971 }
2972
2973 // Build a tokenfactor for all the chains.
2974 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2975}
2976
2977bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2978 bool TailCallOpt) const {
2979 return CallCC == CallingConv::Fast && TailCallOpt;
2980}
2981
Tim Northover3b0846e2014-05-24 12:50:23 +00002982/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2983/// and add input and output parameter nodes.
2984SDValue
2985AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2986 SmallVectorImpl<SDValue> &InVals) const {
2987 SelectionDAG &DAG = CLI.DAG;
2988 SDLoc &DL = CLI.DL;
2989 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2990 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2991 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2992 SDValue Chain = CLI.Chain;
2993 SDValue Callee = CLI.Callee;
2994 bool &IsTailCall = CLI.IsTailCall;
2995 CallingConv::ID CallConv = CLI.CallConv;
2996 bool IsVarArg = CLI.IsVarArg;
2997
2998 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002999 bool IsThisReturn = false;
3000
3001 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3002 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3003 bool IsSibCall = false;
3004
3005 if (IsTailCall) {
3006 // Check if it's really possible to do a tail call.
3007 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003008 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003009 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3010 report_fatal_error("failed to perform tail call elimination on a call "
3011 "site marked musttail");
3012
3013 // A sibling call is one where we're under the usual C ABI and not planning
3014 // to change that but can still do a tail call:
3015 if (!TailCallOpt && IsTailCall)
3016 IsSibCall = true;
3017
3018 if (IsTailCall)
3019 ++NumTailCalls;
3020 }
3021
3022 // Analyze operands of the call, assigning locations to each operand.
3023 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003024 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3025 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003026
3027 if (IsVarArg) {
3028 // Handle fixed and variable vector arguments differently.
3029 // Variable vector arguments always go into memory.
3030 unsigned NumArgs = Outs.size();
3031
3032 for (unsigned i = 0; i != NumArgs; ++i) {
3033 MVT ArgVT = Outs[i].VT;
3034 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3035 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3036 /*IsVarArg=*/ !Outs[i].IsFixed);
3037 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3038 assert(!Res && "Call operand has unhandled type");
3039 (void)Res;
3040 }
3041 } else {
3042 // At this point, Outs[].VT may already be promoted to i32. To correctly
3043 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3044 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3045 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3046 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3047 // LocVT.
3048 unsigned NumArgs = Outs.size();
3049 for (unsigned i = 0; i != NumArgs; ++i) {
3050 MVT ValVT = Outs[i].VT;
3051 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003052 EVT ActualVT = getValueType(DAG.getDataLayout(),
3053 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003054 /*AllowUnknown*/ true);
3055 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3056 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3057 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003058 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003059 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003060 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003061 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003062
3063 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003064 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003065 assert(!Res && "Call operand has unhandled type");
3066 (void)Res;
3067 }
3068 }
3069
3070 // Get a count of how many bytes are to be pushed on the stack.
3071 unsigned NumBytes = CCInfo.getNextStackOffset();
3072
3073 if (IsSibCall) {
3074 // Since we're not changing the ABI to make this a tail call, the memory
3075 // operands are already available in the caller's incoming argument space.
3076 NumBytes = 0;
3077 }
3078
3079 // FPDiff is the byte offset of the call's argument area from the callee's.
3080 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3081 // by this amount for a tail call. In a sibling call it must be 0 because the
3082 // caller will deallocate the entire stack and the callee still expects its
3083 // arguments to begin at SP+0. Completely unused for non-tail calls.
3084 int FPDiff = 0;
3085
3086 if (IsTailCall && !IsSibCall) {
3087 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3088
3089 // Since callee will pop argument stack as a tail call, we must keep the
3090 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003091 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003092
3093 // FPDiff will be negative if this tail call requires more space than we
3094 // would automatically have in our incoming argument space. Positive if we
3095 // can actually shrink the stack.
3096 FPDiff = NumReusableBytes - NumBytes;
3097
3098 // The stack pointer must be 16-byte aligned at all times it's used for a
3099 // memory operation, which in practice means at *all* times and in
3100 // particular across call boundaries. Therefore our own arguments started at
3101 // a 16-byte aligned SP and the delta applied for the tail call should
3102 // satisfy the same constraint.
3103 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3104 }
3105
3106 // Adjust the stack pointer for the new arguments...
3107 // These operations are automatically eliminated by the prolog/epilog pass
3108 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003109 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3110 true),
3111 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003112
Mehdi Amini44ede332015-07-09 02:09:04 +00003113 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3114 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003115
3116 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3117 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003118 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003119
3120 // Walk the register/memloc assignments, inserting copies/loads.
3121 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3122 ++i, ++realArgIdx) {
3123 CCValAssign &VA = ArgLocs[i];
3124 SDValue Arg = OutVals[realArgIdx];
3125 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3126
3127 // Promote the value if needed.
3128 switch (VA.getLocInfo()) {
3129 default:
3130 llvm_unreachable("Unknown loc info!");
3131 case CCValAssign::Full:
3132 break;
3133 case CCValAssign::SExt:
3134 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3135 break;
3136 case CCValAssign::ZExt:
3137 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3138 break;
3139 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003140 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3141 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3142 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3143 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3144 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003145 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3146 break;
3147 case CCValAssign::BCvt:
3148 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3149 break;
3150 case CCValAssign::FPExt:
3151 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3152 break;
3153 }
3154
3155 if (VA.isRegLoc()) {
3156 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3157 assert(VA.getLocVT() == MVT::i64 &&
3158 "unexpected calling convention register assignment");
3159 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3160 "unexpected use of 'returned'");
3161 IsThisReturn = true;
3162 }
3163 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3164 } else {
3165 assert(VA.isMemLoc());
3166
3167 SDValue DstAddr;
3168 MachinePointerInfo DstInfo;
3169
3170 // FIXME: This works on big-endian for composite byvals, which are the
3171 // common case. It should also work for fundamental types too.
3172 uint32_t BEAlign = 0;
3173 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003174 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003175 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003176 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3177 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003178 if (OpSize < 8)
3179 BEAlign = 8 - OpSize;
3180 }
3181 unsigned LocMemOffset = VA.getLocMemOffset();
3182 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003183 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003184 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003185
3186 if (IsTailCall) {
3187 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003188 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003189
Mehdi Amini44ede332015-07-09 02:09:04 +00003190 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003191 DstInfo =
3192 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003193
3194 // Make sure any stack arguments overlapping with where we're storing
3195 // are loaded before this eventual operation. Otherwise they'll be
3196 // clobbered.
3197 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3198 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003199 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003200
Mehdi Amini44ede332015-07-09 02:09:04 +00003201 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003202 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3203 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003204 }
3205
3206 if (Outs[i].Flags.isByVal()) {
3207 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003208 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003209 SDValue Cpy = DAG.getMemcpy(
3210 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003211 /*isVol = */ false, /*AlwaysInline = */ false,
3212 /*isTailCall = */ false,
3213 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003214
3215 MemOpChains.push_back(Cpy);
3216 } else {
3217 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3218 // promoted to a legal register type i32, we should truncate Arg back to
3219 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003220 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3221 VA.getValVT() == MVT::i16)
3222 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003223
Justin Lebar9c375812016-07-15 18:27:10 +00003224 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003225 MemOpChains.push_back(Store);
3226 }
3227 }
3228 }
3229
3230 if (!MemOpChains.empty())
3231 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3232
3233 // Build a sequence of copy-to-reg nodes chained together with token chain
3234 // and flag operands which copy the outgoing args into the appropriate regs.
3235 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003236 for (auto &RegToPass : RegsToPass) {
3237 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3238 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003239 InFlag = Chain.getValue(1);
3240 }
3241
3242 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3243 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3244 // node so that legalize doesn't hack it.
3245 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3246 Subtarget->isTargetMachO()) {
3247 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3248 const GlobalValue *GV = G->getGlobal();
3249 bool InternalLinkage = GV->hasInternalLinkage();
3250 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003251 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003252 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003253 Callee =
3254 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3255 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003256 }
3257 } else if (ExternalSymbolSDNode *S =
3258 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3259 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003260 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3261 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003262 }
3263 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3264 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003265 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003266 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3267 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003268 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003269 }
3270
3271 // We don't usually want to end the call-sequence here because we would tidy
3272 // the frame up *after* the call, however in the ABI-changing tail-call case
3273 // we've carefully laid out the parameters so that when sp is reset they'll be
3274 // in the correct location.
3275 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003276 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3277 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003278 InFlag = Chain.getValue(1);
3279 }
3280
3281 std::vector<SDValue> Ops;
3282 Ops.push_back(Chain);
3283 Ops.push_back(Callee);
3284
3285 if (IsTailCall) {
3286 // Each tail call may have to adjust the stack by a different amount, so
3287 // this information must travel along with the operation for eventual
3288 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003289 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003290 }
3291
3292 // Add argument registers to the end of the list so that they are known live
3293 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003294 for (auto &RegToPass : RegsToPass)
3295 Ops.push_back(DAG.getRegister(RegToPass.first,
3296 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003297
3298 // Add a register mask operand representing the call-preserved registers.
3299 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003300 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003301 if (IsThisReturn) {
3302 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003303 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003304 if (!Mask) {
3305 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003306 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003307 }
3308 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003309 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003310
3311 assert(Mask && "Missing call preserved mask for calling convention");
3312 Ops.push_back(DAG.getRegisterMask(Mask));
3313
3314 if (InFlag.getNode())
3315 Ops.push_back(InFlag);
3316
3317 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3318
3319 // If we're doing a tall call, use a TC_RETURN here rather than an
3320 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003321 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003322 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003323 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003324 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003325
3326 // Returns a chain and a flag for retval copy to use.
3327 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3328 InFlag = Chain.getValue(1);
3329
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003330 uint64_t CalleePopBytes =
3331 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003332
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003333 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3334 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003335 InFlag, DL);
3336 if (!Ins.empty())
3337 InFlag = Chain.getValue(1);
3338
3339 // Handle result values, copying them out of physregs into vregs that we
3340 // return.
3341 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3342 InVals, IsThisReturn,
3343 IsThisReturn ? OutVals[0] : SDValue());
3344}
3345
3346bool AArch64TargetLowering::CanLowerReturn(
3347 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3348 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3349 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3350 ? RetCC_AArch64_WebKit_JS
3351 : RetCC_AArch64_AAPCS;
3352 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003353 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003354 return CCInfo.CheckReturn(Outs, RetCC);
3355}
3356
3357SDValue
3358AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3359 bool isVarArg,
3360 const SmallVectorImpl<ISD::OutputArg> &Outs,
3361 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003362 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003363 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3364 ? RetCC_AArch64_WebKit_JS
3365 : RetCC_AArch64_AAPCS;
3366 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003367 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3368 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003369 CCInfo.AnalyzeReturn(Outs, RetCC);
3370
3371 // Copy the result values into the output registers.
3372 SDValue Flag;
3373 SmallVector<SDValue, 4> RetOps(1, Chain);
3374 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3375 ++i, ++realRVLocIdx) {
3376 CCValAssign &VA = RVLocs[i];
3377 assert(VA.isRegLoc() && "Can only return in registers!");
3378 SDValue Arg = OutVals[realRVLocIdx];
3379
3380 switch (VA.getLocInfo()) {
3381 default:
3382 llvm_unreachable("Unknown loc info!");
3383 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003384 if (Outs[i].ArgVT == MVT::i1) {
3385 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3386 // value. This is strictly redundant on Darwin (which uses "zeroext
3387 // i1"), but will be optimised out before ISel.
3388 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3389 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3390 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003391 break;
3392 case CCValAssign::BCvt:
3393 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3394 break;
3395 }
3396
3397 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3398 Flag = Chain.getValue(1);
3399 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3400 }
Manman Rencbe4f942015-12-16 21:04:19 +00003401 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3402 const MCPhysReg *I =
3403 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3404 if (I) {
3405 for (; *I; ++I) {
3406 if (AArch64::GPR64RegClass.contains(*I))
3407 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3408 else if (AArch64::FPR64RegClass.contains(*I))
3409 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3410 else
3411 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3412 }
3413 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003414
3415 RetOps[0] = Chain; // Update chain.
3416
3417 // Add the flag if we have it.
3418 if (Flag.getNode())
3419 RetOps.push_back(Flag);
3420
3421 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3422}
3423
3424//===----------------------------------------------------------------------===//
3425// Other Lowering Code
3426//===----------------------------------------------------------------------===//
3427
3428SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3429 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003430 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003431 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003432 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3433 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003434 unsigned char OpFlags =
3435 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3436
3437 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3438 "unexpected offset in global node");
3439
3440 // This also catched the large code model case for Darwin.
3441 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3442 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3443 // FIXME: Once remat is capable of dealing with instructions with register
3444 // operands, expand this into two nodes instead of using a wrapper node.
3445 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3446 }
3447
3448 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3449 const unsigned char MO_NC = AArch64II::MO_NC;
3450 return DAG.getNode(
3451 AArch64ISD::WrapperLarge, DL, PtrVT,
3452 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3453 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3454 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3455 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3456 } else {
3457 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3458 // the only correct model on Darwin.
3459 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3460 OpFlags | AArch64II::MO_PAGE);
3461 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3462 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3463
3464 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3465 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3466 }
3467}
3468
3469/// \brief Convert a TLS address reference into the correct sequence of loads
3470/// and calls to compute the variable's address (for Darwin, currently) and
3471/// return an SDValue containing the final node.
3472
3473/// Darwin only has one TLS scheme which must be capable of dealing with the
3474/// fully general situation, in the worst case. This means:
3475/// + "extern __thread" declaration.
3476/// + Defined in a possibly unknown dynamic library.
3477///
3478/// The general system is that each __thread variable has a [3 x i64] descriptor
3479/// which contains information used by the runtime to calculate the address. The
3480/// only part of this the compiler needs to know about is the first xword, which
3481/// contains a function pointer that must be called with the address of the
3482/// entire descriptor in "x0".
3483///
3484/// Since this descriptor may be in a different unit, in general even the
3485/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3486/// is:
3487/// adrp x0, _var@TLVPPAGE
3488/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3489/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3490/// ; the function pointer
3491/// blr x1 ; Uses descriptor address in x0
3492/// ; Address of _var is now in x0.
3493///
3494/// If the address of _var's descriptor *is* known to the linker, then it can
3495/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3496/// a slight efficiency gain.
3497SDValue
3498AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3499 SelectionDAG &DAG) const {
3500 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3501
3502 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003503 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003504 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3505
3506 SDValue TLVPAddr =
3507 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3508 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3509
3510 // The first entry in the descriptor is a function pointer that we must call
3511 // to obtain the address of the variable.
3512 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00003513 SDValue FuncTLVGet = DAG.getLoad(
3514 MVT::i64, DL, Chain, DescAddr,
3515 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3516 /* Alignment = */ 8,
3517 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3518 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00003519 Chain = FuncTLVGet.getValue(1);
3520
Matthias Braun941a7052016-07-28 18:40:00 +00003521 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3522 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003523
3524 // TLS calls preserve all registers except those that absolutely must be
3525 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3526 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003527 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003528 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003529
3530 // Finally, we can make the call. This is just a degenerate version of a
3531 // normal AArch64 call node: x0 takes the address of the descriptor, and
3532 // returns the address of the variable in this thread.
3533 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3534 Chain =
3535 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3536 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3537 DAG.getRegisterMask(Mask), Chain.getValue(1));
3538 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3539}
3540
3541/// When accessing thread-local variables under either the general-dynamic or
3542/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3543/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003544/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003545///
Kristof Beylsaea84612015-03-04 09:12:08 +00003546/// The sequence is:
3547/// adrp x0, :tlsdesc:var
3548/// ldr x1, [x0, #:tlsdesc_lo12:var]
3549/// add x0, x0, #:tlsdesc_lo12:var
3550/// .tlsdesccall var
3551/// blr x1
3552/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003553///
Kristof Beylsaea84612015-03-04 09:12:08 +00003554/// The above sequence must be produced unscheduled, to enable the linker to
3555/// optimize/relax this sequence.
3556/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3557/// above sequence, and expanded really late in the compilation flow, to ensure
3558/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003559SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3560 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003561 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003562 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003563
Kristof Beylsaea84612015-03-04 09:12:08 +00003564 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003565 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003566
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003567 Chain =
3568 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003569 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003570
3571 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3572}
3573
3574SDValue
3575AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3576 SelectionDAG &DAG) const {
3577 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3578 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3579 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003580 // Different choices can be made for the maximum size of the TLS area for a
3581 // module. For the small address model, the default TLS size is 16MiB and the
3582 // maximum TLS size is 4GiB.
3583 // FIXME: add -mtls-size command line option and make it control the 16MiB
3584 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003585 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3586
3587 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003588
3589 if (DAG.getTarget().Options.EmulatedTLS)
3590 return LowerToTLSEmulatedModel(GA, DAG);
3591
Kristof Beylsaea84612015-03-04 09:12:08 +00003592 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3593 if (Model == TLSModel::LocalDynamic)
3594 Model = TLSModel::GeneralDynamic;
3595 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003596
3597 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003598 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003599 SDLoc DL(Op);
3600 const GlobalValue *GV = GA->getGlobal();
3601
3602 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3603
3604 if (Model == TLSModel::LocalExec) {
3605 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003606 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003607 SDValue LoVar = DAG.getTargetGlobalAddress(
3608 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003609 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003610
Kristof Beylsaea84612015-03-04 09:12:08 +00003611 SDValue TPWithOff_lo =
3612 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003613 HiVar,
3614 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003615 0);
3616 SDValue TPWithOff =
3617 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003618 LoVar,
3619 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003620 0);
3621 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003622 } else if (Model == TLSModel::InitialExec) {
3623 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3624 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3625 } else if (Model == TLSModel::LocalDynamic) {
3626 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3627 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3628 // the beginning of the module's TLS region, followed by a DTPREL offset
3629 // calculation.
3630
3631 // These accesses will need deduplicating if there's more than one.
3632 AArch64FunctionInfo *MFI =
3633 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3634 MFI->incNumLocalDynamicTLSAccesses();
3635
Tim Northover3b0846e2014-05-24 12:50:23 +00003636 // The call needs a relocation too for linker relaxation. It doesn't make
3637 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3638 // the address.
3639 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3640 AArch64II::MO_TLS);
3641
3642 // Now we can calculate the offset from TPIDR_EL0 to this module's
3643 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003644 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003645
3646 // Now use :dtprel_whatever: operations to calculate this variable's offset
3647 // in its thread-storage area.
3648 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003649 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003650 SDValue LoVar = DAG.getTargetGlobalAddress(
3651 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003652 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3653
Kristof Beylsaea84612015-03-04 09:12:08 +00003654 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003655 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003656 0);
3657 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003658 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003659 0);
3660 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003661 // The call needs a relocation too for linker relaxation. It doesn't make
3662 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3663 // the address.
3664 SDValue SymAddr =
3665 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3666
3667 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003668 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003669 } else
3670 llvm_unreachable("Unsupported ELF TLS access model");
3671
3672 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3673}
3674
3675SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3676 SelectionDAG &DAG) const {
3677 if (Subtarget->isTargetDarwin())
3678 return LowerDarwinGlobalTLSAddress(Op, DAG);
3679 else if (Subtarget->isTargetELF())
3680 return LowerELFGlobalTLSAddress(Op, DAG);
3681
3682 llvm_unreachable("Unexpected platform trying to use TLS");
3683}
Eugene Zelenko049b0172017-01-06 00:30:53 +00003684
Tim Northover3b0846e2014-05-24 12:50:23 +00003685SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3686 SDValue Chain = Op.getOperand(0);
3687 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3688 SDValue LHS = Op.getOperand(2);
3689 SDValue RHS = Op.getOperand(3);
3690 SDValue Dest = Op.getOperand(4);
3691 SDLoc dl(Op);
3692
3693 // Handle f128 first, since lowering it will result in comparing the return
3694 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3695 // is expecting to deal with.
3696 if (LHS.getValueType() == MVT::f128) {
3697 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3698
3699 // If softenSetCCOperands returned a scalar, we need to compare the result
3700 // against zero to select between true and false values.
3701 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003702 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003703 CC = ISD::SETNE;
3704 }
3705 }
3706
3707 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3708 // instruction.
3709 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003710 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003711 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3712 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3713 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3714 "Unexpected condition code.");
3715 // Only lower legal XALUO ops.
3716 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3717 return SDValue();
3718
3719 // The actual operation with overflow check.
3720 AArch64CC::CondCode OFCC;
3721 SDValue Value, Overflow;
3722 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3723
3724 if (CC == ISD::SETNE)
3725 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003726 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003727
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003728 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3729 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003730 }
3731
3732 if (LHS.getValueType().isInteger()) {
3733 assert((LHS.getValueType() == RHS.getValueType()) &&
3734 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3735
3736 // If the RHS of the comparison is zero, we can potentially fold this
3737 // to a specialized branch.
3738 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3739 if (RHSC && RHSC->getZExtValue() == 0) {
3740 if (CC == ISD::SETEQ) {
3741 // See if we can use a TBZ to fold in an AND as well.
3742 // TBZ has a smaller branch displacement than CBZ. If the offset is
3743 // out of bounds, a late MI-layer pass rewrites branches.
3744 // 403.gcc is an example that hits this case.
3745 if (LHS.getOpcode() == ISD::AND &&
3746 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3747 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3748 SDValue Test = LHS.getOperand(0);
3749 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003750 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003751 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3752 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003753 }
3754
3755 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3756 } else if (CC == ISD::SETNE) {
3757 // See if we can use a TBZ to fold in an AND as well.
3758 // TBZ has a smaller branch displacement than CBZ. If the offset is
3759 // out of bounds, a late MI-layer pass rewrites branches.
3760 // 403.gcc is an example that hits this case.
3761 if (LHS.getOpcode() == ISD::AND &&
3762 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3763 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3764 SDValue Test = LHS.getOperand(0);
3765 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003766 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003767 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3768 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003769 }
3770
3771 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003772 } else if (CC == ISD::SETLT && 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.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00003776 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00003777 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003778 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003779 }
3780 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003781 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3782 LHS.getOpcode() != ISD::AND) {
3783 // Don't combine AND since emitComparison converts the AND to an ANDS
3784 // (a.k.a. TST) and the test in the test bit and branch instruction
3785 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00003786 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00003787 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003788 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003789 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003790
3791 SDValue CCVal;
3792 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3793 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3794 Cmp);
3795 }
3796
3797 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3798
3799 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3800 // clean. Some of them require two branches to implement.
3801 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3802 AArch64CC::CondCode CC1, CC2;
3803 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003804 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003805 SDValue BR1 =
3806 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3807 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003808 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003809 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3810 Cmp);
3811 }
3812
3813 return BR1;
3814}
3815
3816SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3817 SelectionDAG &DAG) const {
3818 EVT VT = Op.getValueType();
3819 SDLoc DL(Op);
3820
3821 SDValue In1 = Op.getOperand(0);
3822 SDValue In2 = Op.getOperand(1);
3823 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003824
3825 if (SrcVT.bitsLT(VT))
3826 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3827 else if (SrcVT.bitsGT(VT))
3828 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003829
3830 EVT VecVT;
3831 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003832 uint64_t EltMask;
3833 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003834 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3835 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003836 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003837 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003838
3839 if (!VT.isVector()) {
3840 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3841 DAG.getUNDEF(VecVT), In1);
3842 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3843 DAG.getUNDEF(VecVT), In2);
3844 } else {
3845 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3846 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3847 }
3848 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3849 EltVT = MVT::i64;
3850 VecVT = MVT::v2i64;
3851
Eric Christopher572e03a2015-06-19 01:53:21 +00003852 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003853 // immediate moves cannot materialize that in a single instruction for
3854 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003855 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003856
3857 if (!VT.isVector()) {
3858 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3859 DAG.getUNDEF(VecVT), In1);
3860 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3861 DAG.getUNDEF(VecVT), In2);
3862 } else {
3863 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3864 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3865 }
3866 } else {
3867 llvm_unreachable("Invalid type for copysign!");
3868 }
3869
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003870 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003871
3872 // If we couldn't materialize the mask above, then the mask vector will be
3873 // the zero vector, and we need to negate it here.
3874 if (VT == MVT::f64 || VT == MVT::v2f64) {
3875 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3876 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3877 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3878 }
3879
3880 SDValue Sel =
3881 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3882
3883 if (VT == MVT::f32)
3884 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3885 else if (VT == MVT::f64)
3886 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3887 else
3888 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3889}
3890
3891SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003892 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3893 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003894 return SDValue();
3895
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003896 if (!Subtarget->hasNEON())
3897 return SDValue();
3898
Tim Northover3b0846e2014-05-24 12:50:23 +00003899 // While there is no integer popcount instruction, it can
3900 // be more efficiently lowered to the following sequence that uses
3901 // AdvSIMD registers/instructions as long as the copies to/from
3902 // the AdvSIMD registers are cheap.
3903 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3904 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3905 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3906 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3907 SDValue Val = Op.getOperand(0);
3908 SDLoc DL(Op);
3909 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003910
Hao Liue0335d72015-01-30 02:13:53 +00003911 if (VT == MVT::i32)
3912 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3913 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003914
Hao Liue0335d72015-01-30 02:13:53 +00003915 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003916 SDValue UaddLV = DAG.getNode(
3917 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003918 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003919
3920 if (VT == MVT::i64)
3921 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3922 return UaddLV;
3923}
3924
3925SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3926
3927 if (Op.getValueType().isVector())
3928 return LowerVSETCC(Op, DAG);
3929
3930 SDValue LHS = Op.getOperand(0);
3931 SDValue RHS = Op.getOperand(1);
3932 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3933 SDLoc dl(Op);
3934
3935 // We chose ZeroOrOneBooleanContents, so use zero and one.
3936 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003937 SDValue TVal = DAG.getConstant(1, dl, VT);
3938 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003939
3940 // Handle f128 first, since one possible outcome is a normal integer
3941 // comparison which gets picked up by the next if statement.
3942 if (LHS.getValueType() == MVT::f128) {
3943 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3944
3945 // If softenSetCCOperands returned a scalar, use it.
3946 if (!RHS.getNode()) {
3947 assert(LHS.getValueType() == Op.getValueType() &&
3948 "Unexpected setcc expansion!");
3949 return LHS;
3950 }
3951 }
3952
3953 if (LHS.getValueType().isInteger()) {
3954 SDValue CCVal;
3955 SDValue Cmp =
3956 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3957
3958 // Note that we inverted the condition above, so we reverse the order of
3959 // the true and false operands here. This will allow the setcc to be
3960 // matched to a single CSINC instruction.
3961 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3962 }
3963
3964 // Now we know we're dealing with FP values.
3965 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3966
3967 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3968 // and do the comparison.
3969 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3970
3971 AArch64CC::CondCode CC1, CC2;
3972 changeFPCCToAArch64CC(CC, CC1, CC2);
3973 if (CC2 == AArch64CC::AL) {
3974 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003975 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003976
3977 // Note that we inverted the condition above, so we reverse the order of
3978 // the true and false operands here. This will allow the setcc to be
3979 // matched to a single CSINC instruction.
3980 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3981 } else {
3982 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3983 // totally clean. Some of them require two CSELs to implement. As is in
3984 // this case, we emit the first CSEL and then emit a second using the output
3985 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3986
3987 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003988 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003989 SDValue CS1 =
3990 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3991
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003992 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003993 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3994 }
3995}
3996
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003997SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3998 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003999 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004000 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004001 // Handle f128 first, because it will result in a comparison of some RTLIB
4002 // call result against zero.
4003 if (LHS.getValueType() == MVT::f128) {
4004 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4005
4006 // If softenSetCCOperands returned a scalar, we need to compare the result
4007 // against zero to select between true and false values.
4008 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004009 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004010 CC = ISD::SETNE;
4011 }
4012 }
4013
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004014 // Also handle f16, for which we need to do a f32 comparison.
4015 if (LHS.getValueType() == MVT::f16) {
4016 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4017 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4018 }
4019
4020 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004021 if (LHS.getValueType().isInteger()) {
4022 assert((LHS.getValueType() == RHS.getValueType()) &&
4023 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4024
4025 unsigned Opcode = AArch64ISD::CSEL;
4026
4027 // If both the TVal and the FVal are constants, see if we can swap them in
4028 // order to for a CSINV or CSINC out of them.
4029 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4030 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4031
4032 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4033 std::swap(TVal, FVal);
4034 std::swap(CTVal, CFVal);
4035 CC = ISD::getSetCCInverse(CC, true);
4036 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4037 std::swap(TVal, FVal);
4038 std::swap(CTVal, CFVal);
4039 CC = ISD::getSetCCInverse(CC, true);
4040 } else if (TVal.getOpcode() == ISD::XOR) {
4041 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4042 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004043 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004044 std::swap(TVal, FVal);
4045 std::swap(CTVal, CFVal);
4046 CC = ISD::getSetCCInverse(CC, true);
4047 }
4048 } else if (TVal.getOpcode() == ISD::SUB) {
4049 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4050 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004051 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004052 std::swap(TVal, FVal);
4053 std::swap(CTVal, CFVal);
4054 CC = ISD::getSetCCInverse(CC, true);
4055 }
4056 } else if (CTVal && CFVal) {
4057 const int64_t TrueVal = CTVal->getSExtValue();
4058 const int64_t FalseVal = CFVal->getSExtValue();
4059 bool Swap = false;
4060
4061 // If both TVal and FVal are constants, see if FVal is the
4062 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4063 // instead of a CSEL in that case.
4064 if (TrueVal == ~FalseVal) {
4065 Opcode = AArch64ISD::CSINV;
4066 } else if (TrueVal == -FalseVal) {
4067 Opcode = AArch64ISD::CSNEG;
4068 } else if (TVal.getValueType() == MVT::i32) {
4069 // If our operands are only 32-bit wide, make sure we use 32-bit
4070 // arithmetic for the check whether we can use CSINC. This ensures that
4071 // the addition in the check will wrap around properly in case there is
4072 // an overflow (which would not be the case if we do the check with
4073 // 64-bit arithmetic).
4074 const uint32_t TrueVal32 = CTVal->getZExtValue();
4075 const uint32_t FalseVal32 = CFVal->getZExtValue();
4076
4077 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4078 Opcode = AArch64ISD::CSINC;
4079
4080 if (TrueVal32 > FalseVal32) {
4081 Swap = true;
4082 }
4083 }
4084 // 64-bit check whether we can use CSINC.
4085 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4086 Opcode = AArch64ISD::CSINC;
4087
4088 if (TrueVal > FalseVal) {
4089 Swap = true;
4090 }
4091 }
4092
4093 // Swap TVal and FVal if necessary.
4094 if (Swap) {
4095 std::swap(TVal, FVal);
4096 std::swap(CTVal, CFVal);
4097 CC = ISD::getSetCCInverse(CC, true);
4098 }
4099
4100 if (Opcode != AArch64ISD::CSEL) {
4101 // Drop FVal since we can get its value by simply inverting/negating
4102 // TVal.
4103 FVal = TVal;
4104 }
4105 }
4106
Chad Rosier58f505b2016-08-26 18:05:50 +00004107 // Avoid materializing a constant when possible by reusing a known value in
4108 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004109 // is one, zero or negative one in the case of a CSEL. We can always
4110 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4111 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004112 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4113 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4114 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4115 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4116 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4117 // "a != C ? x : a" to avoid materializing C.
4118 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4119 TVal = LHS;
4120 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4121 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004122 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4123 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4124 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4125 // avoid materializing C.
4126 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4127 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4128 Opcode = AArch64ISD::CSINV;
4129 TVal = LHS;
4130 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4131 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004132 }
4133
Tim Northover3b0846e2014-05-24 12:50:23 +00004134 SDValue CCVal;
4135 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4136
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004137 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004138 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4139 }
4140
4141 // Now we know we're dealing with FP values.
4142 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4143 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004144 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004145 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4146
4147 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4148 // clean. Some of them require two CSELs to implement.
4149 AArch64CC::CondCode CC1, CC2;
4150 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004151
4152 if (DAG.getTarget().Options.UnsafeFPMath) {
4153 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4154 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4155 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4156 if (RHSVal && RHSVal->isZero()) {
4157 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4158 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4159
4160 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004161 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004162 TVal = LHS;
4163 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004164 CFVal && CFVal->isZero() &&
4165 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004166 FVal = LHS;
4167 }
4168 }
4169
4170 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004171 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004172 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4173
4174 // If we need a second CSEL, emit it, using the output of the first as the
4175 // RHS. We're effectively OR'ing the two CC's together.
4176 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004177 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004178 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4179 }
4180
4181 // Otherwise, return the output of the first CSEL.
4182 return CS1;
4183}
4184
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004185SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4186 SelectionDAG &DAG) const {
4187 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4188 SDValue LHS = Op.getOperand(0);
4189 SDValue RHS = Op.getOperand(1);
4190 SDValue TVal = Op.getOperand(2);
4191 SDValue FVal = Op.getOperand(3);
4192 SDLoc DL(Op);
4193 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4194}
4195
4196SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4197 SelectionDAG &DAG) const {
4198 SDValue CCVal = Op->getOperand(0);
4199 SDValue TVal = Op->getOperand(1);
4200 SDValue FVal = Op->getOperand(2);
4201 SDLoc DL(Op);
4202
4203 unsigned Opc = CCVal.getOpcode();
4204 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4205 // instruction.
4206 if (CCVal.getResNo() == 1 &&
4207 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4208 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4209 // Only lower legal XALUO ops.
4210 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4211 return SDValue();
4212
4213 AArch64CC::CondCode OFCC;
4214 SDValue Value, Overflow;
4215 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004216 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004217
4218 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4219 CCVal, Overflow);
4220 }
4221
4222 // Lower it the same way as we would lower a SELECT_CC node.
4223 ISD::CondCode CC;
4224 SDValue LHS, RHS;
4225 if (CCVal.getOpcode() == ISD::SETCC) {
4226 LHS = CCVal.getOperand(0);
4227 RHS = CCVal.getOperand(1);
4228 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4229 } else {
4230 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004231 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004232 CC = ISD::SETNE;
4233 }
4234 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4235}
4236
Tim Northover3b0846e2014-05-24 12:50:23 +00004237SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4238 SelectionDAG &DAG) const {
4239 // Jump table entries as PC relative offsets. No additional tweaking
4240 // is necessary here. Just get the address of the jump table.
4241 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004242 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004243 SDLoc DL(Op);
4244
4245 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4246 !Subtarget->isTargetMachO()) {
4247 const unsigned char MO_NC = AArch64II::MO_NC;
4248 return DAG.getNode(
4249 AArch64ISD::WrapperLarge, DL, PtrVT,
4250 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4251 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4252 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4253 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4254 AArch64II::MO_G0 | MO_NC));
4255 }
4256
4257 SDValue Hi =
4258 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4259 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4260 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4261 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4262 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4263}
4264
4265SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4266 SelectionDAG &DAG) const {
4267 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004268 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004269 SDLoc DL(Op);
4270
4271 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4272 // Use the GOT for the large code model on iOS.
4273 if (Subtarget->isTargetMachO()) {
4274 SDValue GotAddr = DAG.getTargetConstantPool(
4275 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4276 AArch64II::MO_GOT);
4277 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4278 }
4279
4280 const unsigned char MO_NC = AArch64II::MO_NC;
4281 return DAG.getNode(
4282 AArch64ISD::WrapperLarge, DL, PtrVT,
4283 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4284 CP->getOffset(), AArch64II::MO_G3),
4285 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4286 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4287 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4288 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4289 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4290 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4291 } else {
4292 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4293 // ELF, the only valid one on Darwin.
4294 SDValue Hi =
4295 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4296 CP->getOffset(), AArch64II::MO_PAGE);
4297 SDValue Lo = DAG.getTargetConstantPool(
4298 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4299 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4300
4301 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4302 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4303 }
4304}
4305
4306SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4307 SelectionDAG &DAG) const {
4308 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004309 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004310 SDLoc DL(Op);
4311 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4312 !Subtarget->isTargetMachO()) {
4313 const unsigned char MO_NC = AArch64II::MO_NC;
4314 return DAG.getNode(
4315 AArch64ISD::WrapperLarge, DL, PtrVT,
4316 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4317 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4318 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4319 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4320 } else {
4321 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4322 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4323 AArch64II::MO_NC);
4324 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4325 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4326 }
4327}
4328
4329SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4330 SelectionDAG &DAG) const {
4331 AArch64FunctionInfo *FuncInfo =
4332 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4333
4334 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004335 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4336 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004337 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4338 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004339 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004340}
4341
4342SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4343 SelectionDAG &DAG) const {
4344 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4345 // Standard, section B.3.
4346 MachineFunction &MF = DAG.getMachineFunction();
4347 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004348 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004349 SDLoc DL(Op);
4350
4351 SDValue Chain = Op.getOperand(0);
4352 SDValue VAList = Op.getOperand(1);
4353 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4354 SmallVector<SDValue, 4> MemOps;
4355
4356 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004357 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004358 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004359 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004360
4361 // void *__gr_top at offset 8
4362 int GPRSize = FuncInfo->getVarArgsGPRSize();
4363 if (GPRSize > 0) {
4364 SDValue GRTop, GRTopAddr;
4365
Mehdi Amini44ede332015-07-09 02:09:04 +00004366 GRTopAddr =
4367 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004368
Mehdi Amini44ede332015-07-09 02:09:04 +00004369 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4370 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4371 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004372
4373 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004374 MachinePointerInfo(SV, 8),
4375 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004376 }
4377
4378 // void *__vr_top at offset 16
4379 int FPRSize = FuncInfo->getVarArgsFPRSize();
4380 if (FPRSize > 0) {
4381 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004382 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4383 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004384
Mehdi Amini44ede332015-07-09 02:09:04 +00004385 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4386 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4387 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004388
4389 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004390 MachinePointerInfo(SV, 16),
4391 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004392 }
4393
4394 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004395 SDValue GROffsAddr =
4396 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004397 MemOps.push_back(DAG.getStore(
4398 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4399 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004400
4401 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004402 SDValue VROffsAddr =
4403 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004404 MemOps.push_back(DAG.getStore(
4405 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4406 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004407
4408 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4409}
4410
4411SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4412 SelectionDAG &DAG) const {
4413 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4414 : LowerAAPCS_VASTART(Op, DAG);
4415}
4416
4417SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4418 SelectionDAG &DAG) const {
4419 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4420 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004421 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004422 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4423 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4424 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4425
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004426 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4427 Op.getOperand(2),
4428 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004429 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004430 MachinePointerInfo(SrcSV));
4431}
4432
4433SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4434 assert(Subtarget->isTargetDarwin() &&
4435 "automatic va_arg instruction only works on Darwin");
4436
4437 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4438 EVT VT = Op.getValueType();
4439 SDLoc DL(Op);
4440 SDValue Chain = Op.getOperand(0);
4441 SDValue Addr = Op.getOperand(1);
4442 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004443 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004444
Justin Lebar9c375812016-07-15 18:27:10 +00004445 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004446 Chain = VAList.getValue(1);
4447
4448 if (Align > 8) {
4449 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004450 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4451 DAG.getConstant(Align - 1, DL, PtrVT));
4452 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4453 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004454 }
4455
4456 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004457 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004458
4459 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4460 // up to 64 bits. At the very least, we have to increase the striding of the
4461 // vaargs list to match this, and for FP values we need to introduce
4462 // FP_ROUND nodes as well.
4463 if (VT.isInteger() && !VT.isVector())
4464 ArgSize = 8;
4465 bool NeedFPTrunc = false;
4466 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4467 ArgSize = 8;
4468 NeedFPTrunc = true;
4469 }
4470
4471 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004472 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4473 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004474 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004475 SDValue APStore =
4476 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004477
4478 // Load the actual argument out of the pointer VAList
4479 if (NeedFPTrunc) {
4480 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004481 SDValue WideFP =
4482 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004483 // Round the value down to an f32.
4484 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004485 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004486 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4487 // Merge the rounded value with the chain output of the load.
4488 return DAG.getMergeValues(Ops, DL);
4489 }
4490
Justin Lebar9c375812016-07-15 18:27:10 +00004491 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004492}
4493
4494SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4495 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004496 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4497 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004498
4499 EVT VT = Op.getValueType();
4500 SDLoc DL(Op);
4501 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4502 SDValue FrameAddr =
4503 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4504 while (Depth--)
4505 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004506 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004507 return FrameAddr;
4508}
4509
4510// FIXME? Maybe this could be a TableGen attribute on some registers and
4511// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004512unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4513 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004514 unsigned Reg = StringSwitch<unsigned>(RegName)
4515 .Case("sp", AArch64::SP)
4516 .Default(0);
4517 if (Reg)
4518 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004519 report_fatal_error(Twine("Invalid register name \""
4520 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004521}
4522
4523SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4524 SelectionDAG &DAG) const {
4525 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004526 MachineFrameInfo &MFI = MF.getFrameInfo();
4527 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004528
4529 EVT VT = Op.getValueType();
4530 SDLoc DL(Op);
4531 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4532 if (Depth) {
4533 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004534 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004535 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4536 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004537 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004538 }
4539
4540 // Return LR, which contains the return address. Mark it an implicit live-in.
4541 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4542 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4543}
4544
4545/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4546/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4547SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4548 SelectionDAG &DAG) const {
4549 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4550 EVT VT = Op.getValueType();
4551 unsigned VTBits = VT.getSizeInBits();
4552 SDLoc dl(Op);
4553 SDValue ShOpLo = Op.getOperand(0);
4554 SDValue ShOpHi = Op.getOperand(1);
4555 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004556 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4557
4558 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4559
4560 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004561 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004562 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4563
4564 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4565 // is "undef". We wanted 0, so CSEL it directly.
4566 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4567 ISD::SETEQ, dl, DAG);
4568 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4569 HiBitsForLo =
4570 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4571 HiBitsForLo, CCVal, Cmp);
4572
Tim Northover3b0846e2014-05-24 12:50:23 +00004573 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004574 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004575
Tim Northoverf3be9d52015-12-02 00:33:54 +00004576 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4577 SDValue LoForNormalShift =
4578 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004579
Tim Northoverf3be9d52015-12-02 00:33:54 +00004580 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4581 dl, DAG);
4582 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4583 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4584 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4585 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004586
4587 // AArch64 shifts larger than the register width are wrapped rather than
4588 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004589 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4590 SDValue HiForBigShift =
4591 Opc == ISD::SRA
4592 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4593 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4594 : DAG.getConstant(0, dl, VT);
4595 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4596 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004597
4598 SDValue Ops[2] = { Lo, Hi };
4599 return DAG.getMergeValues(Ops, dl);
4600}
4601
4602/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4603/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4604SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004605 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004606 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4607 EVT VT = Op.getValueType();
4608 unsigned VTBits = VT.getSizeInBits();
4609 SDLoc dl(Op);
4610 SDValue ShOpLo = Op.getOperand(0);
4611 SDValue ShOpHi = Op.getOperand(1);
4612 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004613
4614 assert(Op.getOpcode() == ISD::SHL_PARTS);
4615 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004616 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004617 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4618
4619 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4620 // is "undef". We wanted 0, so CSEL it directly.
4621 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4622 ISD::SETEQ, dl, DAG);
4623 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4624 LoBitsForHi =
4625 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4626 LoBitsForHi, CCVal, Cmp);
4627
Tim Northover3b0846e2014-05-24 12:50:23 +00004628 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004629 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004630 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4631 SDValue HiForNormalShift =
4632 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004633
Tim Northoverf3be9d52015-12-02 00:33:54 +00004634 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004635
Tim Northoverf3be9d52015-12-02 00:33:54 +00004636 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4637 dl, DAG);
4638 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4639 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4640 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004641
4642 // AArch64 shifts of larger than register sizes are wrapped rather than
4643 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004644 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4645 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4646 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4647 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004648
4649 SDValue Ops[2] = { Lo, Hi };
4650 return DAG.getMergeValues(Ops, dl);
4651}
4652
4653bool AArch64TargetLowering::isOffsetFoldingLegal(
4654 const GlobalAddressSDNode *GA) const {
4655 // The AArch64 target doesn't support folding offsets into global addresses.
4656 return false;
4657}
4658
4659bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4660 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4661 // FIXME: We should be able to handle f128 as well with a clever lowering.
4662 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4663 return true;
4664
4665 if (VT == MVT::f64)
4666 return AArch64_AM::getFP64Imm(Imm) != -1;
4667 else if (VT == MVT::f32)
4668 return AArch64_AM::getFP32Imm(Imm) != -1;
4669 return false;
4670}
4671
4672//===----------------------------------------------------------------------===//
4673// AArch64 Optimization Hooks
4674//===----------------------------------------------------------------------===//
4675
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004676static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4677 SDValue Operand, SelectionDAG &DAG,
4678 int &ExtraSteps) {
4679 EVT VT = Operand.getValueType();
4680 if (ST->hasNEON() &&
4681 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4682 VT == MVT::f32 || VT == MVT::v1f32 ||
4683 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4684 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4685 // For the reciprocal estimates, convergence is quadratic, so the number
4686 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4687 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4688 // the result for float (23 mantissa bits) is 2 and for double (52
4689 // mantissa bits) is 3.
4690 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4691
4692 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4693 }
4694
4695 return SDValue();
4696}
4697
Evandro Menezes21f9ce12016-11-10 23:31:06 +00004698SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4699 SelectionDAG &DAG, int Enabled,
4700 int &ExtraSteps,
4701 bool &UseOneConst,
4702 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004703 if (Enabled == ReciprocalEstimate::Enabled ||
4704 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4705 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4706 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00004707 SDLoc DL(Operand);
4708 EVT VT = Operand.getValueType();
4709
4710 SDNodeFlags Flags;
4711 Flags.setUnsafeAlgebra(true);
4712
4713 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4714 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4715 for (int i = ExtraSteps; i > 0; --i) {
4716 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4717 &Flags);
4718 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags);
4719 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4720 }
4721
4722 if (!Reciprocal) {
4723 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4724 VT);
4725 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4726 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4727
4728 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags);
4729 // Correct the result if the operand is 0.0.
4730 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4731 VT, Eq, Operand, Estimate);
4732 }
4733
4734 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004735 return Estimate;
4736 }
4737
4738 return SDValue();
4739}
4740
4741SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4742 SelectionDAG &DAG, int Enabled,
4743 int &ExtraSteps) const {
4744 if (Enabled == ReciprocalEstimate::Enabled)
4745 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00004746 DAG, ExtraSteps)) {
4747 SDLoc DL(Operand);
4748 EVT VT = Operand.getValueType();
4749
4750 SDNodeFlags Flags;
4751 Flags.setUnsafeAlgebra(true);
4752
4753 // Newton reciprocal iteration: E * (2 - X * E)
4754 // AArch64 reciprocal iteration instruction: (2 - M * N)
4755 for (int i = ExtraSteps; i > 0; --i) {
4756 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4757 Estimate, &Flags);
4758 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4759 }
4760
4761 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004762 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00004763 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004764
4765 return SDValue();
4766}
4767
Tim Northover3b0846e2014-05-24 12:50:23 +00004768//===----------------------------------------------------------------------===//
4769// AArch64 Inline Assembly Support
4770//===----------------------------------------------------------------------===//
4771
4772// Table of Constraints
4773// TODO: This is the current set of constraints supported by ARM for the
4774// compiler, not all of them may make sense, e.g. S may be difficult to support.
4775//
4776// r - A general register
4777// w - An FP/SIMD register of some size in the range v0-v31
4778// x - An FP/SIMD register of some size in the range v0-v15
4779// I - Constant that can be used with an ADD instruction
4780// J - Constant that can be used with a SUB instruction
4781// K - Constant that can be used with a 32-bit logical instruction
4782// L - Constant that can be used with a 64-bit logical instruction
4783// M - Constant that can be used as a 32-bit MOV immediate
4784// N - Constant that can be used as a 64-bit MOV immediate
4785// Q - A memory reference with base register and no offset
4786// S - A symbolic address
4787// Y - Floating point constant zero
4788// Z - Integer constant zero
4789//
4790// Note that general register operands will be output using their 64-bit x
4791// register name, whatever the size of the variable, unless the asm operand
4792// is prefixed by the %w modifier. Floating-point and SIMD register operands
4793// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4794// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00004795const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4796 // At this point, we have to lower this constraint to something else, so we
4797 // lower it to an "r" or "w". However, by doing this we will force the result
4798 // to be in register, while the X constraint is much more permissive.
4799 //
4800 // Although we are correct (we are free to emit anything, without
4801 // constraints), we might break use cases that would expect us to be more
4802 // efficient and emit something else.
4803 if (!Subtarget->hasFPARMv8())
4804 return "r";
4805
4806 if (ConstraintVT.isFloatingPoint())
4807 return "w";
4808
4809 if (ConstraintVT.isVector() &&
4810 (ConstraintVT.getSizeInBits() == 64 ||
4811 ConstraintVT.getSizeInBits() == 128))
4812 return "w";
4813
4814 return "r";
4815}
Tim Northover3b0846e2014-05-24 12:50:23 +00004816
4817/// getConstraintType - Given a constraint letter, return the type of
4818/// constraint it is for this target.
4819AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004820AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004821 if (Constraint.size() == 1) {
4822 switch (Constraint[0]) {
4823 default:
4824 break;
4825 case 'z':
4826 return C_Other;
4827 case 'x':
4828 case 'w':
4829 return C_RegisterClass;
4830 // An address with a single base register. Due to the way we
4831 // currently handle addresses it is the same as 'r'.
4832 case 'Q':
4833 return C_Memory;
4834 }
4835 }
4836 return TargetLowering::getConstraintType(Constraint);
4837}
4838
4839/// Examine constraint type and operand type and determine a weight value.
4840/// This object must already have been set up with the operand type
4841/// and the current alternative constraint selected.
4842TargetLowering::ConstraintWeight
4843AArch64TargetLowering::getSingleConstraintMatchWeight(
4844 AsmOperandInfo &info, const char *constraint) const {
4845 ConstraintWeight weight = CW_Invalid;
4846 Value *CallOperandVal = info.CallOperandVal;
4847 // If we don't have a value, we can't do a match,
4848 // but allow it at the lowest weight.
4849 if (!CallOperandVal)
4850 return CW_Default;
4851 Type *type = CallOperandVal->getType();
4852 // Look at the constraint type.
4853 switch (*constraint) {
4854 default:
4855 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4856 break;
4857 case 'x':
4858 case 'w':
4859 if (type->isFloatingPointTy() || type->isVectorTy())
4860 weight = CW_Register;
4861 break;
4862 case 'z':
4863 weight = CW_Constant;
4864 break;
4865 }
4866 return weight;
4867}
4868
4869std::pair<unsigned, const TargetRegisterClass *>
4870AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004871 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004872 if (Constraint.size() == 1) {
4873 switch (Constraint[0]) {
4874 case 'r':
4875 if (VT.getSizeInBits() == 64)
4876 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4877 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4878 case 'w':
Amara Emerson614b44b2016-11-07 15:42:12 +00004879 if (VT.getSizeInBits() == 16)
4880 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00004881 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00004882 return std::make_pair(0U, &AArch64::FPR32RegClass);
4883 if (VT.getSizeInBits() == 64)
4884 return std::make_pair(0U, &AArch64::FPR64RegClass);
4885 if (VT.getSizeInBits() == 128)
4886 return std::make_pair(0U, &AArch64::FPR128RegClass);
4887 break;
4888 // The instructions that this constraint is designed for can
4889 // only take 128-bit registers so just use that regclass.
4890 case 'x':
4891 if (VT.getSizeInBits() == 128)
4892 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4893 break;
4894 }
4895 }
4896 if (StringRef("{cc}").equals_lower(Constraint))
4897 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4898
4899 // Use the default implementation in TargetLowering to convert the register
4900 // constraint into a member of a register class.
4901 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004902 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004903
4904 // Not found as a standard register?
4905 if (!Res.second) {
4906 unsigned Size = Constraint.size();
4907 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4908 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004909 int RegNo;
4910 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4911 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00004912 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00004913 // By default we'll emit v0-v31 for this unless there's a modifier where
4914 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00004915 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4916 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4917 Res.second = &AArch64::FPR64RegClass;
4918 } else {
4919 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4920 Res.second = &AArch64::FPR128RegClass;
4921 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004922 }
4923 }
4924 }
4925
4926 return Res;
4927}
4928
4929/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4930/// vector. If it is invalid, don't add anything to Ops.
4931void AArch64TargetLowering::LowerAsmOperandForConstraint(
4932 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4933 SelectionDAG &DAG) const {
4934 SDValue Result;
4935
4936 // Currently only support length 1 constraints.
4937 if (Constraint.length() != 1)
4938 return;
4939
4940 char ConstraintLetter = Constraint[0];
4941 switch (ConstraintLetter) {
4942 default:
4943 break;
4944
4945 // This set of constraints deal with valid constants for various instructions.
4946 // Validate and return a target constant for them if we can.
4947 case 'z': {
4948 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004949 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004950 return;
4951
4952 if (Op.getValueType() == MVT::i64)
4953 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4954 else
4955 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4956 break;
4957 }
4958
4959 case 'I':
4960 case 'J':
4961 case 'K':
4962 case 'L':
4963 case 'M':
4964 case 'N':
4965 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4966 if (!C)
4967 return;
4968
4969 // Grab the value and do some validation.
4970 uint64_t CVal = C->getZExtValue();
4971 switch (ConstraintLetter) {
4972 // The I constraint applies only to simple ADD or SUB immediate operands:
4973 // i.e. 0 to 4095 with optional shift by 12
4974 // The J constraint applies only to ADD or SUB immediates that would be
4975 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4976 // instruction [or vice versa], in other words -1 to -4095 with optional
4977 // left shift by 12.
4978 case 'I':
4979 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4980 break;
4981 return;
4982 case 'J': {
4983 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004984 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4985 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004986 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004987 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004988 return;
4989 }
4990 // The K and L constraints apply *only* to logical immediates, including
4991 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4992 // been removed and MOV should be used). So these constraints have to
4993 // distinguish between bit patterns that are valid 32-bit or 64-bit
4994 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4995 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4996 // versa.
4997 case 'K':
4998 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4999 break;
5000 return;
5001 case 'L':
5002 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5003 break;
5004 return;
5005 // The M and N constraints are a superset of K and L respectively, for use
5006 // with the MOV (immediate) alias. As well as the logical immediates they
5007 // also match 32 or 64-bit immediates that can be loaded either using a
5008 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5009 // (M) or 64-bit 0x1234000000000000 (N) etc.
5010 // As a note some of this code is liberally stolen from the asm parser.
5011 case 'M': {
5012 if (!isUInt<32>(CVal))
5013 return;
5014 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5015 break;
5016 if ((CVal & 0xFFFF) == CVal)
5017 break;
5018 if ((CVal & 0xFFFF0000ULL) == CVal)
5019 break;
5020 uint64_t NCVal = ~(uint32_t)CVal;
5021 if ((NCVal & 0xFFFFULL) == NCVal)
5022 break;
5023 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5024 break;
5025 return;
5026 }
5027 case 'N': {
5028 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5029 break;
5030 if ((CVal & 0xFFFFULL) == CVal)
5031 break;
5032 if ((CVal & 0xFFFF0000ULL) == CVal)
5033 break;
5034 if ((CVal & 0xFFFF00000000ULL) == CVal)
5035 break;
5036 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5037 break;
5038 uint64_t NCVal = ~CVal;
5039 if ((NCVal & 0xFFFFULL) == NCVal)
5040 break;
5041 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5042 break;
5043 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5044 break;
5045 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5046 break;
5047 return;
5048 }
5049 default:
5050 return;
5051 }
5052
5053 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005054 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005055 break;
5056 }
5057
5058 if (Result.getNode()) {
5059 Ops.push_back(Result);
5060 return;
5061 }
5062
5063 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5064}
5065
5066//===----------------------------------------------------------------------===//
5067// AArch64 Advanced SIMD Support
5068//===----------------------------------------------------------------------===//
5069
5070/// WidenVector - Given a value in the V64 register class, produce the
5071/// equivalent value in the V128 register class.
5072static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5073 EVT VT = V64Reg.getValueType();
5074 unsigned NarrowSize = VT.getVectorNumElements();
5075 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5076 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5077 SDLoc DL(V64Reg);
5078
5079 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005080 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005081}
5082
5083/// getExtFactor - Determine the adjustment factor for the position when
5084/// generating an "extract from vector registers" instruction.
5085static unsigned getExtFactor(SDValue &V) {
5086 EVT EltType = V.getValueType().getVectorElementType();
5087 return EltType.getSizeInBits() / 8;
5088}
5089
5090/// NarrowVector - Given a value in the V128 register class, produce the
5091/// equivalent value in the V64 register class.
5092static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5093 EVT VT = V128Reg.getValueType();
5094 unsigned WideSize = VT.getVectorNumElements();
5095 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5096 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5097 SDLoc DL(V128Reg);
5098
5099 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5100}
5101
5102// Gather data to see if the operation can be modelled as a
5103// shuffle in combination with VEXTs.
5104SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5105 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005106 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005107 SDLoc dl(Op);
5108 EVT VT = Op.getValueType();
5109 unsigned NumElts = VT.getVectorNumElements();
5110
Tim Northover7324e842014-07-24 15:39:55 +00005111 struct ShuffleSourceInfo {
5112 SDValue Vec;
5113 unsigned MinElt;
5114 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005115
Tim Northover7324e842014-07-24 15:39:55 +00005116 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5117 // be compatible with the shuffle we intend to construct. As a result
5118 // ShuffleVec will be some sliding window into the original Vec.
5119 SDValue ShuffleVec;
5120
5121 // Code should guarantee that element i in Vec starts at element "WindowBase
5122 // + i * WindowScale in ShuffleVec".
5123 int WindowBase;
5124 int WindowScale;
5125
Tim Northover7324e842014-07-24 15:39:55 +00005126 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005127 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5128 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5129
5130 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005131 };
5132
5133 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5134 // node.
5135 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005136 for (unsigned i = 0; i < NumElts; ++i) {
5137 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005138 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005139 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005140 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5141 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005142 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005143 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00005144 return SDValue();
5145 }
5146
Tim Northover7324e842014-07-24 15:39:55 +00005147 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005148 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005149 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005150 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005151 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005152
Tim Northover7324e842014-07-24 15:39:55 +00005153 // Update the minimum and maximum lane number seen.
5154 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5155 Source->MinElt = std::min(Source->MinElt, EltNo);
5156 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005157 }
5158
5159 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00005160 // are involved.
5161 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00005162 return SDValue();
5163
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005164 // Find out the smallest element size among result and two sources, and use
5165 // it as element size to build the shuffle_vector.
5166 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005167 for (auto &Source : Sources) {
5168 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005169 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5170 SmallestEltTy = SrcEltTy;
5171 }
5172 }
5173 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005174 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005175 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5176 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005177
Tim Northover7324e842014-07-24 15:39:55 +00005178 // If the source vector is too wide or too narrow, we may nevertheless be able
5179 // to construct a compatible shuffle either by concatenating it with UNDEF or
5180 // extracting a suitable range of elements.
5181 for (auto &Src : Sources) {
5182 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005183
Tim Northover7324e842014-07-24 15:39:55 +00005184 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005185 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005186
5187 // This stage of the search produces a source with the same element type as
5188 // the original, but with a total width matching the BUILD_VECTOR output.
5189 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005190 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5191 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005192
5193 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5194 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005195 // We can pad out the smaller vector for free, so if it's part of a
5196 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005197 Src.ShuffleVec =
5198 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5199 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005200 continue;
5201 }
5202
Tim Northover7324e842014-07-24 15:39:55 +00005203 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005204
James Molloyf497d552014-10-17 17:06:31 +00005205 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005206 // Span too large for a VEXT to cope
5207 return SDValue();
5208 }
5209
James Molloyf497d552014-10-17 17:06:31 +00005210 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005211 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005212 Src.ShuffleVec =
5213 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005214 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005215 Src.WindowBase = -NumSrcElts;
5216 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005217 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005218 Src.ShuffleVec =
5219 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005220 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005221 } else {
5222 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005223 SDValue VEXTSrc1 =
5224 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005225 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005226 SDValue VEXTSrc2 =
5227 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005228 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005229 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5230
5231 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005232 VEXTSrc2,
5233 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005234 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005235 }
5236 }
5237
Tim Northover7324e842014-07-24 15:39:55 +00005238 // Another possible incompatibility occurs from the vector element types. We
5239 // can fix this by bitcasting the source vectors to the same type we intend
5240 // for the shuffle.
5241 for (auto &Src : Sources) {
5242 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5243 if (SrcEltTy == SmallestEltTy)
5244 continue;
5245 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5246 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5247 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5248 Src.WindowBase *= Src.WindowScale;
5249 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005250
Tim Northover7324e842014-07-24 15:39:55 +00005251 // Final sanity check before we try to actually produce a shuffle.
5252 DEBUG(
5253 for (auto Src : Sources)
5254 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5255 );
5256
5257 // The stars all align, our next step is to produce the mask for the shuffle.
5258 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005259 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005260 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005261 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005262 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005263 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005264
David Majnemer0d955d02016-08-11 22:21:41 +00005265 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005266 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5267
5268 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5269 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5270 // segment.
5271 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005272 int BitsDefined =
5273 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00005274 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5275
5276 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5277 // starting at the appropriate offset.
5278 int *LaneMask = &Mask[i * ResMultiplier];
5279
5280 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5281 ExtractBase += NumElts * (Src - Sources.begin());
5282 for (int j = 0; j < LanesDefined; ++j)
5283 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005284 }
5285
5286 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005287 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5288 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005289
Tim Northover7324e842014-07-24 15:39:55 +00005290 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5291 for (unsigned i = 0; i < Sources.size(); ++i)
5292 ShuffleOps[i] = Sources[i].ShuffleVec;
5293
5294 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005295 ShuffleOps[1], Mask);
Tim Northover7324e842014-07-24 15:39:55 +00005296 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005297}
5298
5299// check if an EXT instruction can handle the shuffle mask when the
5300// vector sources of the shuffle are the same.
5301static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5302 unsigned NumElts = VT.getVectorNumElements();
5303
5304 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5305 if (M[0] < 0)
5306 return false;
5307
5308 Imm = M[0];
5309
5310 // If this is a VEXT shuffle, the immediate value is the index of the first
5311 // element. The other shuffle indices must be the successive elements after
5312 // the first one.
5313 unsigned ExpectedElt = Imm;
5314 for (unsigned i = 1; i < NumElts; ++i) {
5315 // Increment the expected index. If it wraps around, just follow it
5316 // back to index zero and keep going.
5317 ++ExpectedElt;
5318 if (ExpectedElt == NumElts)
5319 ExpectedElt = 0;
5320
5321 if (M[i] < 0)
5322 continue; // ignore UNDEF indices
5323 if (ExpectedElt != static_cast<unsigned>(M[i]))
5324 return false;
5325 }
5326
5327 return true;
5328}
5329
5330// check if an EXT instruction can handle the shuffle mask when the
5331// vector sources of the shuffle are different.
5332static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5333 unsigned &Imm) {
5334 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005335 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005336
5337 // Benefit form APInt to handle overflow when calculating expected element.
5338 unsigned NumElts = VT.getVectorNumElements();
5339 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5340 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5341 // The following shuffle indices must be the successive elements after the
5342 // first real element.
5343 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5344 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5345 if (FirstWrongElt != M.end())
5346 return false;
5347
5348 // The index of an EXT is the first element if it is not UNDEF.
5349 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005350 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005351 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5352 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5353 // ExpectedElt is the last mask index plus 1.
5354 Imm = ExpectedElt.getZExtValue();
5355
5356 // There are two difference cases requiring to reverse input vectors.
5357 // For example, for vector <4 x i32> we have the following cases,
5358 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5359 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5360 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5361 // to reverse two input vectors.
5362 if (Imm < NumElts)
5363 ReverseEXT = true;
5364 else
5365 Imm -= NumElts;
5366
5367 return true;
5368}
5369
5370/// isREVMask - Check if a vector shuffle corresponds to a REV
5371/// instruction with the specified blocksize. (The order of the elements
5372/// within each block of the vector is reversed.)
5373static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5374 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5375 "Only possible block sizes for REV are: 16, 32, 64");
5376
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005377 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00005378 if (EltSz == 64)
5379 return false;
5380
5381 unsigned NumElts = VT.getVectorNumElements();
5382 unsigned BlockElts = M[0] + 1;
5383 // If the first shuffle index is UNDEF, be optimistic.
5384 if (M[0] < 0)
5385 BlockElts = BlockSize / EltSz;
5386
5387 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5388 return false;
5389
5390 for (unsigned i = 0; i < NumElts; ++i) {
5391 if (M[i] < 0)
5392 continue; // ignore UNDEF indices
5393 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5394 return false;
5395 }
5396
5397 return true;
5398}
5399
5400static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5401 unsigned NumElts = VT.getVectorNumElements();
5402 WhichResult = (M[0] == 0 ? 0 : 1);
5403 unsigned Idx = WhichResult * NumElts / 2;
5404 for (unsigned i = 0; i != NumElts; i += 2) {
5405 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5406 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5407 return false;
5408 Idx += 1;
5409 }
5410
5411 return true;
5412}
5413
5414static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5415 unsigned NumElts = VT.getVectorNumElements();
5416 WhichResult = (M[0] == 0 ? 0 : 1);
5417 for (unsigned i = 0; i != NumElts; ++i) {
5418 if (M[i] < 0)
5419 continue; // ignore UNDEF indices
5420 if ((unsigned)M[i] != 2 * i + WhichResult)
5421 return false;
5422 }
5423
5424 return true;
5425}
5426
5427static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5428 unsigned NumElts = VT.getVectorNumElements();
5429 WhichResult = (M[0] == 0 ? 0 : 1);
5430 for (unsigned i = 0; i < NumElts; i += 2) {
5431 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5432 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5433 return false;
5434 }
5435 return true;
5436}
5437
5438/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5439/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5440/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5441static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5442 unsigned NumElts = VT.getVectorNumElements();
5443 WhichResult = (M[0] == 0 ? 0 : 1);
5444 unsigned Idx = WhichResult * NumElts / 2;
5445 for (unsigned i = 0; i != NumElts; i += 2) {
5446 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5447 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5448 return false;
5449 Idx += 1;
5450 }
5451
5452 return true;
5453}
5454
5455/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5456/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5457/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5458static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5459 unsigned Half = VT.getVectorNumElements() / 2;
5460 WhichResult = (M[0] == 0 ? 0 : 1);
5461 for (unsigned j = 0; j != 2; ++j) {
5462 unsigned Idx = WhichResult;
5463 for (unsigned i = 0; i != Half; ++i) {
5464 int MIdx = M[i + j * Half];
5465 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5466 return false;
5467 Idx += 2;
5468 }
5469 }
5470
5471 return true;
5472}
5473
5474/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5475/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5476/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5477static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5478 unsigned NumElts = VT.getVectorNumElements();
5479 WhichResult = (M[0] == 0 ? 0 : 1);
5480 for (unsigned i = 0; i < NumElts; i += 2) {
5481 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5482 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5483 return false;
5484 }
5485 return true;
5486}
5487
5488static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5489 bool &DstIsLeft, int &Anomaly) {
5490 if (M.size() != static_cast<size_t>(NumInputElements))
5491 return false;
5492
5493 int NumLHSMatch = 0, NumRHSMatch = 0;
5494 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5495
5496 for (int i = 0; i < NumInputElements; ++i) {
5497 if (M[i] == -1) {
5498 ++NumLHSMatch;
5499 ++NumRHSMatch;
5500 continue;
5501 }
5502
5503 if (M[i] == i)
5504 ++NumLHSMatch;
5505 else
5506 LastLHSMismatch = i;
5507
5508 if (M[i] == i + NumInputElements)
5509 ++NumRHSMatch;
5510 else
5511 LastRHSMismatch = i;
5512 }
5513
5514 if (NumLHSMatch == NumInputElements - 1) {
5515 DstIsLeft = true;
5516 Anomaly = LastLHSMismatch;
5517 return true;
5518 } else if (NumRHSMatch == NumInputElements - 1) {
5519 DstIsLeft = false;
5520 Anomaly = LastRHSMismatch;
5521 return true;
5522 }
5523
5524 return false;
5525}
5526
5527static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5528 if (VT.getSizeInBits() != 128)
5529 return false;
5530
5531 unsigned NumElts = VT.getVectorNumElements();
5532
5533 for (int I = 0, E = NumElts / 2; I != E; I++) {
5534 if (Mask[I] != I)
5535 return false;
5536 }
5537
5538 int Offset = NumElts / 2;
5539 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5540 if (Mask[I] != I + SplitLHS * Offset)
5541 return false;
5542 }
5543
5544 return true;
5545}
5546
5547static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5548 SDLoc DL(Op);
5549 EVT VT = Op.getValueType();
5550 SDValue V0 = Op.getOperand(0);
5551 SDValue V1 = Op.getOperand(1);
5552 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5553
5554 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5555 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5556 return SDValue();
5557
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005558 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00005559
5560 if (!isConcatMask(Mask, VT, SplitV0))
5561 return SDValue();
5562
5563 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5564 VT.getVectorNumElements() / 2);
5565 if (SplitV0) {
5566 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005567 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005568 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005569 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005570 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005571 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005572 }
5573 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5574}
5575
5576/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5577/// the specified operations to build the shuffle.
5578static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5579 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005580 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005581 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5582 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5583 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5584
5585 enum {
5586 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5587 OP_VREV,
5588 OP_VDUP0,
5589 OP_VDUP1,
5590 OP_VDUP2,
5591 OP_VDUP3,
5592 OP_VEXT1,
5593 OP_VEXT2,
5594 OP_VEXT3,
5595 OP_VUZPL, // VUZP, left result
5596 OP_VUZPR, // VUZP, right result
5597 OP_VZIPL, // VZIP, left result
5598 OP_VZIPR, // VZIP, right result
5599 OP_VTRNL, // VTRN, left result
5600 OP_VTRNR // VTRN, right result
5601 };
5602
5603 if (OpNum == OP_COPY) {
5604 if (LHSID == (1 * 9 + 2) * 9 + 3)
5605 return LHS;
5606 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5607 return RHS;
5608 }
5609
5610 SDValue OpLHS, OpRHS;
5611 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5612 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5613 EVT VT = OpLHS.getValueType();
5614
5615 switch (OpNum) {
5616 default:
5617 llvm_unreachable("Unknown shuffle opcode!");
5618 case OP_VREV:
5619 // VREV divides the vector in half and swaps within the half.
5620 if (VT.getVectorElementType() == MVT::i32 ||
5621 VT.getVectorElementType() == MVT::f32)
5622 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5623 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005624 if (VT.getVectorElementType() == MVT::i16 ||
5625 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005626 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5627 // vrev <4 x i8> -> REV16
5628 assert(VT.getVectorElementType() == MVT::i8);
5629 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5630 case OP_VDUP0:
5631 case OP_VDUP1:
5632 case OP_VDUP2:
5633 case OP_VDUP3: {
5634 EVT EltTy = VT.getVectorElementType();
5635 unsigned Opcode;
5636 if (EltTy == MVT::i8)
5637 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005638 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005639 Opcode = AArch64ISD::DUPLANE16;
5640 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5641 Opcode = AArch64ISD::DUPLANE32;
5642 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5643 Opcode = AArch64ISD::DUPLANE64;
5644 else
5645 llvm_unreachable("Invalid vector element type?");
5646
5647 if (VT.getSizeInBits() == 64)
5648 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005649 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005650 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5651 }
5652 case OP_VEXT1:
5653 case OP_VEXT2:
5654 case OP_VEXT3: {
5655 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5656 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005657 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005658 }
5659 case OP_VUZPL:
5660 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5661 OpRHS);
5662 case OP_VUZPR:
5663 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5664 OpRHS);
5665 case OP_VZIPL:
5666 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5667 OpRHS);
5668 case OP_VZIPR:
5669 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5670 OpRHS);
5671 case OP_VTRNL:
5672 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5673 OpRHS);
5674 case OP_VTRNR:
5675 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5676 OpRHS);
5677 }
5678}
5679
5680static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5681 SelectionDAG &DAG) {
5682 // Check to see if we can use the TBL instruction.
5683 SDValue V1 = Op.getOperand(0);
5684 SDValue V2 = Op.getOperand(1);
5685 SDLoc DL(Op);
5686
5687 EVT EltVT = Op.getValueType().getVectorElementType();
5688 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5689
5690 SmallVector<SDValue, 8> TBLMask;
5691 for (int Val : ShuffleMask) {
5692 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5693 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005694 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005695 }
5696 }
5697
5698 MVT IndexVT = MVT::v8i8;
5699 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005700 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005701 IndexVT = MVT::v16i8;
5702 IndexLen = 16;
5703 }
5704
5705 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5706 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5707
5708 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005709 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005710 if (IndexLen == 8)
5711 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5712 Shuffle = DAG.getNode(
5713 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005714 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005715 DAG.getBuildVector(IndexVT, DL,
5716 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005717 } else {
5718 if (IndexLen == 8) {
5719 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5720 Shuffle = DAG.getNode(
5721 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005722 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005723 DAG.getBuildVector(IndexVT, DL,
5724 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005725 } else {
5726 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5727 // cannot currently represent the register constraints on the input
5728 // table registers.
5729 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005730 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5731 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00005732 Shuffle = DAG.getNode(
5733 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005734 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5735 V2Cst, DAG.getBuildVector(IndexVT, DL,
5736 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005737 }
5738 }
5739 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5740}
5741
5742static unsigned getDUPLANEOp(EVT EltType) {
5743 if (EltType == MVT::i8)
5744 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005745 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005746 return AArch64ISD::DUPLANE16;
5747 if (EltType == MVT::i32 || EltType == MVT::f32)
5748 return AArch64ISD::DUPLANE32;
5749 if (EltType == MVT::i64 || EltType == MVT::f64)
5750 return AArch64ISD::DUPLANE64;
5751
5752 llvm_unreachable("Invalid vector element type?");
5753}
5754
5755SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5756 SelectionDAG &DAG) const {
5757 SDLoc dl(Op);
5758 EVT VT = Op.getValueType();
5759
5760 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5761
5762 // Convert shuffles that are directly supported on NEON to target-specific
5763 // DAG nodes, instead of keeping them as shuffles and matching them again
5764 // during code selection. This is more efficient and avoids the possibility
5765 // of inconsistencies between legalization and selection.
5766 ArrayRef<int> ShuffleMask = SVN->getMask();
5767
5768 SDValue V1 = Op.getOperand(0);
5769 SDValue V2 = Op.getOperand(1);
5770
Craig Topperbc56e3b2016-06-30 04:38:51 +00005771 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005772 int Lane = SVN->getSplatIndex();
5773 // If this is undef splat, generate it via "just" vdup, if possible.
5774 if (Lane == -1)
5775 Lane = 0;
5776
5777 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5778 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5779 V1.getOperand(0));
5780 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5781 // constant. If so, we can just reference the lane's definition directly.
5782 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5783 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5784 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5785
5786 // Otherwise, duplicate from the lane of the input vector.
5787 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5788
5789 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5790 // to make a vector of the same size as this SHUFFLE. We can ignore the
5791 // extract entirely, and canonicalise the concat using WidenVector.
5792 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5793 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5794 V1 = V1.getOperand(0);
5795 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5796 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5797 Lane -= Idx * VT.getVectorNumElements() / 2;
5798 V1 = WidenVector(V1.getOperand(Idx), DAG);
5799 } else if (VT.getSizeInBits() == 64)
5800 V1 = WidenVector(V1, DAG);
5801
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005802 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005803 }
5804
5805 if (isREVMask(ShuffleMask, VT, 64))
5806 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5807 if (isREVMask(ShuffleMask, VT, 32))
5808 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5809 if (isREVMask(ShuffleMask, VT, 16))
5810 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5811
5812 bool ReverseEXT = false;
5813 unsigned Imm;
5814 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5815 if (ReverseEXT)
5816 std::swap(V1, V2);
5817 Imm *= getExtFactor(V1);
5818 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005819 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00005820 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005821 Imm *= getExtFactor(V1);
5822 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005823 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005824 }
5825
5826 unsigned WhichResult;
5827 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5828 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5829 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5830 }
5831 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5832 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5833 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5834 }
5835 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5836 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5837 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5838 }
5839
5840 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5841 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5842 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5843 }
5844 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5845 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5846 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5847 }
5848 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5849 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5850 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5851 }
5852
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005853 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005854 return Concat;
5855
5856 bool DstIsLeft;
5857 int Anomaly;
5858 int NumInputElements = V1.getValueType().getVectorNumElements();
5859 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5860 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005861 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005862
5863 SDValue SrcVec = V1;
5864 int SrcLane = ShuffleMask[Anomaly];
5865 if (SrcLane >= NumInputElements) {
5866 SrcVec = V2;
5867 SrcLane -= VT.getVectorNumElements();
5868 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005869 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005870
5871 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005872
5873 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005874 ScalarVT = MVT::i32;
5875
5876 return DAG.getNode(
5877 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5878 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5879 DstLaneV);
5880 }
5881
5882 // If the shuffle is not directly supported and it has 4 elements, use
5883 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5884 unsigned NumElts = VT.getVectorNumElements();
5885 if (NumElts == 4) {
5886 unsigned PFIndexes[4];
5887 for (unsigned i = 0; i != 4; ++i) {
5888 if (ShuffleMask[i] < 0)
5889 PFIndexes[i] = 8;
5890 else
5891 PFIndexes[i] = ShuffleMask[i];
5892 }
5893
5894 // Compute the index in the perfect shuffle table.
5895 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5896 PFIndexes[2] * 9 + PFIndexes[3];
5897 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5898 unsigned Cost = (PFEntry >> 30);
5899
5900 if (Cost <= 4)
5901 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5902 }
5903
5904 return GenerateTBL(Op, ShuffleMask, DAG);
5905}
5906
5907static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5908 APInt &UndefBits) {
5909 EVT VT = BVN->getValueType(0);
5910 APInt SplatBits, SplatUndef;
5911 unsigned SplatBitSize;
5912 bool HasAnyUndefs;
5913 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5914 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5915
5916 for (unsigned i = 0; i < NumSplats; ++i) {
5917 CnstBits <<= SplatBitSize;
5918 UndefBits <<= SplatBitSize;
5919 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5920 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5921 }
5922
5923 return true;
5924 }
5925
5926 return false;
5927}
5928
5929SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5930 SelectionDAG &DAG) const {
5931 BuildVectorSDNode *BVN =
5932 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5933 SDValue LHS = Op.getOperand(0);
5934 SDLoc dl(Op);
5935 EVT VT = Op.getValueType();
5936
5937 if (!BVN)
5938 return Op;
5939
5940 APInt CnstBits(VT.getSizeInBits(), 0);
5941 APInt UndefBits(VT.getSizeInBits(), 0);
5942 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5943 // We only have BIC vector immediate instruction, which is and-not.
5944 CnstBits = ~CnstBits;
5945
5946 // We make use of a little bit of goto ickiness in order to avoid having to
5947 // duplicate the immediate matching logic for the undef toggled case.
5948 bool SecondTry = false;
5949 AttemptModImm:
5950
5951 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5952 CnstBits = CnstBits.zextOrTrunc(64);
5953 uint64_t CnstVal = CnstBits.getZExtValue();
5954
5955 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5956 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5957 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5958 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005959 DAG.getConstant(CnstVal, dl, MVT::i32),
5960 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005961 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005962 }
5963
5964 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5965 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5966 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5967 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005968 DAG.getConstant(CnstVal, dl, MVT::i32),
5969 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005970 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005971 }
5972
5973 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5974 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5975 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5976 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005977 DAG.getConstant(CnstVal, dl, MVT::i32),
5978 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005979 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005980 }
5981
5982 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5983 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5984 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5985 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005986 DAG.getConstant(CnstVal, dl, MVT::i32),
5987 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005988 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005989 }
5990
5991 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5992 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5993 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5994 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005995 DAG.getConstant(CnstVal, dl, MVT::i32),
5996 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005997 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005998 }
5999
6000 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6001 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6002 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6003 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006004 DAG.getConstant(CnstVal, dl, MVT::i32),
6005 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006006 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006007 }
6008 }
6009
6010 if (SecondTry)
6011 goto FailedModImm;
6012 SecondTry = true;
6013 CnstBits = ~UndefBits;
6014 goto AttemptModImm;
6015 }
6016
6017// We can always fall back to a non-immediate AND.
6018FailedModImm:
6019 return Op;
6020}
6021
6022// Specialized code to quickly find if PotentialBVec is a BuildVector that
6023// consists of only the same constant int value, returned in reference arg
6024// ConstVal
6025static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6026 uint64_t &ConstVal) {
6027 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6028 if (!Bvec)
6029 return false;
6030 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6031 if (!FirstElt)
6032 return false;
6033 EVT VT = Bvec->getValueType(0);
6034 unsigned NumElts = VT.getVectorNumElements();
6035 for (unsigned i = 1; i < NumElts; ++i)
6036 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6037 return false;
6038 ConstVal = FirstElt->getZExtValue();
6039 return true;
6040}
6041
6042static unsigned getIntrinsicID(const SDNode *N) {
6043 unsigned Opcode = N->getOpcode();
6044 switch (Opcode) {
6045 default:
6046 return Intrinsic::not_intrinsic;
6047 case ISD::INTRINSIC_WO_CHAIN: {
6048 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6049 if (IID < Intrinsic::num_intrinsics)
6050 return IID;
6051 return Intrinsic::not_intrinsic;
6052 }
6053 }
6054}
6055
6056// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6057// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6058// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6059// Also, logical shift right -> sri, with the same structure.
6060static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6061 EVT VT = N->getValueType(0);
6062
6063 if (!VT.isVector())
6064 return SDValue();
6065
6066 SDLoc DL(N);
6067
6068 // Is the first op an AND?
6069 const SDValue And = N->getOperand(0);
6070 if (And.getOpcode() != ISD::AND)
6071 return SDValue();
6072
6073 // Is the second op an shl or lshr?
6074 SDValue Shift = N->getOperand(1);
6075 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6076 // or AArch64ISD::VLSHR vector, #shift
6077 unsigned ShiftOpc = Shift.getOpcode();
6078 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6079 return SDValue();
6080 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6081
6082 // Is the shift amount constant?
6083 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6084 if (!C2node)
6085 return SDValue();
6086
6087 // Is the and mask vector all constant?
6088 uint64_t C1;
6089 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6090 return SDValue();
6091
6092 // Is C1 == ~C2, taking into account how much one can shift elements of a
6093 // particular size?
6094 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006095 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006096 if (C2 > ElemSizeInBits)
6097 return SDValue();
6098 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6099 if ((C1 & ElemMask) != (~C2 & ElemMask))
6100 return SDValue();
6101
6102 SDValue X = And.getOperand(0);
6103 SDValue Y = Shift.getOperand(0);
6104
6105 unsigned Intrin =
6106 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6107 SDValue ResultSLI =
6108 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006109 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6110 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00006111
6112 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6113 DEBUG(N->dump(&DAG));
6114 DEBUG(dbgs() << "into: \n");
6115 DEBUG(ResultSLI->dump(&DAG));
6116
6117 ++NumShiftInserts;
6118 return ResultSLI;
6119}
6120
6121SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6122 SelectionDAG &DAG) const {
6123 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6124 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006125 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006126 return Res;
6127 }
6128
6129 BuildVectorSDNode *BVN =
6130 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6131 SDValue LHS = Op.getOperand(1);
6132 SDLoc dl(Op);
6133 EVT VT = Op.getValueType();
6134
6135 // OR commutes, so try swapping the operands.
6136 if (!BVN) {
6137 LHS = Op.getOperand(0);
6138 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6139 }
6140 if (!BVN)
6141 return Op;
6142
6143 APInt CnstBits(VT.getSizeInBits(), 0);
6144 APInt UndefBits(VT.getSizeInBits(), 0);
6145 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6146 // We make use of a little bit of goto ickiness in order to avoid having to
6147 // duplicate the immediate matching logic for the undef toggled case.
6148 bool SecondTry = false;
6149 AttemptModImm:
6150
6151 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6152 CnstBits = CnstBits.zextOrTrunc(64);
6153 uint64_t CnstVal = CnstBits.getZExtValue();
6154
6155 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6156 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6157 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6158 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006159 DAG.getConstant(CnstVal, dl, MVT::i32),
6160 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006161 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006162 }
6163
6164 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6165 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6166 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6167 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006168 DAG.getConstant(CnstVal, dl, MVT::i32),
6169 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006170 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006171 }
6172
6173 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6174 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6175 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6176 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006177 DAG.getConstant(CnstVal, dl, MVT::i32),
6178 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006179 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006180 }
6181
6182 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6183 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6184 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6185 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006186 DAG.getConstant(CnstVal, dl, MVT::i32),
6187 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006188 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006189 }
6190
6191 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6192 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6193 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6194 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006195 DAG.getConstant(CnstVal, dl, MVT::i32),
6196 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006197 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006198 }
6199
6200 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6201 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6202 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6203 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006204 DAG.getConstant(CnstVal, dl, MVT::i32),
6205 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006206 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006207 }
6208 }
6209
6210 if (SecondTry)
6211 goto FailedModImm;
6212 SecondTry = true;
6213 CnstBits = UndefBits;
6214 goto AttemptModImm;
6215 }
6216
6217// We can always fall back to a non-immediate OR.
6218FailedModImm:
6219 return Op;
6220}
6221
Kevin Qin4473c192014-07-07 02:45:40 +00006222// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6223// be truncated to fit element width.
6224static SDValue NormalizeBuildVector(SDValue Op,
6225 SelectionDAG &DAG) {
6226 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006227 SDLoc dl(Op);
6228 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006229 EVT EltTy= VT.getVectorElementType();
6230
6231 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6232 return Op;
6233
6234 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006235 for (SDValue Lane : Op->ops()) {
6236 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006237 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006238 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006239 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006240 }
6241 Ops.push_back(Lane);
6242 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006243 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006244}
6245
6246SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6247 SelectionDAG &DAG) const {
6248 SDLoc dl(Op);
6249 EVT VT = Op.getValueType();
6250 Op = NormalizeBuildVector(Op, DAG);
6251 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006252
6253 APInt CnstBits(VT.getSizeInBits(), 0);
6254 APInt UndefBits(VT.getSizeInBits(), 0);
6255 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6256 // We make use of a little bit of goto ickiness in order to avoid having to
6257 // duplicate the immediate matching logic for the undef toggled case.
6258 bool SecondTry = false;
6259 AttemptModImm:
6260
6261 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6262 CnstBits = CnstBits.zextOrTrunc(64);
6263 uint64_t CnstVal = CnstBits.getZExtValue();
6264
6265 // Certain magic vector constants (used to express things like NOT
6266 // and NEG) are passed through unmodified. This allows codegen patterns
6267 // for these operations to match. Special-purpose patterns will lower
6268 // these immediates to MOVIs if it proves necessary.
6269 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6270 return Op;
6271
6272 // The many faces of MOVI...
6273 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6274 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6275 if (VT.getSizeInBits() == 128) {
6276 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006277 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006278 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006279 }
6280
6281 // Support the V64 version via subregister insertion.
6282 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006283 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006284 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006285 }
6286
6287 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6288 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6289 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6290 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006291 DAG.getConstant(CnstVal, dl, MVT::i32),
6292 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006293 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006294 }
6295
6296 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6297 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6298 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6299 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006300 DAG.getConstant(CnstVal, dl, MVT::i32),
6301 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006302 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006303 }
6304
6305 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6306 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6307 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6308 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006309 DAG.getConstant(CnstVal, dl, MVT::i32),
6310 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006311 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006312 }
6313
6314 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6315 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6316 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6317 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006318 DAG.getConstant(CnstVal, dl, MVT::i32),
6319 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006320 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006321 }
6322
6323 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6324 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6325 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6326 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006327 DAG.getConstant(CnstVal, dl, MVT::i32),
6328 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006329 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006330 }
6331
6332 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6333 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6334 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6335 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006336 DAG.getConstant(CnstVal, dl, MVT::i32),
6337 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006338 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006339 }
6340
6341 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6342 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6343 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6344 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006345 DAG.getConstant(CnstVal, dl, MVT::i32),
6346 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006347 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006348 }
6349
6350 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6351 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6352 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6353 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006354 DAG.getConstant(CnstVal, dl, MVT::i32),
6355 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006356 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006357 }
6358
6359 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6360 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6361 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6362 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006363 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006364 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006365 }
6366
6367 // The few faces of FMOV...
6368 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6369 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6370 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6371 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006372 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006373 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006374 }
6375
6376 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6377 VT.getSizeInBits() == 128) {
6378 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6379 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006380 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006381 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006382 }
6383
6384 // The many faces of MVNI...
6385 CnstVal = ~CnstVal;
6386 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6387 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6388 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6389 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006390 DAG.getConstant(CnstVal, dl, MVT::i32),
6391 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006392 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006393 }
6394
6395 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6396 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6397 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6398 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006399 DAG.getConstant(CnstVal, dl, MVT::i32),
6400 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006401 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006402 }
6403
6404 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6405 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6406 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6407 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006408 DAG.getConstant(CnstVal, dl, MVT::i32),
6409 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006410 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006411 }
6412
6413 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6414 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6415 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6416 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006417 DAG.getConstant(CnstVal, dl, MVT::i32),
6418 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006419 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006420 }
6421
6422 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6423 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6424 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6425 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006426 DAG.getConstant(CnstVal, dl, MVT::i32),
6427 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006428 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006429 }
6430
6431 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6432 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6433 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6434 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006435 DAG.getConstant(CnstVal, dl, MVT::i32),
6436 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006437 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006438 }
6439
6440 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6441 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6442 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6443 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006444 DAG.getConstant(CnstVal, dl, MVT::i32),
6445 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006446 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006447 }
6448
6449 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6450 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6451 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6452 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006453 DAG.getConstant(CnstVal, dl, MVT::i32),
6454 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006455 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006456 }
6457 }
6458
6459 if (SecondTry)
6460 goto FailedModImm;
6461 SecondTry = true;
6462 CnstBits = UndefBits;
6463 goto AttemptModImm;
6464 }
6465FailedModImm:
6466
6467 // Scan through the operands to find some interesting properties we can
6468 // exploit:
6469 // 1) If only one value is used, we can use a DUP, or
6470 // 2) if only the low element is not undef, we can just insert that, or
6471 // 3) if only one constant value is used (w/ some non-constant lanes),
6472 // we can splat the constant value into the whole vector then fill
6473 // in the non-constant lanes.
6474 // 4) FIXME: If different constant values are used, but we can intelligently
6475 // select the values we'll be overwriting for the non-constant
6476 // lanes such that we can directly materialize the vector
6477 // some other way (MOVI, e.g.), we can be sneaky.
6478 unsigned NumElts = VT.getVectorNumElements();
6479 bool isOnlyLowElement = true;
6480 bool usesOnlyOneValue = true;
6481 bool usesOnlyOneConstantValue = true;
6482 bool isConstant = true;
6483 unsigned NumConstantLanes = 0;
6484 SDValue Value;
6485 SDValue ConstantValue;
6486 for (unsigned i = 0; i < NumElts; ++i) {
6487 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006488 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006489 continue;
6490 if (i > 0)
6491 isOnlyLowElement = false;
6492 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6493 isConstant = false;
6494
6495 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6496 ++NumConstantLanes;
6497 if (!ConstantValue.getNode())
6498 ConstantValue = V;
6499 else if (ConstantValue != V)
6500 usesOnlyOneConstantValue = false;
6501 }
6502
6503 if (!Value.getNode())
6504 Value = V;
6505 else if (V != Value)
6506 usesOnlyOneValue = false;
6507 }
6508
6509 if (!Value.getNode())
6510 return DAG.getUNDEF(VT);
6511
6512 if (isOnlyLowElement)
6513 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6514
6515 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6516 // i32 and try again.
6517 if (usesOnlyOneValue) {
6518 if (!isConstant) {
6519 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6520 Value.getValueType() != VT)
6521 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6522
6523 // This is actually a DUPLANExx operation, which keeps everything vectory.
6524
6525 // DUPLANE works on 128-bit vectors, widen it if necessary.
6526 SDValue Lane = Value.getOperand(1);
6527 Value = Value.getOperand(0);
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006528 if (Value.getValueSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006529 Value = WidenVector(Value, DAG);
6530
6531 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6532 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6533 }
6534
6535 if (VT.getVectorElementType().isFloatingPoint()) {
6536 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006537 EVT EltTy = VT.getVectorElementType();
6538 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6539 "Unsupported floating-point vector type");
6540 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006541 for (unsigned i = 0; i < NumElts; ++i)
6542 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6543 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006544 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Tim Northover3b0846e2014-05-24 12:50:23 +00006545 Val = LowerBUILD_VECTOR(Val, DAG);
6546 if (Val.getNode())
6547 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6548 }
6549 }
6550
6551 // If there was only one constant value used and for more than one lane,
6552 // start by splatting that value, then replace the non-constant lanes. This
6553 // is better than the default, which will perform a separate initialization
6554 // for each lane.
6555 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6556 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6557 // Now insert the non-constant lanes.
6558 for (unsigned i = 0; i < NumElts; ++i) {
6559 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006560 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006561 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6562 // Note that type legalization likely mucked about with the VT of the
6563 // source operand, so we may have to convert it here before inserting.
6564 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6565 }
6566 }
6567 return Val;
6568 }
6569
6570 // If all elements are constants and the case above didn't get hit, fall back
6571 // to the default expansion, which will generate a load from the constant
6572 // pool.
6573 if (isConstant)
6574 return SDValue();
6575
6576 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6577 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006578 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006579 return shuffle;
6580 }
6581
6582 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6583 // know the default expansion would otherwise fall back on something even
6584 // worse. For a vector with one or two non-undef values, that's
6585 // scalar_to_vector for the elements followed by a shuffle (provided the
6586 // shuffle is valid for the target) and materialization element by element
6587 // on the stack followed by a load for everything else.
6588 if (!isConstant && !usesOnlyOneValue) {
6589 SDValue Vec = DAG.getUNDEF(VT);
6590 SDValue Op0 = Op.getOperand(0);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006591 unsigned ElemSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006592 unsigned i = 0;
6593 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6594 // a) Avoid a RMW dependency on the full vector register, and
6595 // b) Allow the register coalescer to fold away the copy if the
6596 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006597 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6598 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
Sanjay Patel75068522016-03-14 18:09:43 +00006599 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
Matthias Braun0acbd082015-08-31 18:25:15 +00006600 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006601 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6602 MachineSDNode *N =
6603 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006604 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006605 Vec = SDValue(N, 0);
6606 ++i;
6607 }
6608 for (; i < NumElts; ++i) {
6609 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006610 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006611 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006612 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006613 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6614 }
6615 return Vec;
6616 }
6617
6618 // Just use the default expansion. We failed to find a better alternative.
6619 return SDValue();
6620}
6621
6622SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6623 SelectionDAG &DAG) const {
6624 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6625
Tim Northovere4b8e132014-07-15 10:00:26 +00006626 // Check for non-constant or out of range lane.
6627 EVT VT = Op.getOperand(0).getValueType();
6628 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6629 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006630 return SDValue();
6631
Tim Northover3b0846e2014-05-24 12:50:23 +00006632
6633 // Insertion/extraction are legal for V128 types.
6634 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006635 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6636 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006637 return Op;
6638
6639 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006640 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006641 return SDValue();
6642
6643 // For V64 types, we perform insertion by expanding the value
6644 // to a V128 type and perform the insertion on that.
6645 SDLoc DL(Op);
6646 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6647 EVT WideTy = WideVec.getValueType();
6648
6649 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6650 Op.getOperand(1), Op.getOperand(2));
6651 // Re-narrow the resultant vector.
6652 return NarrowVector(Node, DAG);
6653}
6654
6655SDValue
6656AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6657 SelectionDAG &DAG) const {
6658 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6659
Tim Northovere4b8e132014-07-15 10:00:26 +00006660 // Check for non-constant or out of range lane.
6661 EVT VT = Op.getOperand(0).getValueType();
6662 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6663 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006664 return SDValue();
6665
Tim Northover3b0846e2014-05-24 12:50:23 +00006666
6667 // Insertion/extraction are legal for V128 types.
6668 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006669 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6670 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006671 return Op;
6672
6673 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006674 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006675 return SDValue();
6676
6677 // For V64 types, we perform extraction by expanding the value
6678 // to a V128 type and perform the extraction on that.
6679 SDLoc DL(Op);
6680 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6681 EVT WideTy = WideVec.getValueType();
6682
6683 EVT ExtrTy = WideTy.getVectorElementType();
6684 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6685 ExtrTy = MVT::i32;
6686
6687 // For extractions, we just return the result directly.
6688 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6689 Op.getOperand(1));
6690}
6691
6692SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6693 SelectionDAG &DAG) const {
6694 EVT VT = Op.getOperand(0).getValueType();
6695 SDLoc dl(Op);
6696 // Just in case...
6697 if (!VT.isVector())
6698 return SDValue();
6699
6700 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6701 if (!Cst)
6702 return SDValue();
6703 unsigned Val = Cst->getZExtValue();
6704
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006705 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006706
6707 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6708 if (Val == 0)
6709 return Op;
6710
Tim Northover3b0846e2014-05-24 12:50:23 +00006711 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6712 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006713 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006714 return Op;
6715
6716 return SDValue();
6717}
6718
6719bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6720 EVT VT) const {
6721 if (VT.getVectorNumElements() == 4 &&
6722 (VT.is128BitVector() || VT.is64BitVector())) {
6723 unsigned PFIndexes[4];
6724 for (unsigned i = 0; i != 4; ++i) {
6725 if (M[i] < 0)
6726 PFIndexes[i] = 8;
6727 else
6728 PFIndexes[i] = M[i];
6729 }
6730
6731 // Compute the index in the perfect shuffle table.
6732 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6733 PFIndexes[2] * 9 + PFIndexes[3];
6734 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6735 unsigned Cost = (PFEntry >> 30);
6736
6737 if (Cost <= 4)
6738 return true;
6739 }
6740
6741 bool DummyBool;
6742 int DummyInt;
6743 unsigned DummyUnsigned;
6744
6745 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6746 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6747 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6748 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6749 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6750 isZIPMask(M, VT, DummyUnsigned) ||
6751 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6752 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6753 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6754 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6755 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6756}
6757
6758/// getVShiftImm - Check if this is a valid build_vector for the immediate
6759/// operand of a vector shift operation, where all the elements of the
6760/// build_vector must have the same constant integer value.
6761static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6762 // Ignore bit_converts.
6763 while (Op.getOpcode() == ISD::BITCAST)
6764 Op = Op.getOperand(0);
6765 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6766 APInt SplatBits, SplatUndef;
6767 unsigned SplatBitSize;
6768 bool HasAnyUndefs;
6769 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6770 HasAnyUndefs, ElementBits) ||
6771 SplatBitSize > ElementBits)
6772 return false;
6773 Cnt = SplatBits.getSExtValue();
6774 return true;
6775}
6776
6777/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6778/// operand of a vector shift left operation. That value must be in the range:
6779/// 0 <= Value < ElementBits for a left shift; or
6780/// 0 <= Value <= ElementBits for a long left shift.
6781static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6782 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006783 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006784 if (!getVShiftImm(Op, ElementBits, Cnt))
6785 return false;
6786 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6787}
6788
6789/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006790/// operand of a vector shift right operation. The value must be in the range:
6791/// 1 <= Value <= ElementBits for a right shift; or
6792static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006793 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006794 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006795 if (!getVShiftImm(Op, ElementBits, Cnt))
6796 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006797 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6798}
6799
6800SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6801 SelectionDAG &DAG) const {
6802 EVT VT = Op.getValueType();
6803 SDLoc DL(Op);
6804 int64_t Cnt;
6805
6806 if (!Op.getOperand(1).getValueType().isVector())
6807 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006808 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006809
6810 switch (Op.getOpcode()) {
6811 default:
6812 llvm_unreachable("unexpected shift opcode");
6813
6814 case ISD::SHL:
6815 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006816 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6817 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006818 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006819 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6820 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006821 Op.getOperand(0), Op.getOperand(1));
6822 case ISD::SRA:
6823 case ISD::SRL:
6824 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006825 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006826 unsigned Opc =
6827 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006828 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6829 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006830 }
6831
6832 // Right shift register. Note, there is not a shift right register
6833 // instruction, but the shift left register instruction takes a signed
6834 // value, where negative numbers specify a right shift.
6835 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6836 : Intrinsic::aarch64_neon_ushl;
6837 // negate the shift amount
6838 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6839 SDValue NegShiftLeft =
6840 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006841 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6842 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006843 return NegShiftLeft;
6844 }
6845
6846 return SDValue();
6847}
6848
6849static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6850 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006851 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006852 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006853 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6854 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006855
6856 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6857 APInt CnstBits(VT.getSizeInBits(), 0);
6858 APInt UndefBits(VT.getSizeInBits(), 0);
6859 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6860 bool IsZero = IsCnst && (CnstBits == 0);
6861
6862 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6863 switch (CC) {
6864 default:
6865 return SDValue();
6866 case AArch64CC::NE: {
6867 SDValue Fcmeq;
6868 if (IsZero)
6869 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6870 else
6871 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6872 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6873 }
6874 case AArch64CC::EQ:
6875 if (IsZero)
6876 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6877 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6878 case AArch64CC::GE:
6879 if (IsZero)
6880 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6881 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6882 case AArch64CC::GT:
6883 if (IsZero)
6884 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6885 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6886 case AArch64CC::LS:
6887 if (IsZero)
6888 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6889 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6890 case AArch64CC::LT:
6891 if (!NoNans)
6892 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00006893 // If we ignore NaNs then we can use to the MI implementation.
6894 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00006895 case AArch64CC::MI:
6896 if (IsZero)
6897 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6898 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6899 }
6900 }
6901
6902 switch (CC) {
6903 default:
6904 return SDValue();
6905 case AArch64CC::NE: {
6906 SDValue Cmeq;
6907 if (IsZero)
6908 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6909 else
6910 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6911 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6912 }
6913 case AArch64CC::EQ:
6914 if (IsZero)
6915 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6916 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6917 case AArch64CC::GE:
6918 if (IsZero)
6919 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6920 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6921 case AArch64CC::GT:
6922 if (IsZero)
6923 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6924 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6925 case AArch64CC::LE:
6926 if (IsZero)
6927 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6928 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6929 case AArch64CC::LS:
6930 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6931 case AArch64CC::LO:
6932 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6933 case AArch64CC::LT:
6934 if (IsZero)
6935 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6936 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6937 case AArch64CC::HI:
6938 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6939 case AArch64CC::HS:
6940 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6941 }
6942}
6943
6944SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6945 SelectionDAG &DAG) const {
6946 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6947 SDValue LHS = Op.getOperand(0);
6948 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006949 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006950 SDLoc dl(Op);
6951
6952 if (LHS.getValueType().getVectorElementType().isInteger()) {
6953 assert(LHS.getValueType() == RHS.getValueType());
6954 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006955 SDValue Cmp =
6956 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6957 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006958 }
6959
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006960 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6961 return SDValue();
6962
Tim Northover3b0846e2014-05-24 12:50:23 +00006963 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6964 LHS.getValueType().getVectorElementType() == MVT::f64);
6965
6966 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6967 // clean. Some of them require two branches to implement.
6968 AArch64CC::CondCode CC1, CC2;
6969 bool ShouldInvert;
6970 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6971
6972 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6973 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006974 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006975 if (!Cmp.getNode())
6976 return SDValue();
6977
6978 if (CC2 != AArch64CC::AL) {
6979 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006980 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006981 if (!Cmp2.getNode())
6982 return SDValue();
6983
Tim Northover45aa89c2015-02-08 00:50:47 +00006984 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006985 }
6986
Tim Northover45aa89c2015-02-08 00:50:47 +00006987 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6988
Tim Northover3b0846e2014-05-24 12:50:23 +00006989 if (ShouldInvert)
6990 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6991
6992 return Cmp;
6993}
6994
6995/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6996/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6997/// specified in the intrinsic calls.
6998bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6999 const CallInst &I,
7000 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007001 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007002 switch (Intrinsic) {
7003 case Intrinsic::aarch64_neon_ld2:
7004 case Intrinsic::aarch64_neon_ld3:
7005 case Intrinsic::aarch64_neon_ld4:
7006 case Intrinsic::aarch64_neon_ld1x2:
7007 case Intrinsic::aarch64_neon_ld1x3:
7008 case Intrinsic::aarch64_neon_ld1x4:
7009 case Intrinsic::aarch64_neon_ld2lane:
7010 case Intrinsic::aarch64_neon_ld3lane:
7011 case Intrinsic::aarch64_neon_ld4lane:
7012 case Intrinsic::aarch64_neon_ld2r:
7013 case Intrinsic::aarch64_neon_ld3r:
7014 case Intrinsic::aarch64_neon_ld4r: {
7015 Info.opc = ISD::INTRINSIC_W_CHAIN;
7016 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007017 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007018 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7019 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7020 Info.offset = 0;
7021 Info.align = 0;
7022 Info.vol = false; // volatile loads with NEON intrinsics not supported
7023 Info.readMem = true;
7024 Info.writeMem = false;
7025 return true;
7026 }
7027 case Intrinsic::aarch64_neon_st2:
7028 case Intrinsic::aarch64_neon_st3:
7029 case Intrinsic::aarch64_neon_st4:
7030 case Intrinsic::aarch64_neon_st1x2:
7031 case Intrinsic::aarch64_neon_st1x3:
7032 case Intrinsic::aarch64_neon_st1x4:
7033 case Intrinsic::aarch64_neon_st2lane:
7034 case Intrinsic::aarch64_neon_st3lane:
7035 case Intrinsic::aarch64_neon_st4lane: {
7036 Info.opc = ISD::INTRINSIC_VOID;
7037 // Conservatively set memVT to the entire set of vectors stored.
7038 unsigned NumElts = 0;
7039 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7040 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7041 if (!ArgTy->isVectorTy())
7042 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007043 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007044 }
7045 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7046 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7047 Info.offset = 0;
7048 Info.align = 0;
7049 Info.vol = false; // volatile stores with NEON intrinsics not supported
7050 Info.readMem = false;
7051 Info.writeMem = true;
7052 return true;
7053 }
7054 case Intrinsic::aarch64_ldaxr:
7055 case Intrinsic::aarch64_ldxr: {
7056 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7057 Info.opc = ISD::INTRINSIC_W_CHAIN;
7058 Info.memVT = MVT::getVT(PtrTy->getElementType());
7059 Info.ptrVal = I.getArgOperand(0);
7060 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007061 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007062 Info.vol = true;
7063 Info.readMem = true;
7064 Info.writeMem = false;
7065 return true;
7066 }
7067 case Intrinsic::aarch64_stlxr:
7068 case Intrinsic::aarch64_stxr: {
7069 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7070 Info.opc = ISD::INTRINSIC_W_CHAIN;
7071 Info.memVT = MVT::getVT(PtrTy->getElementType());
7072 Info.ptrVal = I.getArgOperand(1);
7073 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007074 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007075 Info.vol = true;
7076 Info.readMem = false;
7077 Info.writeMem = true;
7078 return true;
7079 }
7080 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007081 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007082 Info.opc = ISD::INTRINSIC_W_CHAIN;
7083 Info.memVT = MVT::i128;
7084 Info.ptrVal = I.getArgOperand(0);
7085 Info.offset = 0;
7086 Info.align = 16;
7087 Info.vol = true;
7088 Info.readMem = true;
7089 Info.writeMem = false;
7090 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007091 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007092 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007093 Info.opc = ISD::INTRINSIC_W_CHAIN;
7094 Info.memVT = MVT::i128;
7095 Info.ptrVal = I.getArgOperand(2);
7096 Info.offset = 0;
7097 Info.align = 16;
7098 Info.vol = true;
7099 Info.readMem = false;
7100 Info.writeMem = true;
7101 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007102 default:
7103 break;
7104 }
7105
7106 return false;
7107}
7108
7109// Truncations from 64-bit GPR to 32-bit GPR is free.
7110bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7111 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7112 return false;
7113 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7114 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007115 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007116}
7117bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007118 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007119 return false;
7120 unsigned NumBits1 = VT1.getSizeInBits();
7121 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007122 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007123}
7124
Chad Rosier54390052015-02-23 19:15:16 +00007125/// Check if it is profitable to hoist instruction in then/else to if.
7126/// Not profitable if I and it's user can form a FMA instruction
7127/// because we prefer FMSUB/FMADD.
7128bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7129 if (I->getOpcode() != Instruction::FMul)
7130 return true;
7131
7132 if (I->getNumUses() != 1)
7133 return true;
7134
7135 Instruction *User = I->user_back();
7136
7137 if (User &&
7138 !(User->getOpcode() == Instruction::FSub ||
7139 User->getOpcode() == Instruction::FAdd))
7140 return true;
7141
7142 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007143 const DataLayout &DL = I->getModule()->getDataLayout();
7144 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007145
Eric Christopher114fa1c2016-02-29 22:50:49 +00007146 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7147 isOperationLegalOrCustom(ISD::FMA, VT) &&
7148 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7149 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007150}
7151
Tim Northover3b0846e2014-05-24 12:50:23 +00007152// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7153// 64-bit GPR.
7154bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7155 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7156 return false;
7157 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7158 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007159 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007160}
7161bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007162 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007163 return false;
7164 unsigned NumBits1 = VT1.getSizeInBits();
7165 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007166 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007167}
7168
7169bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7170 EVT VT1 = Val.getValueType();
7171 if (isZExtFree(VT1, VT2)) {
7172 return true;
7173 }
7174
7175 if (Val.getOpcode() != ISD::LOAD)
7176 return false;
7177
7178 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007179 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7180 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7181 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007182}
7183
Quentin Colombet6843ac42015-03-31 20:52:32 +00007184bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7185 if (isa<FPExtInst>(Ext))
7186 return false;
7187
7188 // Vector types are next free.
7189 if (Ext->getType()->isVectorTy())
7190 return false;
7191
7192 for (const Use &U : Ext->uses()) {
7193 // The extension is free if we can fold it with a left shift in an
7194 // addressing mode or an arithmetic operation: add, sub, and cmp.
7195
7196 // Is there a shift?
7197 const Instruction *Instr = cast<Instruction>(U.getUser());
7198
7199 // Is this a constant shift?
7200 switch (Instr->getOpcode()) {
7201 case Instruction::Shl:
7202 if (!isa<ConstantInt>(Instr->getOperand(1)))
7203 return false;
7204 break;
7205 case Instruction::GetElementPtr: {
7206 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007207 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00007208 std::advance(GTI, U.getOperandNo()-1);
7209 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007210 // This extension will end up with a shift because of the scaling factor.
7211 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7212 // Get the shift amount based on the scaling factor:
7213 // log2(sizeof(IdxTy)) - log2(8).
7214 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007215 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007216 // Is the constant foldable in the shift of the addressing mode?
7217 // I.e., shift amount is between 1 and 4 inclusive.
7218 if (ShiftAmt == 0 || ShiftAmt > 4)
7219 return false;
7220 break;
7221 }
7222 case Instruction::Trunc:
7223 // Check if this is a noop.
7224 // trunc(sext ty1 to ty2) to ty1.
7225 if (Instr->getType() == Ext->getOperand(0)->getType())
7226 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00007227 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007228 default:
7229 return false;
7230 }
7231
7232 // At this point we can use the bfm family, so this extension is free
7233 // for that use.
7234 }
7235 return true;
7236}
7237
Tim Northover3b0846e2014-05-24 12:50:23 +00007238bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7239 unsigned &RequiredAligment) const {
7240 if (!LoadedType.isSimple() ||
7241 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7242 return false;
7243 // Cyclone supports unaligned accesses.
7244 RequiredAligment = 0;
7245 unsigned NumBits = LoadedType.getSizeInBits();
7246 return NumBits == 32 || NumBits == 64;
7247}
7248
Hao Liu7ec8ee32015-06-26 02:32:07 +00007249/// \brief Lower an interleaved load into a ldN intrinsic.
7250///
7251/// E.g. Lower an interleaved load (Factor = 2):
7252/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7253/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7254/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7255///
7256/// Into:
7257/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7258/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7259/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7260bool AArch64TargetLowering::lowerInterleavedLoad(
7261 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7262 ArrayRef<unsigned> Indices, unsigned Factor) const {
7263 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7264 "Invalid interleave factor");
7265 assert(!Shuffles.empty() && "Empty shufflevector input");
7266 assert(Shuffles.size() == Indices.size() &&
7267 "Unmatched number of shufflevectors and indices");
7268
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007269 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007270
7271 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007272 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007273
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007274 // Skip if we do not have NEON and skip illegal vector types.
7275 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007276 return false;
7277
7278 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7279 // load integer vectors first and then convert to pointer vectors.
7280 Type *EltTy = VecTy->getVectorElementType();
7281 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007282 VecTy =
7283 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007284
7285 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7286 Type *Tys[2] = {VecTy, PtrTy};
7287 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7288 Intrinsic::aarch64_neon_ld3,
7289 Intrinsic::aarch64_neon_ld4};
7290 Function *LdNFunc =
7291 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7292
7293 IRBuilder<> Builder(LI);
7294 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7295
7296 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7297
7298 // Replace uses of each shufflevector with the corresponding vector loaded
7299 // by ldN.
7300 for (unsigned i = 0; i < Shuffles.size(); i++) {
7301 ShuffleVectorInst *SVI = Shuffles[i];
7302 unsigned Index = Indices[i];
7303
7304 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7305
7306 // Convert the integer vector to pointer vector if the element is pointer.
7307 if (EltTy->isPointerTy())
7308 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7309
7310 SVI->replaceAllUsesWith(SubVec);
7311 }
7312
7313 return true;
7314}
7315
7316/// \brief Get a mask consisting of sequential integers starting from \p Start.
7317///
7318/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7319static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7320 unsigned NumElts) {
7321 SmallVector<Constant *, 16> Mask;
7322 for (unsigned i = 0; i < NumElts; i++)
7323 Mask.push_back(Builder.getInt32(Start + i));
7324
7325 return ConstantVector::get(Mask);
7326}
7327
7328/// \brief Lower an interleaved store into a stN intrinsic.
7329///
7330/// E.g. Lower an interleaved store (Factor = 3):
7331/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007332/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00007333/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7334///
7335/// Into:
7336/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7337/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7338/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7339/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7340///
7341/// Note that the new shufflevectors will be removed and we'll only generate one
7342/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007343///
7344/// Example for a more general valid mask (Factor 3). Lower:
7345/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7346/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7347/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7348///
7349/// Into:
7350/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7351/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7352/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7353/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00007354bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7355 ShuffleVectorInst *SVI,
7356 unsigned Factor) const {
7357 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7358 "Invalid interleave factor");
7359
7360 VectorType *VecTy = SVI->getType();
7361 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7362 "Invalid interleaved store");
7363
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007364 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00007365 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007366 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007367
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007368 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007369 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007370
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007371 // Skip if we do not have NEON and skip illegal vector types.
7372 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007373 return false;
7374
7375 Value *Op0 = SVI->getOperand(0);
7376 Value *Op1 = SVI->getOperand(1);
7377 IRBuilder<> Builder(SI);
7378
7379 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7380 // vectors to integer vectors.
7381 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007382 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007383 unsigned NumOpElts =
7384 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7385
7386 // Convert to the corresponding integer vector.
7387 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7388 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7389 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7390
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007391 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007392 }
7393
7394 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7395 Type *Tys[2] = {SubVecTy, PtrTy};
7396 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7397 Intrinsic::aarch64_neon_st3,
7398 Intrinsic::aarch64_neon_st4};
7399 Function *StNFunc =
7400 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7401
7402 SmallVector<Value *, 5> Ops;
7403
7404 // Split the shufflevector operands into sub vectors for the new stN call.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007405 auto Mask = SVI->getShuffleMask();
7406 for (unsigned i = 0; i < Factor; i++) {
7407 if (Mask[i] >= 0) {
7408 Ops.push_back(Builder.CreateShuffleVector(
7409 Op0, Op1, getSequentialMask(Builder, Mask[i], LaneLen)));
7410 } else {
7411 unsigned StartMask = 0;
7412 for (unsigned j = 1; j < LaneLen; j++) {
7413 if (Mask[j*Factor + i] >= 0) {
7414 StartMask = Mask[j*Factor + i] - j;
7415 break;
7416 }
7417 }
7418 // Note: If all elements in a chunk are undefs, StartMask=0!
7419 // Note: Filling undef gaps with random elements is ok, since
7420 // those elements were being written anyway (with undefs).
7421 // In the case of all undefs we're defaulting to using elems from 0
7422 // Note: StartMask cannot be negative, it's checked in isReInterleaveMask
7423 Ops.push_back(Builder.CreateShuffleVector(
7424 Op0, Op1, getSequentialMask(Builder, StartMask, LaneLen)));
7425 }
7426 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00007427
7428 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7429 Builder.CreateCall(StNFunc, Ops);
7430 return true;
7431}
7432
Tim Northover3b0846e2014-05-24 12:50:23 +00007433static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7434 unsigned AlignCheck) {
7435 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7436 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7437}
7438
7439EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7440 unsigned SrcAlign, bool IsMemset,
7441 bool ZeroMemset,
7442 bool MemcpyStrSrc,
7443 MachineFunction &MF) const {
7444 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7445 // instruction to materialize the v2i64 zero and one store (with restrictive
7446 // addressing mode). Just do two i64 store of zero-registers.
7447 bool Fast;
7448 const Function *F = MF.getFunction();
7449 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007450 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007451 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007452 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007453 return MVT::f128;
7454
Lang Hames90333852015-04-09 03:40:33 +00007455 if (Size >= 8 &&
7456 (memOpAlign(SrcAlign, DstAlign, 8) ||
7457 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7458 return MVT::i64;
7459
7460 if (Size >= 4 &&
7461 (memOpAlign(SrcAlign, DstAlign, 4) ||
7462 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007463 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007464
7465 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007466}
7467
7468// 12-bit optionally shifted immediates are legal for adds.
7469bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berry486f49c2016-06-07 16:48:43 +00007470 // Avoid UB for INT64_MIN.
7471 if (Immed == std::numeric_limits<int64_t>::min())
7472 return false;
7473 // Same encoding for add/sub, just flip the sign.
7474 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007475 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007476}
7477
7478// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7479// immediates is the same as for an add or a sub.
7480bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007481 return isLegalAddImmediate(Immed);
7482}
7483
7484/// isLegalAddressingMode - Return true if the addressing mode represented
7485/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007486bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7487 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007488 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007489 // AArch64 has five basic addressing modes:
7490 // reg
7491 // reg + 9-bit signed offset
7492 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7493 // reg1 + reg2
7494 // reg + SIZE_IN_BYTES * reg
7495
7496 // No global is ever allowed as a base.
7497 if (AM.BaseGV)
7498 return false;
7499
7500 // No reg+reg+imm addressing.
7501 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7502 return false;
7503
7504 // check reg + imm case:
7505 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7506 uint64_t NumBytes = 0;
7507 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007508 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007509 NumBytes = NumBits / 8;
7510 if (!isPowerOf2_64(NumBits))
7511 NumBytes = 0;
7512 }
7513
7514 if (!AM.Scale) {
7515 int64_t Offset = AM.BaseOffs;
7516
7517 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00007518 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00007519 return true;
7520
7521 // 12-bit unsigned offset
7522 unsigned shift = Log2_64(NumBytes);
7523 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7524 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7525 (Offset >> shift) << shift == Offset)
7526 return true;
7527 return false;
7528 }
7529
7530 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7531
Haicheng Wu6bb0e392016-12-21 21:40:47 +00007532 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007533}
7534
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007535int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7536 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007537 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007538 // Scaling factors are not free at all.
7539 // Operands | Rt Latency
7540 // -------------------------------------------
7541 // Rt, [Xn, Xm] | 4
7542 // -------------------------------------------
7543 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7544 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007545 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007546 // Scale represents reg2 * scale, thus account for 1 if
7547 // it is not equal to 0 or 1.
7548 return AM.Scale != 0 && AM.Scale != 1;
7549 return -1;
7550}
7551
7552bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7553 VT = VT.getScalarType();
7554
7555 if (!VT.isSimple())
7556 return false;
7557
7558 switch (VT.getSimpleVT().SimpleTy) {
7559 case MVT::f32:
7560 case MVT::f64:
7561 return true;
7562 default:
7563 break;
7564 }
7565
7566 return false;
7567}
7568
7569const MCPhysReg *
7570AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7571 // LR is a callee-save register, but we must treat it as clobbered by any call
7572 // site. Hence we include LR in the scratch registers, which are in turn added
7573 // as implicit-defs for stackmaps and patchpoints.
7574 static const MCPhysReg ScratchRegs[] = {
7575 AArch64::X16, AArch64::X17, AArch64::LR, 0
7576 };
7577 return ScratchRegs;
7578}
7579
7580bool
7581AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7582 EVT VT = N->getValueType(0);
7583 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7584 // it with shift to let it be lowered to UBFX.
7585 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7586 isa<ConstantSDNode>(N->getOperand(1))) {
7587 uint64_t TruncMask = N->getConstantOperandVal(1);
7588 if (isMask_64(TruncMask) &&
7589 N->getOperand(0).getOpcode() == ISD::SRL &&
7590 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7591 return false;
7592 }
7593 return true;
7594}
7595
7596bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7597 Type *Ty) const {
7598 assert(Ty->isIntegerTy());
7599
7600 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7601 if (BitSize == 0)
7602 return false;
7603
7604 int64_t Val = Imm.getSExtValue();
7605 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7606 return true;
7607
7608 if ((int64_t)Val < 0)
7609 Val = ~Val;
7610 if (BitSize == 32)
7611 Val &= (1LL << 32) - 1;
7612
7613 unsigned LZ = countLeadingZeros((uint64_t)Val);
7614 unsigned Shift = (63 - LZ) / 16;
7615 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007616 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007617}
7618
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007619/// Turn vector tests of the signbit in the form of:
7620/// xor (sra X, elt_size(X)-1), -1
7621/// into:
7622/// cmge X, X, #0
7623static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7624 const AArch64Subtarget *Subtarget) {
7625 EVT VT = N->getValueType(0);
7626 if (!Subtarget->hasNEON() || !VT.isVector())
7627 return SDValue();
7628
7629 // There must be a shift right algebraic before the xor, and the xor must be a
7630 // 'not' operation.
7631 SDValue Shift = N->getOperand(0);
7632 SDValue Ones = N->getOperand(1);
7633 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7634 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7635 return SDValue();
7636
7637 // The shift should be smearing the sign bit across each vector element.
7638 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7639 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7640 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7641 return SDValue();
7642
7643 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7644}
7645
Tim Northover3b0846e2014-05-24 12:50:23 +00007646// Generate SUBS and CSEL for integer abs.
7647static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7648 EVT VT = N->getValueType(0);
7649
7650 SDValue N0 = N->getOperand(0);
7651 SDValue N1 = N->getOperand(1);
7652 SDLoc DL(N);
7653
7654 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7655 // and change it to SUB and CSEL.
7656 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7657 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7658 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7659 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7660 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007661 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007662 N0.getOperand(0));
7663 // Generate SUBS & CSEL.
7664 SDValue Cmp =
7665 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007666 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007667 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007668 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007669 SDValue(Cmp.getNode(), 1));
7670 }
7671 return SDValue();
7672}
7673
Tim Northover3b0846e2014-05-24 12:50:23 +00007674static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7675 TargetLowering::DAGCombinerInfo &DCI,
7676 const AArch64Subtarget *Subtarget) {
7677 if (DCI.isBeforeLegalizeOps())
7678 return SDValue();
7679
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007680 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7681 return Cmp;
7682
Tim Northover3b0846e2014-05-24 12:50:23 +00007683 return performIntegerAbsCombine(N, DAG);
7684}
7685
Chad Rosier17020f92014-07-23 14:57:52 +00007686SDValue
7687AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7688 SelectionDAG &DAG,
7689 std::vector<SDNode *> *Created) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +00007690 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7691 if (isIntDivCheap(N->getValueType(0), Attr))
7692 return SDValue(N,0); // Lower SDIV as SDIV
7693
Chad Rosier17020f92014-07-23 14:57:52 +00007694 // fold (sdiv X, pow2)
7695 EVT VT = N->getValueType(0);
7696 if ((VT != MVT::i32 && VT != MVT::i64) ||
7697 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7698 return SDValue();
7699
7700 SDLoc DL(N);
7701 SDValue N0 = N->getOperand(0);
7702 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007703 SDValue Zero = DAG.getConstant(0, DL, VT);
7704 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007705
7706 // Add (N0 < 0) ? Pow2 - 1 : 0;
7707 SDValue CCVal;
7708 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7709 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7710 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7711
7712 if (Created) {
7713 Created->push_back(Cmp.getNode());
7714 Created->push_back(Add.getNode());
7715 Created->push_back(CSel.getNode());
7716 }
7717
7718 // Divide by pow2.
7719 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007720 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007721
7722 // If we're dividing by a positive value, we're done. Otherwise, we must
7723 // negate the result.
7724 if (Divisor.isNonNegative())
7725 return SRA;
7726
7727 if (Created)
7728 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007729 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007730}
7731
Tim Northover3b0846e2014-05-24 12:50:23 +00007732static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7733 TargetLowering::DAGCombinerInfo &DCI,
7734 const AArch64Subtarget *Subtarget) {
7735 if (DCI.isBeforeLegalizeOps())
7736 return SDValue();
7737
Chad Rosier31ee8132016-11-11 17:07:37 +00007738 // The below optimizations require a constant RHS.
7739 if (!isa<ConstantSDNode>(N->getOperand(1)))
7740 return SDValue();
7741
7742 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7743 const APInt &ConstValue = C->getAPIntValue();
7744
Tim Northover3b0846e2014-05-24 12:50:23 +00007745 // Multiplication of a power of two plus/minus one can be done more
7746 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7747 // future CPUs have a cheaper MADD instruction, this may need to be
7748 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7749 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00007750 // More aggressively, some multiplications N0 * C can be lowered to
7751 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7752 // e.g. 6=3*2=(2+1)*2.
7753 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7754 // which equals to (1+2)*16-(1+2).
7755 SDValue N0 = N->getOperand(0);
7756 // TrailingZeroes is used to test if the mul can be lowered to
7757 // shift+add+shift.
7758 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7759 if (TrailingZeroes) {
7760 // Conservatively do not lower to shift+add+shift if the mul might be
7761 // folded into smul or umul.
7762 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7763 isZeroExtended(N0.getNode(), DAG)))
7764 return SDValue();
7765 // Conservatively do not lower to shift+add+shift if the mul might be
7766 // folded into madd or msub.
7767 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7768 N->use_begin()->getOpcode() == ISD::SUB))
7769 return SDValue();
7770 }
7771 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
7772 // and shift+add+shift.
7773 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
7774
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007775 unsigned ShiftAmt, AddSubOpc;
7776 // Is the shifted value the LHS operand of the add/sub?
7777 bool ShiftValUseIsN0 = true;
7778 // Do we need to negate the result?
7779 bool NegateResult = false;
7780
Chad Rosier31ee8132016-11-11 17:07:37 +00007781 if (ConstValue.isNonNegative()) {
7782 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00007783 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00007784 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
7785 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00007786 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00007787 if (SCVMinus1.isPowerOf2()) {
7788 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007789 AddSubOpc = ISD::ADD;
7790 } else if (CVPlus1.isPowerOf2()) {
7791 ShiftAmt = CVPlus1.logBase2();
7792 AddSubOpc = ISD::SUB;
7793 } else
7794 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00007795 } else {
7796 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00007797 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007798 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00007799 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007800 if (CVNegPlus1.isPowerOf2()) {
7801 ShiftAmt = CVNegPlus1.logBase2();
7802 AddSubOpc = ISD::SUB;
7803 ShiftValUseIsN0 = false;
7804 } else if (CVNegMinus1.isPowerOf2()) {
7805 ShiftAmt = CVNegMinus1.logBase2();
7806 AddSubOpc = ISD::ADD;
7807 NegateResult = true;
7808 } else
7809 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00007810 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007811
7812 SDLoc DL(N);
7813 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00007814 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007815 DAG.getConstant(ShiftAmt, DL, MVT::i64));
7816
7817 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
7818 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
7819 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00007820 assert(!(NegateResult && TrailingZeroes) &&
7821 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007822 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00007823 if (NegateResult)
7824 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
7825 // Shift the result.
7826 if (TrailingZeroes)
7827 return DAG.getNode(ISD::SHL, DL, VT, Res,
7828 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
7829 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00007830}
7831
Jim Grosbachf7502c42014-07-18 00:40:52 +00007832static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7833 SelectionDAG &DAG) {
7834 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7835 // optimize away operation when it's from a constant.
7836 //
7837 // The general transformation is:
7838 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7839 // AND(VECTOR_CMP(x,y), constant2)
7840 // constant2 = UNARYOP(constant)
7841
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007842 // Early exit if this isn't a vector operation, the operand of the
7843 // unary operation isn't a bitwise AND, or if the sizes of the operations
7844 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007845 EVT VT = N->getValueType(0);
7846 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007847 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7848 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007849 return SDValue();
7850
Jim Grosbach724e4382014-07-23 20:41:43 +00007851 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007852 // make the transformation for non-constant splats as well, but it's unclear
7853 // that would be a benefit as it would not eliminate any operations, just
7854 // perform one more step in scalar code before moving to the vector unit.
7855 if (BuildVectorSDNode *BV =
7856 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007857 // Bail out if the vector isn't a constant.
7858 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007859 return SDValue();
7860
7861 // Everything checks out. Build up the new and improved node.
7862 SDLoc DL(N);
7863 EVT IntVT = BV->getValueType(0);
7864 // Create a new constant of the appropriate type for the transformed
7865 // DAG.
7866 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7867 // The AND node needs bitcasts to/from an integer vector type around it.
7868 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7869 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7870 N->getOperand(0)->getOperand(0), MaskConst);
7871 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7872 return Res;
7873 }
7874
7875 return SDValue();
7876}
7877
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007878static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7879 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007880 // First try to optimize away the conversion when it's conditionally from
7881 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007882 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007883 return Res;
7884
Tim Northover3b0846e2014-05-24 12:50:23 +00007885 EVT VT = N->getValueType(0);
7886 if (VT != MVT::f32 && VT != MVT::f64)
7887 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007888
Tim Northover3b0846e2014-05-24 12:50:23 +00007889 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007890 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00007891 return SDValue();
7892
7893 // If the result of an integer load is only used by an integer-to-float
7894 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007895 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007896 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007897 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007898 // Do not change the width of a volatile load.
7899 !cast<LoadSDNode>(N0)->isVolatile()) {
7900 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7901 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00007902 LN0->getPointerInfo(), LN0->getAlignment(),
7903 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00007904
7905 // Make sure successors of the original load stay after it by updating them
7906 // to use the new Chain.
7907 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7908
7909 unsigned Opcode =
7910 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7911 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7912 }
7913
7914 return SDValue();
7915}
7916
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007917/// Fold a floating-point multiply by power of two into floating-point to
7918/// fixed-point conversion.
7919static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00007920 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007921 const AArch64Subtarget *Subtarget) {
7922 if (!Subtarget->hasNEON())
7923 return SDValue();
7924
7925 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00007926 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7927 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007928 return SDValue();
7929
7930 SDValue ConstVec = Op->getOperand(1);
7931 if (!isa<BuildVectorSDNode>(ConstVec))
7932 return SDValue();
7933
7934 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7935 uint32_t FloatBits = FloatTy.getSizeInBits();
7936 if (FloatBits != 32 && FloatBits != 64)
7937 return SDValue();
7938
7939 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7940 uint32_t IntBits = IntTy.getSizeInBits();
7941 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7942 return SDValue();
7943
7944 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7945 if (IntBits > FloatBits)
7946 return SDValue();
7947
7948 BitVector UndefElements;
7949 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7950 int32_t Bits = IntBits == 64 ? 64 : 32;
7951 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7952 if (C == -1 || C == 0 || C > Bits)
7953 return SDValue();
7954
7955 MVT ResTy;
7956 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7957 switch (NumLanes) {
7958 default:
7959 return SDValue();
7960 case 2:
7961 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7962 break;
7963 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00007964 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007965 break;
7966 }
7967
Silviu Barangafa00ba32016-08-08 13:13:57 +00007968 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7969 return SDValue();
7970
7971 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7972 "Illegal vector type after legalization");
7973
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007974 SDLoc DL(N);
7975 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7976 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7977 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7978 SDValue FixConv =
7979 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7980 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7981 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7982 // We can handle smaller integers by generating an extra trunc.
7983 if (IntBits < FloatBits)
7984 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7985
7986 return FixConv;
7987}
7988
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007989/// Fold a floating-point divide by power of two into fixed-point to
7990/// floating-point conversion.
7991static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00007992 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007993 const AArch64Subtarget *Subtarget) {
7994 if (!Subtarget->hasNEON())
7995 return SDValue();
7996
7997 SDValue Op = N->getOperand(0);
7998 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00007999 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8000 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008001 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8002 return SDValue();
8003
8004 SDValue ConstVec = N->getOperand(1);
8005 if (!isa<BuildVectorSDNode>(ConstVec))
8006 return SDValue();
8007
8008 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8009 int32_t IntBits = IntTy.getSizeInBits();
8010 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8011 return SDValue();
8012
8013 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8014 int32_t FloatBits = FloatTy.getSizeInBits();
8015 if (FloatBits != 32 && FloatBits != 64)
8016 return SDValue();
8017
8018 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8019 if (IntBits > FloatBits)
8020 return SDValue();
8021
8022 BitVector UndefElements;
8023 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8024 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8025 if (C == -1 || C == 0 || C > FloatBits)
8026 return SDValue();
8027
8028 MVT ResTy;
8029 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8030 switch (NumLanes) {
8031 default:
8032 return SDValue();
8033 case 2:
8034 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8035 break;
8036 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00008037 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008038 break;
8039 }
8040
Tim Northover85cf5642016-08-26 18:52:31 +00008041 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8042 return SDValue();
8043
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008044 SDLoc DL(N);
8045 SDValue ConvInput = Op.getOperand(0);
8046 bool IsSigned = Opc == ISD::SINT_TO_FP;
8047 if (IntBits < FloatBits)
8048 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8049 ResTy, ConvInput);
8050
8051 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8052 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8053 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8054 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8055 DAG.getConstant(C, DL, MVT::i32));
8056}
8057
Tim Northover3b0846e2014-05-24 12:50:23 +00008058/// An EXTR instruction is made up of two shifts, ORed together. This helper
8059/// searches for and classifies those shifts.
8060static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8061 bool &FromHi) {
8062 if (N.getOpcode() == ISD::SHL)
8063 FromHi = false;
8064 else if (N.getOpcode() == ISD::SRL)
8065 FromHi = true;
8066 else
8067 return false;
8068
8069 if (!isa<ConstantSDNode>(N.getOperand(1)))
8070 return false;
8071
8072 ShiftAmount = N->getConstantOperandVal(1);
8073 Src = N->getOperand(0);
8074 return true;
8075}
8076
8077/// EXTR instruction extracts a contiguous chunk of bits from two existing
8078/// registers viewed as a high/low pair. This function looks for the pattern:
8079/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8080/// EXTR. Can't quite be done in TableGen because the two immediates aren't
8081/// independent.
8082static SDValue tryCombineToEXTR(SDNode *N,
8083 TargetLowering::DAGCombinerInfo &DCI) {
8084 SelectionDAG &DAG = DCI.DAG;
8085 SDLoc DL(N);
8086 EVT VT = N->getValueType(0);
8087
8088 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8089
8090 if (VT != MVT::i32 && VT != MVT::i64)
8091 return SDValue();
8092
8093 SDValue LHS;
8094 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008095 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008096 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8097 return SDValue();
8098
8099 SDValue RHS;
8100 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008101 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008102 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8103 return SDValue();
8104
8105 // If they're both trying to come from the high part of the register, they're
8106 // not really an EXTR.
8107 if (LHSFromHi == RHSFromHi)
8108 return SDValue();
8109
8110 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8111 return SDValue();
8112
8113 if (LHSFromHi) {
8114 std::swap(LHS, RHS);
8115 std::swap(ShiftLHS, ShiftRHS);
8116 }
8117
8118 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008119 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008120}
8121
8122static SDValue tryCombineToBSL(SDNode *N,
8123 TargetLowering::DAGCombinerInfo &DCI) {
8124 EVT VT = N->getValueType(0);
8125 SelectionDAG &DAG = DCI.DAG;
8126 SDLoc DL(N);
8127
8128 if (!VT.isVector())
8129 return SDValue();
8130
8131 SDValue N0 = N->getOperand(0);
8132 if (N0.getOpcode() != ISD::AND)
8133 return SDValue();
8134
8135 SDValue N1 = N->getOperand(1);
8136 if (N1.getOpcode() != ISD::AND)
8137 return SDValue();
8138
8139 // We only have to look for constant vectors here since the general, variable
8140 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008141 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008142 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8143 for (int i = 1; i >= 0; --i)
8144 for (int j = 1; j >= 0; --j) {
8145 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8146 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8147 if (!BVN0 || !BVN1)
8148 continue;
8149
8150 bool FoundMatch = true;
8151 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8152 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8153 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8154 if (!CN0 || !CN1 ||
8155 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8156 FoundMatch = false;
8157 break;
8158 }
8159 }
8160
8161 if (FoundMatch)
8162 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8163 N0->getOperand(1 - i), N1->getOperand(1 - j));
8164 }
8165
8166 return SDValue();
8167}
8168
8169static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8170 const AArch64Subtarget *Subtarget) {
8171 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00008172 SelectionDAG &DAG = DCI.DAG;
8173 EVT VT = N->getValueType(0);
8174
8175 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8176 return SDValue();
8177
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008178 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008179 return Res;
8180
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008181 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008182 return Res;
8183
8184 return SDValue();
8185}
8186
Chad Rosier14aa2ad2016-05-26 19:41:33 +00008187static SDValue performSRLCombine(SDNode *N,
8188 TargetLowering::DAGCombinerInfo &DCI) {
8189 SelectionDAG &DAG = DCI.DAG;
8190 EVT VT = N->getValueType(0);
8191 if (VT != MVT::i32 && VT != MVT::i64)
8192 return SDValue();
8193
8194 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8195 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8196 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8197 SDValue N0 = N->getOperand(0);
8198 if (N0.getOpcode() == ISD::BSWAP) {
8199 SDLoc DL(N);
8200 SDValue N1 = N->getOperand(1);
8201 SDValue N00 = N0.getOperand(0);
8202 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8203 uint64_t ShiftAmt = C->getZExtValue();
8204 if (VT == MVT::i32 && ShiftAmt == 16 &&
8205 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8206 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8207 if (VT == MVT::i64 && ShiftAmt == 32 &&
8208 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8209 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8210 }
8211 }
8212 return SDValue();
8213}
8214
Tim Northover3b0846e2014-05-24 12:50:23 +00008215static SDValue performBitcastCombine(SDNode *N,
8216 TargetLowering::DAGCombinerInfo &DCI,
8217 SelectionDAG &DAG) {
8218 // Wait 'til after everything is legalized to try this. That way we have
8219 // legal vector types and such.
8220 if (DCI.isBeforeLegalizeOps())
8221 return SDValue();
8222
8223 // Remove extraneous bitcasts around an extract_subvector.
8224 // For example,
8225 // (v4i16 (bitconvert
8226 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8227 // becomes
8228 // (extract_subvector ((v8i16 ...), (i64 4)))
8229
8230 // Only interested in 64-bit vectors as the ultimate result.
8231 EVT VT = N->getValueType(0);
8232 if (!VT.isVector())
8233 return SDValue();
8234 if (VT.getSimpleVT().getSizeInBits() != 64)
8235 return SDValue();
8236 // Is the operand an extract_subvector starting at the beginning or halfway
8237 // point of the vector? A low half may also come through as an
8238 // EXTRACT_SUBREG, so look for that, too.
8239 SDValue Op0 = N->getOperand(0);
8240 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8241 !(Op0->isMachineOpcode() &&
8242 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8243 return SDValue();
8244 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8245 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8246 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8247 return SDValue();
8248 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8249 if (idx != AArch64::dsub)
8250 return SDValue();
8251 // The dsub reference is equivalent to a lane zero subvector reference.
8252 idx = 0;
8253 }
8254 // Look through the bitcast of the input to the extract.
8255 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8256 return SDValue();
8257 SDValue Source = Op0->getOperand(0)->getOperand(0);
8258 // If the source type has twice the number of elements as our destination
8259 // type, we know this is an extract of the high or low half of the vector.
8260 EVT SVT = Source->getValueType(0);
8261 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8262 return SDValue();
8263
8264 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8265
8266 // Create the simplified form to just extract the low or high half of the
8267 // vector directly rather than bothering with the bitcasts.
8268 SDLoc dl(N);
8269 unsigned NumElements = VT.getVectorNumElements();
8270 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008271 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008272 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8273 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008274 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008275 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8276 Source, SubReg),
8277 0);
8278 }
8279}
8280
8281static SDValue performConcatVectorsCombine(SDNode *N,
8282 TargetLowering::DAGCombinerInfo &DCI,
8283 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008284 SDLoc dl(N);
8285 EVT VT = N->getValueType(0);
8286 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8287
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008288 // Optimize concat_vectors of truncated vectors, where the intermediate
8289 // type is illegal, to avoid said illegality, e.g.,
8290 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8291 // (v2i16 (truncate (v2i64)))))
8292 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008293 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8294 // (v4i32 (bitcast (v2i64))),
8295 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008296 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8297 // on both input and result type, so we might generate worse code.
8298 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8299 if (N->getNumOperands() == 2 &&
8300 N0->getOpcode() == ISD::TRUNCATE &&
8301 N1->getOpcode() == ISD::TRUNCATE) {
8302 SDValue N00 = N0->getOperand(0);
8303 SDValue N10 = N1->getOperand(0);
8304 EVT N00VT = N00.getValueType();
8305
8306 if (N00VT == N10.getValueType() &&
8307 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8308 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008309 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8310 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8311 for (size_t i = 0; i < Mask.size(); ++i)
8312 Mask[i] = i * 2;
8313 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8314 DAG.getVectorShuffle(
8315 MidVT, dl,
8316 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8317 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008318 }
8319 }
8320
Tim Northover3b0846e2014-05-24 12:50:23 +00008321 // Wait 'til after everything is legalized to try this. That way we have
8322 // legal vector types and such.
8323 if (DCI.isBeforeLegalizeOps())
8324 return SDValue();
8325
Tim Northover3b0846e2014-05-24 12:50:23 +00008326 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8327 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8328 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008329 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008330 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008331 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008332 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008333 }
8334
8335 // Canonicalise concat_vectors so that the right-hand vector has as few
8336 // bit-casts as possible before its real operation. The primary matching
8337 // destination for these operations will be the narrowing "2" instructions,
8338 // which depend on the operation being performed on this right-hand vector.
8339 // For example,
8340 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8341 // becomes
8342 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8343
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008344 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008345 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008346 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008347 MVT RHSTy = RHS.getValueType().getSimpleVT();
8348 // If the RHS is not a vector, this is not the pattern we're looking for.
8349 if (!RHSTy.isVector())
8350 return SDValue();
8351
8352 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8353
8354 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8355 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008356 return DAG.getNode(ISD::BITCAST, dl, VT,
8357 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8358 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8359 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008360}
8361
8362static SDValue tryCombineFixedPointConvert(SDNode *N,
8363 TargetLowering::DAGCombinerInfo &DCI,
8364 SelectionDAG &DAG) {
8365 // Wait 'til after everything is legalized to try this. That way we have
8366 // legal vector types and such.
8367 if (DCI.isBeforeLegalizeOps())
8368 return SDValue();
8369 // Transform a scalar conversion of a value from a lane extract into a
8370 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8371 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8372 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8373 //
8374 // The second form interacts better with instruction selection and the
8375 // register allocator to avoid cross-class register copies that aren't
8376 // coalescable due to a lane reference.
8377
8378 // Check the operand and see if it originates from a lane extract.
8379 SDValue Op1 = N->getOperand(1);
8380 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8381 // Yep, no additional predication needed. Perform the transform.
8382 SDValue IID = N->getOperand(0);
8383 SDValue Shift = N->getOperand(2);
8384 SDValue Vec = Op1.getOperand(0);
8385 SDValue Lane = Op1.getOperand(1);
8386 EVT ResTy = N->getValueType(0);
8387 EVT VecResTy;
8388 SDLoc DL(N);
8389
8390 // The vector width should be 128 bits by the time we get here, even
8391 // if it started as 64 bits (the extract_vector handling will have
8392 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008393 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008394 "unexpected vector size on extract_vector_elt!");
8395 if (Vec.getValueType() == MVT::v4i32)
8396 VecResTy = MVT::v4f32;
8397 else if (Vec.getValueType() == MVT::v2i64)
8398 VecResTy = MVT::v2f64;
8399 else
Craig Topper2a30d782014-06-18 05:05:13 +00008400 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008401
8402 SDValue Convert =
8403 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8404 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8405 }
8406 return SDValue();
8407}
8408
8409// AArch64 high-vector "long" operations are formed by performing the non-high
8410// version on an extract_subvector of each operand which gets the high half:
8411//
8412// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8413//
8414// However, there are cases which don't have an extract_high explicitly, but
8415// have another operation that can be made compatible with one for free. For
8416// example:
8417//
8418// (dupv64 scalar) --> (extract_high (dup128 scalar))
8419//
8420// This routine does the actual conversion of such DUPs, once outer routines
8421// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008422// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8423// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008424static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008425 switch (N.getOpcode()) {
8426 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008427 case AArch64ISD::DUPLANE8:
8428 case AArch64ISD::DUPLANE16:
8429 case AArch64ISD::DUPLANE32:
8430 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008431 case AArch64ISD::MOVI:
8432 case AArch64ISD::MOVIshift:
8433 case AArch64ISD::MOVIedit:
8434 case AArch64ISD::MOVImsl:
8435 case AArch64ISD::MVNIshift:
8436 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008437 break;
8438 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008439 // FMOV could be supported, but isn't very useful, as it would only occur
8440 // if you passed a bitcast' floating point immediate to an eligible long
8441 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008442 return SDValue();
8443 }
8444
8445 MVT NarrowTy = N.getSimpleValueType();
8446 if (!NarrowTy.is64BitVector())
8447 return SDValue();
8448
8449 MVT ElementTy = NarrowTy.getVectorElementType();
8450 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008451 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008452
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008453 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008454 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8455 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008456 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008457}
8458
8459static bool isEssentiallyExtractSubvector(SDValue N) {
8460 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8461 return true;
8462
8463 return N.getOpcode() == ISD::BITCAST &&
8464 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8465}
8466
8467/// \brief Helper structure to keep track of ISD::SET_CC operands.
8468struct GenericSetCCInfo {
8469 const SDValue *Opnd0;
8470 const SDValue *Opnd1;
8471 ISD::CondCode CC;
8472};
8473
8474/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8475struct AArch64SetCCInfo {
8476 const SDValue *Cmp;
8477 AArch64CC::CondCode CC;
8478};
8479
8480/// \brief Helper structure to keep track of SetCC information.
8481union SetCCInfo {
8482 GenericSetCCInfo Generic;
8483 AArch64SetCCInfo AArch64;
8484};
8485
8486/// \brief Helper structure to be able to read SetCC information. If set to
8487/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8488/// GenericSetCCInfo.
8489struct SetCCInfoAndKind {
8490 SetCCInfo Info;
8491 bool IsAArch64;
8492};
8493
8494/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8495/// an
8496/// AArch64 lowered one.
8497/// \p SetCCInfo is filled accordingly.
8498/// \post SetCCInfo is meanginfull only when this function returns true.
8499/// \return True when Op is a kind of SET_CC operation.
8500static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8501 // If this is a setcc, this is straight forward.
8502 if (Op.getOpcode() == ISD::SETCC) {
8503 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8504 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8505 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8506 SetCCInfo.IsAArch64 = false;
8507 return true;
8508 }
8509 // Otherwise, check if this is a matching csel instruction.
8510 // In other words:
8511 // - csel 1, 0, cc
8512 // - csel 0, 1, !cc
8513 if (Op.getOpcode() != AArch64ISD::CSEL)
8514 return false;
8515 // Set the information about the operands.
8516 // TODO: we want the operands of the Cmp not the csel
8517 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8518 SetCCInfo.IsAArch64 = true;
8519 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8520 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8521
8522 // Check that the operands matches the constraints:
8523 // (1) Both operands must be constants.
8524 // (2) One must be 1 and the other must be 0.
8525 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8526 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8527
8528 // Check (1).
8529 if (!TValue || !FValue)
8530 return false;
8531
8532 // Check (2).
8533 if (!TValue->isOne()) {
8534 // Update the comparison when we are interested in !cc.
8535 std::swap(TValue, FValue);
8536 SetCCInfo.Info.AArch64.CC =
8537 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8538 }
8539 return TValue->isOne() && FValue->isNullValue();
8540}
8541
8542// Returns true if Op is setcc or zext of setcc.
8543static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8544 if (isSetCC(Op, Info))
8545 return true;
8546 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8547 isSetCC(Op->getOperand(0), Info));
8548}
8549
8550// The folding we want to perform is:
8551// (add x, [zext] (setcc cc ...) )
8552// -->
8553// (csel x, (add x, 1), !cc ...)
8554//
8555// The latter will get matched to a CSINC instruction.
8556static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8557 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8558 SDValue LHS = Op->getOperand(0);
8559 SDValue RHS = Op->getOperand(1);
8560 SetCCInfoAndKind InfoAndKind;
8561
8562 // If neither operand is a SET_CC, give up.
8563 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8564 std::swap(LHS, RHS);
8565 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8566 return SDValue();
8567 }
8568
8569 // FIXME: This could be generatized to work for FP comparisons.
8570 EVT CmpVT = InfoAndKind.IsAArch64
8571 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8572 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8573 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8574 return SDValue();
8575
8576 SDValue CCVal;
8577 SDValue Cmp;
8578 SDLoc dl(Op);
8579 if (InfoAndKind.IsAArch64) {
8580 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008581 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8582 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008583 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8584 } else
8585 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8586 *InfoAndKind.Info.Generic.Opnd1,
8587 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8588 CCVal, DAG, dl);
8589
8590 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008591 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008592 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8593}
8594
8595// The basic add/sub long vector instructions have variants with "2" on the end
8596// which act on the high-half of their inputs. They are normally matched by
8597// patterns like:
8598//
8599// (add (zeroext (extract_high LHS)),
8600// (zeroext (extract_high RHS)))
8601// -> uaddl2 vD, vN, vM
8602//
8603// However, if one of the extracts is something like a duplicate, this
8604// instruction can still be used profitably. This function puts the DAG into a
8605// more appropriate form for those patterns to trigger.
8606static SDValue performAddSubLongCombine(SDNode *N,
8607 TargetLowering::DAGCombinerInfo &DCI,
8608 SelectionDAG &DAG) {
8609 if (DCI.isBeforeLegalizeOps())
8610 return SDValue();
8611
8612 MVT VT = N->getSimpleValueType(0);
8613 if (!VT.is128BitVector()) {
8614 if (N->getOpcode() == ISD::ADD)
8615 return performSetccAddFolding(N, DAG);
8616 return SDValue();
8617 }
8618
8619 // Make sure both branches are extended in the same way.
8620 SDValue LHS = N->getOperand(0);
8621 SDValue RHS = N->getOperand(1);
8622 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8623 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8624 LHS.getOpcode() != RHS.getOpcode())
8625 return SDValue();
8626
8627 unsigned ExtType = LHS.getOpcode();
8628
8629 // It's not worth doing if at least one of the inputs isn't already an
8630 // extract, but we don't know which it'll be so we have to try both.
8631 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8632 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8633 if (!RHS.getNode())
8634 return SDValue();
8635
8636 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8637 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8638 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8639 if (!LHS.getNode())
8640 return SDValue();
8641
8642 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8643 }
8644
8645 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8646}
8647
8648// Massage DAGs which we can use the high-half "long" operations on into
8649// something isel will recognize better. E.g.
8650//
8651// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8652// (aarch64_neon_umull (extract_high (v2i64 vec)))
8653// (extract_high (v2i64 (dup128 scalar)))))
8654//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008655static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008656 TargetLowering::DAGCombinerInfo &DCI,
8657 SelectionDAG &DAG) {
8658 if (DCI.isBeforeLegalizeOps())
8659 return SDValue();
8660
Hal Finkelcd8664c2015-12-11 23:11:52 +00008661 SDValue LHS = N->getOperand(1);
8662 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008663 assert(LHS.getValueType().is64BitVector() &&
8664 RHS.getValueType().is64BitVector() &&
8665 "unexpected shape for long operation");
8666
8667 // Either node could be a DUP, but it's not worth doing both of them (you'd
8668 // just as well use the non-high version) so look for a corresponding extract
8669 // operation on the other "wing".
8670 if (isEssentiallyExtractSubvector(LHS)) {
8671 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8672 if (!RHS.getNode())
8673 return SDValue();
8674 } else if (isEssentiallyExtractSubvector(RHS)) {
8675 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8676 if (!LHS.getNode())
8677 return SDValue();
8678 }
8679
Hal Finkelcd8664c2015-12-11 23:11:52 +00008680 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8681 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008682}
8683
8684static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8685 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8686 unsigned ElemBits = ElemTy.getSizeInBits();
8687
8688 int64_t ShiftAmount;
8689 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8690 APInt SplatValue, SplatUndef;
8691 unsigned SplatBitSize;
8692 bool HasAnyUndefs;
8693 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8694 HasAnyUndefs, ElemBits) ||
8695 SplatBitSize != ElemBits)
8696 return SDValue();
8697
8698 ShiftAmount = SplatValue.getSExtValue();
8699 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8700 ShiftAmount = CVN->getSExtValue();
8701 } else
8702 return SDValue();
8703
8704 unsigned Opcode;
8705 bool IsRightShift;
8706 switch (IID) {
8707 default:
8708 llvm_unreachable("Unknown shift intrinsic");
8709 case Intrinsic::aarch64_neon_sqshl:
8710 Opcode = AArch64ISD::SQSHL_I;
8711 IsRightShift = false;
8712 break;
8713 case Intrinsic::aarch64_neon_uqshl:
8714 Opcode = AArch64ISD::UQSHL_I;
8715 IsRightShift = false;
8716 break;
8717 case Intrinsic::aarch64_neon_srshl:
8718 Opcode = AArch64ISD::SRSHR_I;
8719 IsRightShift = true;
8720 break;
8721 case Intrinsic::aarch64_neon_urshl:
8722 Opcode = AArch64ISD::URSHR_I;
8723 IsRightShift = true;
8724 break;
8725 case Intrinsic::aarch64_neon_sqshlu:
8726 Opcode = AArch64ISD::SQSHLU_I;
8727 IsRightShift = false;
8728 break;
8729 }
8730
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008731 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8732 SDLoc dl(N);
8733 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8734 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8735 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8736 SDLoc dl(N);
8737 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8738 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8739 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008740
8741 return SDValue();
8742}
8743
8744// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8745// the intrinsics must be legal and take an i32, this means there's almost
8746// certainly going to be a zext in the DAG which we can eliminate.
8747static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8748 SDValue AndN = N->getOperand(2);
8749 if (AndN.getOpcode() != ISD::AND)
8750 return SDValue();
8751
8752 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8753 if (!CMask || CMask->getZExtValue() != Mask)
8754 return SDValue();
8755
8756 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8757 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8758}
8759
Ahmed Bougachafab58922015-03-10 20:45:38 +00008760static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8761 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008762 SDLoc dl(N);
8763 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8764 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008765 N->getOperand(1).getSimpleValueType(),
8766 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008767 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008768}
8769
Tim Northover3b0846e2014-05-24 12:50:23 +00008770static SDValue performIntrinsicCombine(SDNode *N,
8771 TargetLowering::DAGCombinerInfo &DCI,
8772 const AArch64Subtarget *Subtarget) {
8773 SelectionDAG &DAG = DCI.DAG;
8774 unsigned IID = getIntrinsicID(N);
8775 switch (IID) {
8776 default:
8777 break;
8778 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8779 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8780 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008781 case Intrinsic::aarch64_neon_saddv:
8782 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8783 case Intrinsic::aarch64_neon_uaddv:
8784 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8785 case Intrinsic::aarch64_neon_sminv:
8786 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8787 case Intrinsic::aarch64_neon_uminv:
8788 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8789 case Intrinsic::aarch64_neon_smaxv:
8790 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8791 case Intrinsic::aarch64_neon_umaxv:
8792 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008793 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008794 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008795 N->getOperand(1), N->getOperand(2));
8796 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008797 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008798 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008799 case Intrinsic::aarch64_neon_fmaxnm:
8800 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8801 N->getOperand(1), N->getOperand(2));
8802 case Intrinsic::aarch64_neon_fminnm:
8803 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8804 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008805 case Intrinsic::aarch64_neon_smull:
8806 case Intrinsic::aarch64_neon_umull:
8807 case Intrinsic::aarch64_neon_pmull:
8808 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008809 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008810 case Intrinsic::aarch64_neon_sqshl:
8811 case Intrinsic::aarch64_neon_uqshl:
8812 case Intrinsic::aarch64_neon_sqshlu:
8813 case Intrinsic::aarch64_neon_srshl:
8814 case Intrinsic::aarch64_neon_urshl:
8815 return tryCombineShiftImm(IID, N, DAG);
8816 case Intrinsic::aarch64_crc32b:
8817 case Intrinsic::aarch64_crc32cb:
8818 return tryCombineCRC32(0xff, N, DAG);
8819 case Intrinsic::aarch64_crc32h:
8820 case Intrinsic::aarch64_crc32ch:
8821 return tryCombineCRC32(0xffff, N, DAG);
8822 }
8823 return SDValue();
8824}
8825
8826static SDValue performExtendCombine(SDNode *N,
8827 TargetLowering::DAGCombinerInfo &DCI,
8828 SelectionDAG &DAG) {
8829 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8830 // we can convert that DUP into another extract_high (of a bigger DUP), which
8831 // helps the backend to decide that an sabdl2 would be useful, saving a real
8832 // extract_high operation.
8833 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008834 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008835 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008836 unsigned IID = getIntrinsicID(ABDNode);
8837 if (IID == Intrinsic::aarch64_neon_sabd ||
8838 IID == Intrinsic::aarch64_neon_uabd) {
8839 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8840 if (!NewABD.getNode())
8841 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008842
Hal Finkelcd8664c2015-12-11 23:11:52 +00008843 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8844 NewABD);
8845 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008846 }
8847
8848 // This is effectively a custom type legalization for AArch64.
8849 //
8850 // Type legalization will split an extend of a small, legal, type to a larger
8851 // illegal type by first splitting the destination type, often creating
8852 // illegal source types, which then get legalized in isel-confusing ways,
8853 // leading to really terrible codegen. E.g.,
8854 // %result = v8i32 sext v8i8 %value
8855 // becomes
8856 // %losrc = extract_subreg %value, ...
8857 // %hisrc = extract_subreg %value, ...
8858 // %lo = v4i32 sext v4i8 %losrc
8859 // %hi = v4i32 sext v4i8 %hisrc
8860 // Things go rapidly downhill from there.
8861 //
8862 // For AArch64, the [sz]ext vector instructions can only go up one element
8863 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8864 // take two instructions.
8865 //
8866 // This implies that the most efficient way to do the extend from v8i8
8867 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8868 // the normal splitting to happen for the v8i16->v8i32.
8869
8870 // This is pre-legalization to catch some cases where the default
8871 // type legalization will create ill-tempered code.
8872 if (!DCI.isBeforeLegalizeOps())
8873 return SDValue();
8874
8875 // We're only interested in cleaning things up for non-legal vector types
8876 // here. If both the source and destination are legal, things will just
8877 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008878 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008879 EVT ResVT = N->getValueType(0);
8880 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8881 return SDValue();
8882 // If the vector type isn't a simple VT, it's beyond the scope of what
8883 // we're worried about here. Let legalization do its thing and hope for
8884 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008885 SDValue Src = N->getOperand(0);
8886 EVT SrcVT = Src->getValueType(0);
8887 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008888 return SDValue();
8889
Tim Northover3b0846e2014-05-24 12:50:23 +00008890 // If the source VT is a 64-bit vector, we can play games and get the
8891 // better results we want.
8892 if (SrcVT.getSizeInBits() != 64)
8893 return SDValue();
8894
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008895 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008896 unsigned ElementCount = SrcVT.getVectorNumElements();
8897 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8898 SDLoc DL(N);
8899 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8900
8901 // Now split the rest of the operation into two halves, each with a 64
8902 // bit source.
8903 EVT LoVT, HiVT;
8904 SDValue Lo, Hi;
8905 unsigned NumElements = ResVT.getVectorNumElements();
8906 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8907 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8908 ResVT.getVectorElementType(), NumElements / 2);
8909
8910 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8911 LoVT.getVectorNumElements());
8912 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008913 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008914 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008915 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008916 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8917 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8918
8919 // Now combine the parts back together so we still have a single result
8920 // like the combiner expects.
8921 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8922}
8923
Geoff Berry8301c642016-11-16 19:35:19 +00008924static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
8925 SDValue SplatVal, unsigned NumVecElts) {
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008926 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +00008927 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008928
8929 // Create scalar stores. This is at least as good as the code sequence for a
8930 // split unaligned store which is a dup.s, ext.b, and two stores.
8931 // Most of the time the three stores should be replaced by store pair
8932 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008933 SDLoc DL(&St);
8934 SDValue BasePtr = St.getBasePtr();
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008935 SDValue NewST1 =
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008936 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, St.getPointerInfo(),
Geoff Berry8301c642016-11-16 19:35:19 +00008937 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008938
8939 unsigned Offset = EltOffset;
8940 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +00008941 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008942 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8943 DAG.getConstant(Offset, DL, MVT::i64));
8944 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008945 St.getPointerInfo(), Alignment,
8946 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008947 Offset += EltOffset;
8948 }
8949 return NewST1;
8950}
8951
Geoff Berry526c5052016-11-14 19:39:04 +00008952/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
8953/// load store optimizer pass will merge them to store pair stores. This should
8954/// be better than a movi to create the vector zero followed by a vector store
8955/// if the zero constant is not re-used, since one instructions and one register
8956/// live range will be removed.
8957///
8958/// For example, the final generated code should be:
8959///
8960/// stp xzr, xzr, [x0]
8961///
8962/// instead of:
8963///
8964/// movi v0.2d, #0
8965/// str q0, [x0]
8966///
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008967static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8968 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +00008969 EVT VT = StVal.getValueType();
8970
Geoff Berry8301c642016-11-16 19:35:19 +00008971 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
8972 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +00008973 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +00008974 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
8975 VT.getVectorElementType().getSizeInBits() == 64) ||
8976 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
8977 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +00008978 return SDValue();
8979
8980 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
8981 return SDValue();
8982
8983 // If the zero constant has more than one use then the vector store could be
8984 // better since the constant mov will be amortized and stp q instructions
8985 // should be able to be formed.
8986 if (!StVal.hasOneUse())
8987 return SDValue();
8988
8989 // If the immediate offset of the address operand is too large for the stp
8990 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008991 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
8992 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +00008993 if (Offset < -512 || Offset > 504)
8994 return SDValue();
8995 }
8996
8997 for (int I = 0; I < NumVecElts; ++I) {
8998 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +00008999 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +00009000 return SDValue();
9001 }
Geoff Berry8301c642016-11-16 19:35:19 +00009002
Geoff Berry526c5052016-11-14 19:39:04 +00009003 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9004 // undoing this transformation.
Geoff Berry8301c642016-11-16 19:35:19 +00009005 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9006 ? DAG.getRegister(AArch64::WZR, MVT::i32)
9007 : DAG.getRegister(AArch64::XZR, MVT::i64);
9008 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +00009009}
9010
Tim Northover3b0846e2014-05-24 12:50:23 +00009011/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9012/// value. The load store optimizer pass will merge them to store pair stores.
9013/// This has better performance than a splat of the scalar followed by a split
9014/// vector store. Even if the stores are not merged it is four stores vs a dup,
9015/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009016static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9017 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009018 EVT VT = StVal.getValueType();
9019
9020 // Don't replace floating point stores, they possibly won't be transformed to
9021 // stp because of the store pair suppress pass.
9022 if (VT.isFloatingPoint())
9023 return SDValue();
9024
Tim Northover3b0846e2014-05-24 12:50:23 +00009025 // We can express a splat as store pair(s) for 2 or 4 elements.
9026 unsigned NumVecElts = VT.getVectorNumElements();
9027 if (NumVecElts != 4 && NumVecElts != 2)
9028 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009029
9030 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +00009031 // Make sure that each of the relevant vector element locations are inserted
9032 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9033 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9034 SDValue SplatVal;
9035 for (unsigned I = 0; I < NumVecElts; ++I) {
9036 // Check for insert vector elements.
9037 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +00009038 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009039
9040 // Check that same value is inserted at each vector element.
9041 if (I == 0)
9042 SplatVal = StVal.getOperand(1);
9043 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +00009044 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009045
9046 // Check insert element index.
9047 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9048 if (!CIndex)
9049 return SDValue();
9050 uint64_t IndexVal = CIndex->getZExtValue();
9051 if (IndexVal >= NumVecElts)
9052 return SDValue();
9053 IndexNotInserted.reset(IndexVal);
9054
9055 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009056 }
Geoff Berry25fa4992016-11-11 19:25:20 +00009057 // Check that all vector element locations were inserted to.
9058 if (IndexNotInserted.any())
9059 return SDValue();
9060
Geoff Berry8301c642016-11-16 19:35:19 +00009061 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009062}
9063
Geoff Berry8301c642016-11-16 19:35:19 +00009064static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9065 SelectionDAG &DAG,
9066 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009067 if (!DCI.isBeforeLegalize())
9068 return SDValue();
9069
9070 StoreSDNode *S = cast<StoreSDNode>(N);
9071 if (S->isVolatile())
9072 return SDValue();
9073
Geoff Berry526c5052016-11-14 19:39:04 +00009074 SDValue StVal = S->getValue();
9075 EVT VT = StVal.getValueType();
9076 if (!VT.isVector())
9077 return SDValue();
9078
9079 // If we get a splat of zeros, convert this vector store to a store of
9080 // scalars. They will be merged into store pairs of xzr thereby removing one
9081 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009082 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +00009083 return ReplacedZeroSplat;
9084
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00009085 // FIXME: The logic for deciding if an unaligned store should be split should
9086 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9087 // a call to that function here.
9088
Matthias Braun651cff42016-06-02 18:03:53 +00009089 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00009090 return SDValue();
9091
Sanjay Patel924879a2015-08-04 15:49:57 +00009092 // Don't split at -Oz.
9093 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00009094 return SDValue();
9095
Tim Northover3b0846e2014-05-24 12:50:23 +00009096 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9097 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +00009098 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +00009099 return SDValue();
9100
9101 // Split unaligned 16B stores. They are terrible for performance.
9102 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9103 // extensions can use this to mark that it does not want splitting to happen
9104 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9105 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9106 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9107 S->getAlignment() <= 2)
9108 return SDValue();
9109
9110 // If we get a splat of a scalar convert this vector store to a store of
9111 // scalars. They will be merged into store pairs thereby removing two
9112 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009113 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +00009114 return ReplacedSplat;
9115
9116 SDLoc DL(S);
9117 unsigned NumElts = VT.getVectorNumElements() / 2;
9118 // Split VT into two.
9119 EVT HalfVT =
9120 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9121 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009122 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009123 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009124 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009125 SDValue BasePtr = S->getBasePtr();
9126 SDValue NewST1 =
9127 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00009128 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009129 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009130 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009131 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00009132 S->getPointerInfo(), S->getAlignment(),
9133 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009134}
9135
9136/// Target-specific DAG combine function for post-increment LD1 (lane) and
9137/// post-increment LD1R.
9138static SDValue performPostLD1Combine(SDNode *N,
9139 TargetLowering::DAGCombinerInfo &DCI,
9140 bool IsLaneOp) {
9141 if (DCI.isBeforeLegalizeOps())
9142 return SDValue();
9143
9144 SelectionDAG &DAG = DCI.DAG;
9145 EVT VT = N->getValueType(0);
9146
9147 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9148 SDNode *LD = N->getOperand(LoadIdx).getNode();
9149 // If it is not LOAD, can not do such combine.
9150 if (LD->getOpcode() != ISD::LOAD)
9151 return SDValue();
9152
9153 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9154 EVT MemVT = LoadSDN->getMemoryVT();
9155 // Check if memory operand is the same type as the vector element.
9156 if (MemVT != VT.getVectorElementType())
9157 return SDValue();
9158
9159 // Check if there are other uses. If so, do not combine as it will introduce
9160 // an extra load.
9161 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9162 ++UI) {
9163 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9164 continue;
9165 if (*UI != N)
9166 return SDValue();
9167 }
9168
9169 SDValue Addr = LD->getOperand(1);
9170 SDValue Vector = N->getOperand(0);
9171 // Search for a use of the address operand that is an increment.
9172 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9173 Addr.getNode()->use_end(); UI != UE; ++UI) {
9174 SDNode *User = *UI;
9175 if (User->getOpcode() != ISD::ADD
9176 || UI.getUse().getResNo() != Addr.getResNo())
9177 continue;
9178
9179 // Check that the add is independent of the load. Otherwise, folding it
9180 // would create a cycle.
9181 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9182 continue;
9183 // Also check that add is not used in the vector operand. This would also
9184 // create a cycle.
9185 if (User->isPredecessorOf(Vector.getNode()))
9186 continue;
9187
9188 // If the increment is a constant, it must match the memory ref size.
9189 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9190 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9191 uint32_t IncVal = CInc->getZExtValue();
9192 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9193 if (IncVal != NumBytes)
9194 continue;
9195 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9196 }
9197
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00009198 // Finally, check that the vector doesn't depend on the load.
9199 // Again, this would create a cycle.
9200 // The load depending on the vector is fine, as that's the case for the
9201 // LD1*post we'll eventually generate anyway.
9202 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9203 continue;
9204
Tim Northover3b0846e2014-05-24 12:50:23 +00009205 SmallVector<SDValue, 8> Ops;
9206 Ops.push_back(LD->getOperand(0)); // Chain
9207 if (IsLaneOp) {
9208 Ops.push_back(Vector); // The vector to be inserted
9209 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9210 }
9211 Ops.push_back(Addr);
9212 Ops.push_back(Inc);
9213
9214 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00009215 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00009216 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9217 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9218 MemVT,
9219 LoadSDN->getMemOperand());
9220
9221 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00009222 SDValue NewResults[] = {
9223 SDValue(LD, 0), // The result of load
9224 SDValue(UpdN.getNode(), 2) // Chain
9225 };
Tim Northover3b0846e2014-05-24 12:50:23 +00009226 DCI.CombineTo(LD, NewResults);
9227 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9228 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9229
9230 break;
9231 }
9232 return SDValue();
9233}
9234
Tim Northover339c83e2015-11-10 00:44:23 +00009235/// Simplify \Addr given that the top byte of it is ignored by HW during
9236/// address translation.
9237static bool performTBISimplification(SDValue Addr,
9238 TargetLowering::DAGCombinerInfo &DCI,
9239 SelectionDAG &DAG) {
9240 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9241 APInt KnownZero, KnownOne;
9242 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9243 DCI.isBeforeLegalizeOps());
9244 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9245 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
9246 DCI.CommitTargetLoweringOpt(TLO);
9247 return true;
9248 }
9249 return false;
9250}
9251
9252static SDValue performSTORECombine(SDNode *N,
9253 TargetLowering::DAGCombinerInfo &DCI,
9254 SelectionDAG &DAG,
9255 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +00009256 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00009257 return Split;
9258
9259 if (Subtarget->supportsAddressTopByteIgnored() &&
9260 performTBISimplification(N->getOperand(2), DCI, DAG))
9261 return SDValue(N, 0);
9262
9263 return SDValue();
9264}
9265
9266 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009267/// LoopVectorizer for the across vector reduction. It consists of
9268/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9269/// are reduced, where s is an induction variable from 0 to
9270/// log2(NumVectorElements).
9271static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9272 unsigned Op,
9273 SelectionDAG &DAG) {
9274 EVT VTy = OpV->getOperand(0).getValueType();
9275 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00009276 return SDValue();
9277
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009278 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00009279 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9280 if (NumVecElts != 4)
9281 return SDValue();
9282 } else {
9283 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9284 return SDValue();
9285 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009286
9287 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009288 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00009289 // Iterate over each step of the across vector reduction.
9290 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00009291 SDValue CurOp = PreOp.getOperand(0);
9292 SDValue Shuffle = PreOp.getOperand(1);
9293 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009294 // Try to swap the 1st and 2nd operand as add and min/max instructions
9295 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00009296 CurOp = PreOp.getOperand(1);
9297 Shuffle = PreOp.getOperand(0);
9298 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9299 return SDValue();
9300 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009301
9302 // Check if the input vector is fed by the operator we want to handle,
9303 // except the last step; the very first input vector is not necessarily
9304 // the same operator we are handling.
9305 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9306 return SDValue();
9307
Chad Rosier6c36eff2015-09-03 18:13:57 +00009308 // Check if it forms one step of the across vector reduction.
9309 // E.g.,
9310 // %cur = add %1, %0
9311 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9312 // %pre = add %cur, %shuffle
9313 if (Shuffle.getOperand(0) != CurOp)
9314 return SDValue();
9315
9316 int NumMaskElts = 1 << CurStep;
9317 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9318 // Check mask values in each step.
9319 // We expect the shuffle mask in each step follows a specific pattern
9320 // denoted here by the <M, U> form, where M is a sequence of integers
9321 // starting from NumMaskElts, increasing by 1, and the number integers
9322 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9323 // of undef in U should be NumVecElts - NumMaskElts.
9324 // E.g., for <8 x i16>, mask values in each step should be :
9325 // step 0 : <1,u,u,u,u,u,u,u>
9326 // step 1 : <2,3,u,u,u,u,u,u>
9327 // step 2 : <4,5,6,7,u,u,u,u>
9328 for (int i = 0; i < NumVecElts; ++i)
9329 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9330 (i >= NumMaskElts && !(Mask[i] < 0)))
9331 return SDValue();
9332
9333 PreOp = CurOp;
9334 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009335 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009336 bool IsIntrinsic = false;
9337
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009338 switch (Op) {
9339 default:
9340 llvm_unreachable("Unexpected operator for across vector reduction");
9341 case ISD::ADD:
9342 Opcode = AArch64ISD::UADDV;
9343 break;
9344 case ISD::SMAX:
9345 Opcode = AArch64ISD::SMAXV;
9346 break;
9347 case ISD::UMAX:
9348 Opcode = AArch64ISD::UMAXV;
9349 break;
9350 case ISD::SMIN:
9351 Opcode = AArch64ISD::SMINV;
9352 break;
9353 case ISD::UMIN:
9354 Opcode = AArch64ISD::UMINV;
9355 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009356 case ISD::FMAXNUM:
9357 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9358 IsIntrinsic = true;
9359 break;
9360 case ISD::FMINNUM:
9361 Opcode = Intrinsic::aarch64_neon_fminnmv;
9362 IsIntrinsic = true;
9363 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009364 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009365 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00009366
9367 return IsIntrinsic
9368 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9369 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9370 : DAG.getNode(
9371 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9372 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9373 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009374}
9375
9376/// Target-specific DAG combine for the across vector min/max reductions.
9377/// This function specifically handles the final clean-up step of the vector
9378/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9379/// pattern, which narrows down and finds the final min/max value from all
9380/// elements of the vector.
9381/// For example, for a <16 x i8> vector :
9382/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9383/// %smax0 = smax %arr, svn0
9384/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9385/// %smax1 = smax %smax0, %svn1
9386/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9387/// %smax2 = smax %smax1, svn2
9388/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9389/// %sc = setcc %smax2, %svn3, gt
9390/// %n0 = extract_vector_elt %sc, #0
9391/// %n1 = extract_vector_elt %smax2, #0
9392/// %n2 = extract_vector_elt $smax2, #1
9393/// %result = select %n0, %n1, n2
9394/// becomes :
9395/// %1 = smaxv %0
9396/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009397static SDValue
9398performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9399 const AArch64Subtarget *Subtarget) {
9400 if (!Subtarget->hasNEON())
9401 return SDValue();
9402
9403 SDValue N0 = N->getOperand(0);
9404 SDValue IfTrue = N->getOperand(1);
9405 SDValue IfFalse = N->getOperand(2);
9406
9407 // Check if the SELECT merges up the final result of the min/max
9408 // from a vector.
9409 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9410 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9411 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9412 return SDValue();
9413
9414 // Expect N0 is fed by SETCC.
9415 SDValue SetCC = N0.getOperand(0);
9416 EVT SetCCVT = SetCC.getValueType();
9417 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9418 SetCCVT.getVectorElementType() != MVT::i1)
9419 return SDValue();
9420
9421 SDValue VectorOp = SetCC.getOperand(0);
9422 unsigned Op = VectorOp->getOpcode();
9423 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009424 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9425 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009426 return SDValue();
9427
9428 EVT VTy = VectorOp.getValueType();
9429 if (!VTy.isVector())
9430 return SDValue();
9431
Jun Bum Lim0aace132015-10-09 14:11:25 +00009432 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009433 return SDValue();
9434
Jun Bum Lim0aace132015-10-09 14:11:25 +00009435 EVT EltTy = VTy.getVectorElementType();
9436 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9437 if (EltTy != MVT::f32)
9438 return SDValue();
9439 } else {
9440 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9441 return SDValue();
9442 }
9443
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009444 // Check if extracting from the same vector.
9445 // For example,
9446 // %sc = setcc %vector, %svn1, gt
9447 // %n0 = extract_vector_elt %sc, #0
9448 // %n1 = extract_vector_elt %vector, #0
9449 // %n2 = extract_vector_elt $vector, #1
9450 if (!(VectorOp == IfTrue->getOperand(0) &&
9451 VectorOp == IfFalse->getOperand(0)))
9452 return SDValue();
9453
9454 // Check if the condition code is matched with the operator type.
9455 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9456 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9457 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9458 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009459 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9460 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9461 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9462 CC != ISD::SETGE) ||
9463 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9464 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9465 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009466 return SDValue();
9467
9468 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009469 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009470 return SDValue();
9471
9472 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009473 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009474 return SDValue();
9475
9476 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009477 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009478 return SDValue();
9479
9480 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9481}
9482
9483/// Target-specific DAG combine for the across vector add reduction.
9484/// This function specifically handles the final clean-up step of the vector
9485/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9486/// pattern, which adds all elements of a vector together.
9487/// For example, for a <4 x i32> vector :
9488/// %1 = vector_shuffle %0, <2,3,u,u>
9489/// %2 = add %0, %1
9490/// %3 = vector_shuffle %2, <1,u,u,u>
9491/// %4 = add %2, %3
9492/// %result = extract_vector_elt %4, 0
9493/// becomes :
9494/// %0 = uaddv %0
9495/// %result = extract_vector_elt %0, 0
9496static SDValue
9497performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9498 const AArch64Subtarget *Subtarget) {
9499 if (!Subtarget->hasNEON())
9500 return SDValue();
9501 SDValue N0 = N->getOperand(0);
9502 SDValue N1 = N->getOperand(1);
9503
9504 // Check if the input vector is fed by the ADD.
9505 if (N0->getOpcode() != ISD::ADD)
9506 return SDValue();
9507
9508 // The vector extract idx must constant zero because we only expect the final
9509 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009510 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009511 return SDValue();
9512
9513 EVT VTy = N0.getValueType();
9514 if (!VTy.isVector())
9515 return SDValue();
9516
9517 EVT EltTy = VTy.getVectorElementType();
9518 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9519 return SDValue();
9520
Jun Bum Lim0aace132015-10-09 14:11:25 +00009521 if (VTy.getSizeInBits() < 64)
9522 return SDValue();
9523
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009524 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009525}
9526
Tim Northover3b0846e2014-05-24 12:50:23 +00009527/// Target-specific DAG combine function for NEON load/store intrinsics
9528/// to merge base address updates.
9529static SDValue performNEONPostLDSTCombine(SDNode *N,
9530 TargetLowering::DAGCombinerInfo &DCI,
9531 SelectionDAG &DAG) {
9532 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9533 return SDValue();
9534
9535 unsigned AddrOpIdx = N->getNumOperands() - 1;
9536 SDValue Addr = N->getOperand(AddrOpIdx);
9537
9538 // Search for a use of the address operand that is an increment.
9539 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9540 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9541 SDNode *User = *UI;
9542 if (User->getOpcode() != ISD::ADD ||
9543 UI.getUse().getResNo() != Addr.getResNo())
9544 continue;
9545
9546 // Check that the add is independent of the load/store. Otherwise, folding
9547 // it would create a cycle.
9548 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9549 continue;
9550
9551 // Find the new opcode for the updating load/store.
9552 bool IsStore = false;
9553 bool IsLaneOp = false;
9554 bool IsDupOp = false;
9555 unsigned NewOpc = 0;
9556 unsigned NumVecs = 0;
9557 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9558 switch (IntNo) {
9559 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9560 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9561 NumVecs = 2; break;
9562 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9563 NumVecs = 3; break;
9564 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9565 NumVecs = 4; break;
9566 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9567 NumVecs = 2; IsStore = true; break;
9568 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9569 NumVecs = 3; IsStore = true; break;
9570 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9571 NumVecs = 4; IsStore = true; break;
9572 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9573 NumVecs = 2; break;
9574 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9575 NumVecs = 3; break;
9576 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9577 NumVecs = 4; break;
9578 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9579 NumVecs = 2; IsStore = true; break;
9580 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9581 NumVecs = 3; IsStore = true; break;
9582 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9583 NumVecs = 4; IsStore = true; break;
9584 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9585 NumVecs = 2; IsDupOp = true; break;
9586 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9587 NumVecs = 3; IsDupOp = true; break;
9588 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9589 NumVecs = 4; IsDupOp = true; break;
9590 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9591 NumVecs = 2; IsLaneOp = true; break;
9592 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9593 NumVecs = 3; IsLaneOp = true; break;
9594 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9595 NumVecs = 4; IsLaneOp = true; break;
9596 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9597 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9598 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9599 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9600 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9601 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9602 }
9603
9604 EVT VecTy;
9605 if (IsStore)
9606 VecTy = N->getOperand(2).getValueType();
9607 else
9608 VecTy = N->getValueType(0);
9609
9610 // If the increment is a constant, it must match the memory ref size.
9611 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9612 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9613 uint32_t IncVal = CInc->getZExtValue();
9614 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9615 if (IsLaneOp || IsDupOp)
9616 NumBytes /= VecTy.getVectorNumElements();
9617 if (IncVal != NumBytes)
9618 continue;
9619 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9620 }
9621 SmallVector<SDValue, 8> Ops;
9622 Ops.push_back(N->getOperand(0)); // Incoming chain
9623 // Load lane and store have vector list as input.
9624 if (IsLaneOp || IsStore)
9625 for (unsigned i = 2; i < AddrOpIdx; ++i)
9626 Ops.push_back(N->getOperand(i));
9627 Ops.push_back(Addr); // Base register
9628 Ops.push_back(Inc);
9629
9630 // Return Types.
9631 EVT Tys[6];
9632 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9633 unsigned n;
9634 for (n = 0; n < NumResultVecs; ++n)
9635 Tys[n] = VecTy;
9636 Tys[n++] = MVT::i64; // Type of write back register
9637 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009638 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009639
9640 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9641 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9642 MemInt->getMemoryVT(),
9643 MemInt->getMemOperand());
9644
9645 // Update the uses.
9646 std::vector<SDValue> NewResults;
9647 for (unsigned i = 0; i < NumResultVecs; ++i) {
9648 NewResults.push_back(SDValue(UpdN.getNode(), i));
9649 }
9650 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9651 DCI.CombineTo(N, NewResults);
9652 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9653
9654 break;
9655 }
9656 return SDValue();
9657}
9658
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009659// Checks to see if the value is the prescribed width and returns information
9660// about its extension mode.
9661static
9662bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9663 ExtType = ISD::NON_EXTLOAD;
9664 switch(V.getNode()->getOpcode()) {
9665 default:
9666 return false;
9667 case ISD::LOAD: {
9668 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9669 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9670 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9671 ExtType = LoadNode->getExtensionType();
9672 return true;
9673 }
9674 return false;
9675 }
9676 case ISD::AssertSext: {
9677 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9678 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9679 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9680 ExtType = ISD::SEXTLOAD;
9681 return true;
9682 }
9683 return false;
9684 }
9685 case ISD::AssertZext: {
9686 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9687 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9688 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9689 ExtType = ISD::ZEXTLOAD;
9690 return true;
9691 }
9692 return false;
9693 }
9694 case ISD::Constant:
9695 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009696 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9697 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009698 }
9699 }
9700
9701 return true;
9702}
9703
9704// This function does a whole lot of voodoo to determine if the tests are
9705// equivalent without and with a mask. Essentially what happens is that given a
9706// DAG resembling:
9707//
9708// +-------------+ +-------------+ +-------------+ +-------------+
9709// | Input | | AddConstant | | CompConstant| | CC |
9710// +-------------+ +-------------+ +-------------+ +-------------+
9711// | | | |
9712// V V | +----------+
9713// +-------------+ +----+ | |
9714// | ADD | |0xff| | |
9715// +-------------+ +----+ | |
9716// | | | |
9717// V V | |
9718// +-------------+ | |
9719// | AND | | |
9720// +-------------+ | |
9721// | | |
9722// +-----+ | |
9723// | | |
9724// V V V
9725// +-------------+
9726// | CMP |
9727// +-------------+
9728//
9729// The AND node may be safely removed for some combinations of inputs. In
9730// particular we need to take into account the extension type of the Input,
9731// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9732// width of the input (this can work for any width inputs, the above graph is
9733// specific to 8 bits.
9734//
9735// The specific equations were worked out by generating output tables for each
9736// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9737// problem was simplified by working with 4 bit inputs, which means we only
9738// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9739// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9740// patterns present in both extensions (0,7). For every distinct set of
9741// AddConstant and CompConstants bit patterns we can consider the masked and
9742// unmasked versions to be equivalent if the result of this function is true for
9743// all 16 distinct bit patterns of for the current extension type of Input (w0).
9744//
9745// sub w8, w0, w1
9746// and w10, w8, #0x0f
9747// cmp w8, w2
9748// cset w9, AArch64CC
9749// cmp w10, w2
9750// cset w11, AArch64CC
9751// cmp w9, w11
9752// cset w0, eq
9753// ret
9754//
9755// Since the above function shows when the outputs are equivalent it defines
9756// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9757// would be expensive to run during compiles. The equations below were written
9758// in a test harness that confirmed they gave equivalent outputs to the above
9759// for all inputs function, so they can be used determine if the removal is
9760// legal instead.
9761//
9762// isEquivalentMaskless() is the code for testing if the AND can be removed
9763// factored out of the DAG recognition as the DAG can take several forms.
9764
David Majnemere61e4bf2016-06-21 05:10:24 +00009765static bool isEquivalentMaskless(unsigned CC, unsigned width,
9766 ISD::LoadExtType ExtType, int AddConstant,
9767 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009768 // By being careful about our equations and only writing the in term
9769 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9770 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009771 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009772
9773 // For the purposes of these comparisons sign extending the type is
9774 // equivalent to zero extending the add and displacing it by half the integer
9775 // width. Provided we are careful and make sure our equations are valid over
9776 // the whole range we can just adjust the input and avoid writing equations
9777 // for sign extended inputs.
9778 if (ExtType == ISD::SEXTLOAD)
9779 AddConstant -= (1 << (width-1));
9780
9781 switch(CC) {
9782 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009783 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009784 if ((AddConstant == 0) ||
9785 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9786 (AddConstant >= 0 && CompConstant < 0) ||
9787 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9788 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009789 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009790 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009791 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009792 if ((AddConstant == 0) ||
9793 (AddConstant >= 0 && CompConstant <= 0) ||
9794 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9795 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009796 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009797 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009798 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009799 if ((AddConstant >= 0 && CompConstant < 0) ||
9800 (AddConstant <= 0 && CompConstant >= -1 &&
9801 CompConstant < AddConstant + MaxUInt))
9802 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009803 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009804 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009805 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009806 if ((AddConstant == 0) ||
9807 (AddConstant > 0 && CompConstant <= 0) ||
9808 (AddConstant < 0 && CompConstant <= AddConstant))
9809 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009810 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009811 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009812 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009813 if ((AddConstant >= 0 && CompConstant <= 0) ||
9814 (AddConstant <= 0 && CompConstant >= 0 &&
9815 CompConstant <= AddConstant + MaxUInt))
9816 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009817 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009818 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009819 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009820 if ((AddConstant > 0 && CompConstant < 0) ||
9821 (AddConstant < 0 && CompConstant >= 0 &&
9822 CompConstant < AddConstant + MaxUInt) ||
9823 (AddConstant >= 0 && CompConstant >= 0 &&
9824 CompConstant >= AddConstant) ||
9825 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009826 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009827 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009828 case AArch64CC::VS:
9829 case AArch64CC::VC:
9830 case AArch64CC::AL:
9831 case AArch64CC::NV:
9832 return true;
9833 case AArch64CC::Invalid:
9834 break;
9835 }
9836
9837 return false;
9838}
9839
9840static
9841SDValue performCONDCombine(SDNode *N,
9842 TargetLowering::DAGCombinerInfo &DCI,
9843 SelectionDAG &DAG, unsigned CCIndex,
9844 unsigned CmpIndex) {
9845 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9846 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9847 unsigned CondOpcode = SubsNode->getOpcode();
9848
9849 if (CondOpcode != AArch64ISD::SUBS)
9850 return SDValue();
9851
9852 // There is a SUBS feeding this condition. Is it fed by a mask we can
9853 // use?
9854
9855 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9856 unsigned MaskBits = 0;
9857
9858 if (AndNode->getOpcode() != ISD::AND)
9859 return SDValue();
9860
9861 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9862 uint32_t CNV = CN->getZExtValue();
9863 if (CNV == 255)
9864 MaskBits = 8;
9865 else if (CNV == 65535)
9866 MaskBits = 16;
9867 }
9868
9869 if (!MaskBits)
9870 return SDValue();
9871
9872 SDValue AddValue = AndNode->getOperand(0);
9873
9874 if (AddValue.getOpcode() != ISD::ADD)
9875 return SDValue();
9876
9877 // The basic dag structure is correct, grab the inputs and validate them.
9878
9879 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9880 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9881 SDValue SubsInputValue = SubsNode->getOperand(1);
9882
9883 // The mask is present and the provenance of all the values is a smaller type,
9884 // lets see if the mask is superfluous.
9885
9886 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9887 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9888 return SDValue();
9889
9890 ISD::LoadExtType ExtType;
9891
9892 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9893 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9894 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9895 return SDValue();
9896
9897 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9898 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9899 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9900 return SDValue();
9901
9902 // The AND is not necessary, remove it.
9903
9904 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9905 SubsNode->getValueType(1));
9906 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9907
9908 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9909 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9910
9911 return SDValue(N, 0);
9912}
9913
Tim Northover3b0846e2014-05-24 12:50:23 +00009914// Optimize compare with zero and branch.
9915static SDValue performBRCONDCombine(SDNode *N,
9916 TargetLowering::DAGCombinerInfo &DCI,
9917 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009918 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009919 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009920 SDValue Chain = N->getOperand(0);
9921 SDValue Dest = N->getOperand(1);
9922 SDValue CCVal = N->getOperand(2);
9923 SDValue Cmp = N->getOperand(3);
9924
9925 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9926 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9927 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9928 return SDValue();
9929
9930 unsigned CmpOpc = Cmp.getOpcode();
9931 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9932 return SDValue();
9933
9934 // Only attempt folding if there is only one use of the flag and no use of the
9935 // value.
9936 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9937 return SDValue();
9938
9939 SDValue LHS = Cmp.getOperand(0);
9940 SDValue RHS = Cmp.getOperand(1);
9941
9942 assert(LHS.getValueType() == RHS.getValueType() &&
9943 "Expected the value type to be the same for both operands!");
9944 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9945 return SDValue();
9946
Artyom Skrobov314ee042015-11-25 19:41:11 +00009947 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009948 std::swap(LHS, RHS);
9949
Artyom Skrobov314ee042015-11-25 19:41:11 +00009950 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009951 return SDValue();
9952
9953 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9954 LHS.getOpcode() == ISD::SRL)
9955 return SDValue();
9956
9957 // Fold the compare into the branch instruction.
9958 SDValue BR;
9959 if (CC == AArch64CC::EQ)
9960 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9961 else
9962 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9963
9964 // Do not add new nodes to DAG combiner worklist.
9965 DCI.CombineTo(N, BR, false);
9966
9967 return SDValue();
9968}
9969
Geoff Berry9e934b02016-01-04 18:55:47 +00009970// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9971// as well as whether the test should be inverted. This code is required to
9972// catch these cases (as opposed to standard dag combines) because
9973// AArch64ISD::TBZ is matched during legalization.
9974static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9975 SelectionDAG &DAG) {
9976
9977 if (!Op->hasOneUse())
9978 return Op;
9979
9980 // We don't handle undef/constant-fold cases below, as they should have
9981 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9982 // etc.)
9983
9984 // (tbz (trunc x), b) -> (tbz x, b)
9985 // This case is just here to enable more of the below cases to be caught.
9986 if (Op->getOpcode() == ISD::TRUNCATE &&
9987 Bit < Op->getValueType(0).getSizeInBits()) {
9988 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9989 }
9990
9991 if (Op->getNumOperands() != 2)
9992 return Op;
9993
9994 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9995 if (!C)
9996 return Op;
9997
9998 switch (Op->getOpcode()) {
9999 default:
10000 return Op;
10001
10002 // (tbz (and x, m), b) -> (tbz x, b)
10003 case ISD::AND:
10004 if ((C->getZExtValue() >> Bit) & 1)
10005 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10006 return Op;
10007
10008 // (tbz (shl x, c), b) -> (tbz x, b-c)
10009 case ISD::SHL:
10010 if (C->getZExtValue() <= Bit &&
10011 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10012 Bit = Bit - C->getZExtValue();
10013 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10014 }
10015 return Op;
10016
10017 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10018 case ISD::SRA:
10019 Bit = Bit + C->getZExtValue();
10020 if (Bit >= Op->getValueType(0).getSizeInBits())
10021 Bit = Op->getValueType(0).getSizeInBits() - 1;
10022 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10023
10024 // (tbz (srl x, c), b) -> (tbz x, b+c)
10025 case ISD::SRL:
10026 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10027 Bit = Bit + C->getZExtValue();
10028 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10029 }
10030 return Op;
10031
10032 // (tbz (xor x, -1), b) -> (tbnz x, b)
10033 case ISD::XOR:
10034 if ((C->getZExtValue() >> Bit) & 1)
10035 Invert = !Invert;
10036 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10037 }
10038}
10039
10040// Optimize test single bit zero/non-zero and branch.
10041static SDValue performTBZCombine(SDNode *N,
10042 TargetLowering::DAGCombinerInfo &DCI,
10043 SelectionDAG &DAG) {
10044 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10045 bool Invert = false;
10046 SDValue TestSrc = N->getOperand(1);
10047 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10048
10049 if (TestSrc == NewTestSrc)
10050 return SDValue();
10051
10052 unsigned NewOpc = N->getOpcode();
10053 if (Invert) {
10054 if (NewOpc == AArch64ISD::TBZ)
10055 NewOpc = AArch64ISD::TBNZ;
10056 else {
10057 assert(NewOpc == AArch64ISD::TBNZ);
10058 NewOpc = AArch64ISD::TBZ;
10059 }
10060 }
10061
10062 SDLoc DL(N);
10063 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10064 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10065}
10066
Tim Northover3b0846e2014-05-24 12:50:23 +000010067// vselect (v1i1 setcc) ->
10068// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10069// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10070// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10071// such VSELECT.
10072static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10073 SDValue N0 = N->getOperand(0);
10074 EVT CCVT = N0.getValueType();
10075
10076 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10077 CCVT.getVectorElementType() != MVT::i1)
10078 return SDValue();
10079
10080 EVT ResVT = N->getValueType(0);
10081 EVT CmpVT = N0.getOperand(0).getValueType();
10082 // Only combine when the result type is of the same size as the compared
10083 // operands.
10084 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10085 return SDValue();
10086
10087 SDValue IfTrue = N->getOperand(1);
10088 SDValue IfFalse = N->getOperand(2);
10089 SDValue SetCC =
10090 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10091 N0.getOperand(0), N0.getOperand(1),
10092 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10093 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10094 IfTrue, IfFalse);
10095}
10096
10097/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10098/// the compare-mask instructions rather than going via NZCV, even if LHS and
10099/// RHS are really scalar. This replaces any scalar setcc in the above pattern
10100/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000010101static SDValue performSelectCombine(SDNode *N,
10102 TargetLowering::DAGCombinerInfo &DCI) {
10103 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000010104 SDValue N0 = N->getOperand(0);
10105 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000010106
Ahmed Bougachac004c602015-04-27 21:43:12 +000010107 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000010108 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010109
Ahmed Bougachac004c602015-04-27 21:43:12 +000010110 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10111 // scalar SetCCResultType. We also don't expect vectors, because we assume
10112 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10113 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10114 "Scalar-SETCC feeding SELECT has unexpected result type!");
10115
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010116 // If NumMaskElts == 0, the comparison is larger than select result. The
10117 // largest real NEON comparison is 64-bits per lane, which means the result is
10118 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000010119 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000010120
10121 // Don't try to do this optimization when the setcc itself has i1 operands.
10122 // There are no legal vectors of i1, so this would be pointless.
10123 if (SrcVT == MVT::i1)
10124 return SDValue();
10125
Tim Northover3c0915e2014-08-29 15:34:58 +000010126 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010127 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000010128 return SDValue();
10129
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010130 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010131 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10132
Ahmed Bougacha89bba612015-04-27 21:01:20 +000010133 // Also bail out if the vector CCVT isn't the same size as ResVT.
10134 // This can happen if the SETCC operand size doesn't divide the ResVT size
10135 // (e.g., f64 vs v3f32).
10136 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10137 return SDValue();
10138
Ahmed Bougachac004c602015-04-27 21:43:12 +000010139 // Make sure we didn't create illegal types, if we're not supposed to.
10140 assert(DCI.isBeforeLegalize() ||
10141 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10142
Tim Northover3b0846e2014-05-24 12:50:23 +000010143 // First perform a vector comparison, where lane 0 is the one we're interested
10144 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010145 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010146 SDValue LHS =
10147 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10148 SDValue RHS =
10149 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10150 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10151
10152 // Now duplicate the comparison mask we want across all other lanes.
10153 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000010154 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010155 Mask = DAG.getNode(ISD::BITCAST, DL,
10156 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000010157
10158 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10159}
10160
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010161/// Get rid of unnecessary NVCASTs (that don't change the type).
10162static SDValue performNVCASTCombine(SDNode *N) {
10163 if (N->getValueType(0) == N->getOperand(0).getValueType())
10164 return N->getOperand(0);
10165
10166 return SDValue();
10167}
10168
Tim Northover3b0846e2014-05-24 12:50:23 +000010169SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10170 DAGCombinerInfo &DCI) const {
10171 SelectionDAG &DAG = DCI.DAG;
10172 switch (N->getOpcode()) {
10173 default:
10174 break;
10175 case ISD::ADD:
10176 case ISD::SUB:
10177 return performAddSubLongCombine(N, DCI, DAG);
10178 case ISD::XOR:
10179 return performXorCombine(N, DAG, DCI, Subtarget);
10180 case ISD::MUL:
10181 return performMulCombine(N, DAG, DCI, Subtarget);
10182 case ISD::SINT_TO_FP:
10183 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000010184 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000010185 case ISD::FP_TO_SINT:
10186 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000010187 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000010188 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000010189 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010190 case ISD::OR:
10191 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000010192 case ISD::SRL:
10193 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010194 case ISD::INTRINSIC_WO_CHAIN:
10195 return performIntrinsicCombine(N, DCI, Subtarget);
10196 case ISD::ANY_EXTEND:
10197 case ISD::ZERO_EXTEND:
10198 case ISD::SIGN_EXTEND:
10199 return performExtendCombine(N, DCI, DAG);
10200 case ISD::BITCAST:
10201 return performBitcastCombine(N, DCI, DAG);
10202 case ISD::CONCAT_VECTORS:
10203 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +000010204 case ISD::SELECT: {
10205 SDValue RV = performSelectCombine(N, DCI);
10206 if (!RV.getNode())
10207 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10208 return RV;
10209 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010210 case ISD::VSELECT:
10211 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000010212 case ISD::LOAD:
10213 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10214 return SDValue(N, 0);
10215 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000010216 case ISD::STORE:
10217 return performSTORECombine(N, DCI, DAG, Subtarget);
10218 case AArch64ISD::BRCOND:
10219 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000010220 case AArch64ISD::TBNZ:
10221 case AArch64ISD::TBZ:
10222 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010223 case AArch64ISD::CSEL:
10224 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000010225 case AArch64ISD::DUP:
10226 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010227 case AArch64ISD::NVCAST:
10228 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000010229 case ISD::INSERT_VECTOR_ELT:
10230 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +000010231 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +000010232 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010233 case ISD::INTRINSIC_VOID:
10234 case ISD::INTRINSIC_W_CHAIN:
10235 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10236 case Intrinsic::aarch64_neon_ld2:
10237 case Intrinsic::aarch64_neon_ld3:
10238 case Intrinsic::aarch64_neon_ld4:
10239 case Intrinsic::aarch64_neon_ld1x2:
10240 case Intrinsic::aarch64_neon_ld1x3:
10241 case Intrinsic::aarch64_neon_ld1x4:
10242 case Intrinsic::aarch64_neon_ld2lane:
10243 case Intrinsic::aarch64_neon_ld3lane:
10244 case Intrinsic::aarch64_neon_ld4lane:
10245 case Intrinsic::aarch64_neon_ld2r:
10246 case Intrinsic::aarch64_neon_ld3r:
10247 case Intrinsic::aarch64_neon_ld4r:
10248 case Intrinsic::aarch64_neon_st2:
10249 case Intrinsic::aarch64_neon_st3:
10250 case Intrinsic::aarch64_neon_st4:
10251 case Intrinsic::aarch64_neon_st1x2:
10252 case Intrinsic::aarch64_neon_st1x3:
10253 case Intrinsic::aarch64_neon_st1x4:
10254 case Intrinsic::aarch64_neon_st2lane:
10255 case Intrinsic::aarch64_neon_st3lane:
10256 case Intrinsic::aarch64_neon_st4lane:
10257 return performNEONPostLDSTCombine(N, DCI, DAG);
10258 default:
10259 break;
10260 }
10261 }
10262 return SDValue();
10263}
10264
10265// Check if the return value is used as only a return value, as otherwise
10266// we can't perform a tail-call. In particular, we need to check for
10267// target ISD nodes that are returns and any other "odd" constructs
10268// that the generic analysis code won't necessarily catch.
10269bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10270 SDValue &Chain) const {
10271 if (N->getNumValues() != 1)
10272 return false;
10273 if (!N->hasNUsesOfValue(1, 0))
10274 return false;
10275
10276 SDValue TCChain = Chain;
10277 SDNode *Copy = *N->use_begin();
10278 if (Copy->getOpcode() == ISD::CopyToReg) {
10279 // If the copy has a glue operand, we conservatively assume it isn't safe to
10280 // perform a tail call.
10281 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10282 MVT::Glue)
10283 return false;
10284 TCChain = Copy->getOperand(0);
10285 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10286 return false;
10287
10288 bool HasRet = false;
10289 for (SDNode *Node : Copy->uses()) {
10290 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10291 return false;
10292 HasRet = true;
10293 }
10294
10295 if (!HasRet)
10296 return false;
10297
10298 Chain = TCChain;
10299 return true;
10300}
10301
10302// Return whether the an instruction can potentially be optimized to a tail
10303// call. This will cause the optimizers to attempt to move, or duplicate,
10304// return instructions to help enable tail call optimizations for this
10305// instruction.
10306bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010307 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010308}
10309
10310bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10311 SDValue &Offset,
10312 ISD::MemIndexedMode &AM,
10313 bool &IsInc,
10314 SelectionDAG &DAG) const {
10315 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10316 return false;
10317
10318 Base = Op->getOperand(0);
10319 // All of the indexed addressing mode instructions take a signed
10320 // 9 bit immediate offset.
10321 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000010322 int64_t RHSC = RHS->getSExtValue();
10323 if (Op->getOpcode() == ISD::SUB)
10324 RHSC = -(uint64_t)RHSC;
10325 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000010326 return false;
10327 IsInc = (Op->getOpcode() == ISD::ADD);
10328 Offset = Op->getOperand(1);
10329 return true;
10330 }
10331 return false;
10332}
10333
10334bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10335 SDValue &Offset,
10336 ISD::MemIndexedMode &AM,
10337 SelectionDAG &DAG) const {
10338 EVT VT;
10339 SDValue Ptr;
10340 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10341 VT = LD->getMemoryVT();
10342 Ptr = LD->getBasePtr();
10343 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10344 VT = ST->getMemoryVT();
10345 Ptr = ST->getBasePtr();
10346 } else
10347 return false;
10348
10349 bool IsInc;
10350 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10351 return false;
10352 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10353 return true;
10354}
10355
10356bool AArch64TargetLowering::getPostIndexedAddressParts(
10357 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10358 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10359 EVT VT;
10360 SDValue Ptr;
10361 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10362 VT = LD->getMemoryVT();
10363 Ptr = LD->getBasePtr();
10364 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10365 VT = ST->getMemoryVT();
10366 Ptr = ST->getBasePtr();
10367 } else
10368 return false;
10369
10370 bool IsInc;
10371 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10372 return false;
10373 // Post-indexing updates the base, so it's not a valid transform
10374 // if that's not the same as the load's pointer.
10375 if (Ptr != Base)
10376 return false;
10377 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10378 return true;
10379}
10380
Tim Northoverf8bfe212014-07-18 13:07:05 +000010381static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10382 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010383 SDLoc DL(N);
10384 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010385
10386 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10387 return;
10388
Tim Northoverf8bfe212014-07-18 13:07:05 +000010389 Op = SDValue(
10390 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10391 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010392 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010393 0);
10394 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10395 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10396}
10397
Charlie Turner434d4592015-10-16 15:38:25 +000010398static void ReplaceReductionResults(SDNode *N,
10399 SmallVectorImpl<SDValue> &Results,
10400 SelectionDAG &DAG, unsigned InterOp,
10401 unsigned AcrossOp) {
10402 EVT LoVT, HiVT;
10403 SDValue Lo, Hi;
10404 SDLoc dl(N);
10405 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10406 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10407 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10408 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10409 Results.push_back(SplitVal);
10410}
10411
Tim Northover2f32e7f2016-08-04 19:32:28 +000010412static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10413 SDLoc DL(N);
10414 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10415 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10416 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10417 DAG.getConstant(64, DL, MVT::i64)));
10418 return std::make_pair(Lo, Hi);
10419}
10420
Tim Northovercdf15292016-04-14 17:03:29 +000010421static void ReplaceCMP_SWAP_128Results(SDNode *N,
10422 SmallVectorImpl<SDValue> & Results,
10423 SelectionDAG &DAG) {
10424 assert(N->getValueType(0) == MVT::i128 &&
10425 "AtomicCmpSwap on types less than 128 should be legal");
Tim Northover2f32e7f2016-08-04 19:32:28 +000010426 auto Desired = splitInt128(N->getOperand(2), DAG);
10427 auto New = splitInt128(N->getOperand(3), DAG);
10428 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10429 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000010430 SDNode *CmpSwap = DAG.getMachineNode(
10431 AArch64::CMP_SWAP_128, SDLoc(N),
10432 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10433
10434 MachineFunction &MF = DAG.getMachineFunction();
10435 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10436 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10437 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10438
10439 Results.push_back(SDValue(CmpSwap, 0));
10440 Results.push_back(SDValue(CmpSwap, 1));
10441 Results.push_back(SDValue(CmpSwap, 3));
10442}
10443
Tim Northover3b0846e2014-05-24 12:50:23 +000010444void AArch64TargetLowering::ReplaceNodeResults(
10445 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10446 switch (N->getOpcode()) {
10447 default:
10448 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010449 case ISD::BITCAST:
10450 ReplaceBITCASTResults(N, Results, DAG);
10451 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010452 case AArch64ISD::SADDV:
10453 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10454 return;
10455 case AArch64ISD::UADDV:
10456 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10457 return;
10458 case AArch64ISD::SMINV:
10459 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10460 return;
10461 case AArch64ISD::UMINV:
10462 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10463 return;
10464 case AArch64ISD::SMAXV:
10465 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10466 return;
10467 case AArch64ISD::UMAXV:
10468 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10469 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010470 case ISD::FP_TO_UINT:
10471 case ISD::FP_TO_SINT:
10472 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10473 // Let normal code take care of it by not adding anything to Results.
10474 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010475 case ISD::ATOMIC_CMP_SWAP:
10476 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10477 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010478 }
10479}
10480
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010481bool AArch64TargetLowering::useLoadStackGuardNode() const {
Tim Shene885d5e2016-04-19 19:40:37 +000010482 if (!Subtarget->isTargetAndroid())
10483 return true;
10484 return TargetLowering::useLoadStackGuardNode();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010485}
10486
Sanjay Patel1dd15592015-07-28 23:05:48 +000010487unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010488 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10489 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010490 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010491}
10492
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010493TargetLoweringBase::LegalizeTypeAction
10494AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10495 MVT SVT = VT.getSimpleVT();
10496 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10497 // v4i16, v2i32 instead of to promote.
10498 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10499 || SVT == MVT::v1f32)
10500 return TypeWidenVector;
10501
10502 return TargetLoweringBase::getPreferredVectorAction(VT);
10503}
10504
Robin Morisseted3d48f2014-09-03 21:29:59 +000010505// Loads and stores less than 128-bits are already atomic; ones above that
10506// are doomed anyway, so defer to the default libcall and blame the OS when
10507// things go wrong.
10508bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10509 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10510 return Size == 128;
10511}
10512
10513// Loads and stores less than 128-bits are already atomic; ones above that
10514// are doomed anyway, so defer to the default libcall and blame the OS when
10515// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010516TargetLowering::AtomicExpansionKind
10517AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010518 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010519 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010520}
10521
10522// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010523TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010524AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010525 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010526 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010527}
10528
Ahmed Bougacha52468672015-09-11 17:08:28 +000010529bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10530 AtomicCmpXchgInst *AI) const {
Tim Northovercdf15292016-04-14 17:03:29 +000010531 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10532 // implement cmpxchg without spilling. If the address being exchanged is also
10533 // on the stack and close enough to the spill slot, this can lead to a
10534 // situation where the monitor always gets cleared and the atomic operation
10535 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10536 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010537}
10538
Tim Northover3b0846e2014-05-24 12:50:23 +000010539Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10540 AtomicOrdering Ord) const {
10541 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10542 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010543 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010544
10545 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10546 // intrinsic must return {i64, i64} and we have to recombine them into a
10547 // single i128 here.
10548 if (ValTy->getPrimitiveSizeInBits() == 128) {
10549 Intrinsic::ID Int =
10550 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010551 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000010552
10553 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10554 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10555
10556 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10557 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10558 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10559 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10560 return Builder.CreateOr(
10561 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10562 }
10563
10564 Type *Tys[] = { Addr->getType() };
10565 Intrinsic::ID Int =
10566 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010567 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010568
10569 return Builder.CreateTruncOrBitCast(
10570 Builder.CreateCall(Ldxr, Addr),
10571 cast<PointerType>(Addr->getType())->getElementType());
10572}
10573
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010574void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10575 IRBuilder<> &Builder) const {
10576 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000010577 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010578}
10579
Tim Northover3b0846e2014-05-24 12:50:23 +000010580Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10581 Value *Val, Value *Addr,
10582 AtomicOrdering Ord) const {
10583 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010584 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010585
10586 // Since the intrinsics must have legal type, the i128 intrinsics take two
10587 // parameters: "i64, i64". We must marshal Val into the appropriate form
10588 // before the call.
10589 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10590 Intrinsic::ID Int =
10591 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10592 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10593 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10594
10595 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10596 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10597 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010598 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010599 }
10600
10601 Intrinsic::ID Int =
10602 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10603 Type *Tys[] = { Addr->getType() };
10604 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10605
David Blaikieff6409d2015-05-18 22:13:54 +000010606 return Builder.CreateCall(Stxr,
10607 {Builder.CreateZExtOrBitCast(
10608 Val, Stxr->getFunctionType()->getParamType(0)),
10609 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010610}
Tim Northover3c55cca2014-11-27 21:02:42 +000010611
10612bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10613 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10614 return Ty->isArrayTy();
10615}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010616
10617bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10618 EVT) const {
10619 return false;
10620}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010621
Tim Shen00127562016-04-08 21:26:31 +000010622Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010623 if (!Subtarget->isTargetAndroid())
Tim Shen00127562016-04-08 21:26:31 +000010624 return TargetLowering::getIRStackGuard(IRB);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010625
10626 // Android provides a fixed TLS slot for the stack cookie. See the definition
10627 // of TLS_SLOT_STACK_GUARD in
10628 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10629 const unsigned TlsOffset = 0x28;
10630 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10631 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010632 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010633 return IRB.CreatePointerCast(
10634 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10635 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10636}
10637
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010638Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10639 if (!Subtarget->isTargetAndroid())
10640 return TargetLowering::getSafeStackPointerLocation(IRB);
10641
10642 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10643 // definition of TLS_SLOT_SAFESTACK in
10644 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10645 const unsigned TlsOffset = 0x48;
10646 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10647 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010648 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010649 return IRB.CreatePointerCast(
10650 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10651 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10652}
Manman Rencbe4f942015-12-16 21:04:19 +000010653
10654void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10655 // Update IsSplitCSR in AArch64unctionInfo.
10656 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10657 AFI->setIsSplitCSR(true);
10658}
10659
10660void AArch64TargetLowering::insertCopiesSplitCSR(
10661 MachineBasicBlock *Entry,
10662 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10663 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10664 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10665 if (!IStart)
10666 return;
10667
10668 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10669 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010670 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010671 for (const MCPhysReg *I = IStart; *I; ++I) {
10672 const TargetRegisterClass *RC = nullptr;
10673 if (AArch64::GPR64RegClass.contains(*I))
10674 RC = &AArch64::GPR64RegClass;
10675 else if (AArch64::FPR64RegClass.contains(*I))
10676 RC = &AArch64::FPR64RegClass;
10677 else
10678 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10679
10680 unsigned NewVR = MRI->createVirtualRegister(RC);
10681 // Create copy from CSR to a virtual register.
10682 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10683 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10684 // nounwind. If we want to generalize this later, we may need to emit
10685 // CFI pseudo-instructions.
10686 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10687 Attribute::NoUnwind) &&
10688 "Function should be nounwind in insertCopiesSplitCSR!");
10689 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010690 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010691 .addReg(*I);
10692
Manman Ren4632e8e2016-01-15 20:13:28 +000010693 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010694 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010695 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10696 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010697 .addReg(NewVR);
10698 }
10699}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010700
10701bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10702 // Integer division on AArch64 is expensive. However, when aggressively
10703 // optimizing for code size, we prefer to use a div instruction, as it is
10704 // usually smaller than the alternative sequence.
10705 // The exception to this is vector division. Since AArch64 doesn't have vector
10706 // integer division, leaving the division as-is is a loss even in terms of
10707 // size, because it will have to be scalarized, while the alternative code
10708 // sequence can be performed in vector form.
10709 bool OptSize =
10710 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10711 return OptSize && !VT.isVector();
10712}