blob: f2df1330a5b4fb65f6660003bb9f65d66d8779c4 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tim Northover3b0846e2014-05-24 12:50:23 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AArch64TargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
Adhemerval Zanellaa3cefa52019-03-18 18:45:57 +000013#include "AArch64ExpandImm.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/STLExtras.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000026#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000027#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000028#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +000032#include "llvm/Analysis/VectorUtils.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000033#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000034#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000035#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000036#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000038#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000039#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000041#include "llvm/CodeGen/RuntimeLibcalls.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000044#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000045#include "llvm/CodeGen/TargetInstrInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000046#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000047#include "llvm/IR/Attributes.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000052#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000054#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000055#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000056#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Instructions.h"
Florian Hahn3b251962019-02-05 10:27:40 +000058#include "llvm/IR/IntrinsicInst.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000059#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000060#include "llvm/IR/Module.h"
61#include "llvm/IR/OperandTraits.h"
Florian Hahn3b251962019-02-05 10:27:40 +000062#include "llvm/IR/PatternMatch.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000063#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000064#include "llvm/IR/Use.h"
65#include "llvm/IR/Value.h"
66#include "llvm/MC/MCRegisterInfo.h"
67#include "llvm/Support/Casting.h"
68#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000069#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000070#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000071#include "llvm/Support/Debug.h"
72#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000073#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000074#include "llvm/Support/MachineValueType.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000075#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000076#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000077#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000078#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000079#include <algorithm>
80#include <bitset>
81#include <cassert>
82#include <cctype>
83#include <cstdint>
84#include <cstdlib>
85#include <iterator>
86#include <limits>
87#include <tuple>
88#include <utility>
89#include <vector>
90
Tim Northover3b0846e2014-05-24 12:50:23 +000091using namespace llvm;
Florian Hahn3b251962019-02-05 10:27:40 +000092using namespace llvm::PatternMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +000093
94#define DEBUG_TYPE "aarch64-lower"
95
96STATISTIC(NumTailCalls, "Number of tail calls");
97STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000098STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +000099
Tim Northover3b0846e2014-05-24 12:50:23 +0000100static cl::opt<bool>
101EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +0000102 cl::desc("Allow AArch64 SLI/SRI formation"),
103 cl::init(false));
104
105// FIXME: The necessary dtprel relocations don't seem to be supported
106// well in the GNU bfd and gold linkers at the moment. Therefore, by
107// default, for now, fall back to GeneralDynamic code generation.
108cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109 "aarch64-elf-ldtls-generation", cl::Hidden,
110 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000112
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000113static cl::opt<bool>
114EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
115 cl::desc("Enable AArch64 logical imm instruction "
116 "optimization"),
117 cl::init(true));
118
Matthias Braunaf7d7702015-07-16 20:02:37 +0000119/// Value type used for condition codes.
120static const MVT MVT_CC = MVT::i32;
121
Eric Christopher905f12d2015-01-29 00:19:42 +0000122AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
123 const AArch64Subtarget &STI)
124 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000125 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
126 // we have to make something up. Arbitrarily, choose ZeroOrOne.
127 setBooleanContents(ZeroOrOneBooleanContent);
128 // When comparing vectors the result sets the different elements in the
129 // vector to all-one or all-zero.
130 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
131
132 // Set up the register classes.
133 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
134 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
135
136 if (Subtarget->hasFPARMv8()) {
137 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
138 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
139 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
140 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
141 }
142
143 if (Subtarget->hasNEON()) {
144 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
145 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
146 // Someone set us up the NEON.
147 addDRTypeForNEON(MVT::v2f32);
148 addDRTypeForNEON(MVT::v8i8);
149 addDRTypeForNEON(MVT::v4i16);
150 addDRTypeForNEON(MVT::v2i32);
151 addDRTypeForNEON(MVT::v1i64);
152 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000153 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000154
155 addQRTypeForNEON(MVT::v4f32);
156 addQRTypeForNEON(MVT::v2f64);
157 addQRTypeForNEON(MVT::v16i8);
158 addQRTypeForNEON(MVT::v8i16);
159 addQRTypeForNEON(MVT::v4i32);
160 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000161 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000162 }
163
Cullen Rhodes2a481762019-08-05 13:44:10 +0000164 if (Subtarget->hasSVE()) {
165 // Add legal sve predicate types
166 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
167 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
168 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
169 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
170
171 // Add legal sve data types
172 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
173 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
174 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
175 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
176
177 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
178 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
179 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
180 addRegisterClass(MVT::nxv1f32, &AArch64::ZPRRegClass);
181 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
182 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
183 addRegisterClass(MVT::nxv1f64, &AArch64::ZPRRegClass);
184 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
185 }
186
Tim Northover3b0846e2014-05-24 12:50:23 +0000187 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000188 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000189
190 // Provide all sorts of operation actions
191 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
192 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
193 setOperationAction(ISD::SETCC, MVT::i32, Custom);
194 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000195 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000196 setOperationAction(ISD::SETCC, MVT::f32, Custom);
197 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000198 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
199 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000200 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
201 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
202 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000203 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000204 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
205 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
206 setOperationAction(ISD::SELECT, MVT::i32, Custom);
207 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000208 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000209 setOperationAction(ISD::SELECT, MVT::f32, Custom);
210 setOperationAction(ISD::SELECT, MVT::f64, Custom);
211 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
212 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000213 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000214 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
215 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
Tim Northover1c353412018-10-24 20:19:09 +0000216 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000217 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
218
219 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
220 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
221 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
222
223 setOperationAction(ISD::FREM, MVT::f32, Expand);
224 setOperationAction(ISD::FREM, MVT::f64, Expand);
225 setOperationAction(ISD::FREM, MVT::f80, Expand);
226
Amara Emersone27d5012018-04-10 19:01:58 +0000227 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
228
Tim Northover3b0846e2014-05-24 12:50:23 +0000229 // Custom lowering hooks are needed for XOR
230 // to fold it into CSINC/CSINV.
231 setOperationAction(ISD::XOR, MVT::i32, Custom);
232 setOperationAction(ISD::XOR, MVT::i64, Custom);
233
234 // Virtually no operation on f128 is legal, but LLVM can't expand them when
235 // there's a valid register class, so we need custom operations in most cases.
236 setOperationAction(ISD::FABS, MVT::f128, Expand);
237 setOperationAction(ISD::FADD, MVT::f128, Custom);
238 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
239 setOperationAction(ISD::FCOS, MVT::f128, Expand);
240 setOperationAction(ISD::FDIV, MVT::f128, Custom);
241 setOperationAction(ISD::FMA, MVT::f128, Expand);
242 setOperationAction(ISD::FMUL, MVT::f128, Custom);
243 setOperationAction(ISD::FNEG, MVT::f128, Expand);
244 setOperationAction(ISD::FPOW, MVT::f128, Expand);
245 setOperationAction(ISD::FREM, MVT::f128, Expand);
246 setOperationAction(ISD::FRINT, MVT::f128, Expand);
247 setOperationAction(ISD::FSIN, MVT::f128, Expand);
248 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
249 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
250 setOperationAction(ISD::FSUB, MVT::f128, Custom);
251 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
252 setOperationAction(ISD::SETCC, MVT::f128, Custom);
253 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
254 setOperationAction(ISD::SELECT, MVT::f128, Custom);
255 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
256 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
257
258 // Lowering for many of the conversions is actually specified by the non-f128
259 // type. The LowerXXX function will be trivial when f128 isn't involved.
260 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
261 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
262 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
263 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
264 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
265 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
266 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
267 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
268 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
269 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
270 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
271 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
272 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
273 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
274
275 // Variable arguments.
276 setOperationAction(ISD::VASTART, MVT::Other, Custom);
277 setOperationAction(ISD::VAARG, MVT::Other, Custom);
278 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
279 setOperationAction(ISD::VAEND, MVT::Other, Expand);
280
281 // Variable-sized objects.
282 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
283 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000284
285 if (Subtarget->isTargetWindows())
286 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
287 else
288 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000289
Tim Northover3b0846e2014-05-24 12:50:23 +0000290 // Constant pool entries
291 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
292
293 // BlockAddress
294 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
295
296 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
297 setOperationAction(ISD::ADDC, MVT::i32, Custom);
298 setOperationAction(ISD::ADDE, MVT::i32, Custom);
299 setOperationAction(ISD::SUBC, MVT::i32, Custom);
300 setOperationAction(ISD::SUBE, MVT::i32, Custom);
301 setOperationAction(ISD::ADDC, MVT::i64, Custom);
302 setOperationAction(ISD::ADDE, MVT::i64, Custom);
303 setOperationAction(ISD::SUBC, MVT::i64, Custom);
304 setOperationAction(ISD::SUBE, MVT::i64, Custom);
305
306 // AArch64 lacks both left-rotate and popcount instructions.
307 setOperationAction(ISD::ROTL, MVT::i32, Expand);
308 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000309 for (MVT VT : MVT::vector_valuetypes()) {
310 setOperationAction(ISD::ROTL, VT, Expand);
311 setOperationAction(ISD::ROTR, VT, Expand);
312 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000313
314 // AArch64 doesn't have {U|S}MUL_LOHI.
315 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
316 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
317
Tim Northover3b0846e2014-05-24 12:50:23 +0000318 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
319 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
320
321 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
322 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000323 for (MVT VT : MVT::vector_valuetypes()) {
324 setOperationAction(ISD::SDIVREM, VT, Expand);
325 setOperationAction(ISD::UDIVREM, VT, Expand);
326 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000327 setOperationAction(ISD::SREM, MVT::i32, Expand);
328 setOperationAction(ISD::SREM, MVT::i64, Expand);
329 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
330 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
331 setOperationAction(ISD::UREM, MVT::i32, Expand);
332 setOperationAction(ISD::UREM, MVT::i64, Expand);
333
334 // Custom lower Add/Sub/Mul with overflow.
335 setOperationAction(ISD::SADDO, MVT::i32, Custom);
336 setOperationAction(ISD::SADDO, MVT::i64, Custom);
337 setOperationAction(ISD::UADDO, MVT::i32, Custom);
338 setOperationAction(ISD::UADDO, MVT::i64, Custom);
339 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
340 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
341 setOperationAction(ISD::USUBO, MVT::i32, Custom);
342 setOperationAction(ISD::USUBO, MVT::i64, Custom);
343 setOperationAction(ISD::SMULO, MVT::i32, Custom);
344 setOperationAction(ISD::SMULO, MVT::i64, Custom);
345 setOperationAction(ISD::UMULO, MVT::i32, Custom);
346 setOperationAction(ISD::UMULO, MVT::i64, Custom);
347
348 setOperationAction(ISD::FSIN, MVT::f32, Expand);
349 setOperationAction(ISD::FSIN, MVT::f64, Expand);
350 setOperationAction(ISD::FCOS, MVT::f32, Expand);
351 setOperationAction(ISD::FCOS, MVT::f64, Expand);
352 setOperationAction(ISD::FPOW, MVT::f32, Expand);
353 setOperationAction(ISD::FPOW, MVT::f64, Expand);
354 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
355 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000356 if (Subtarget->hasFullFP16())
357 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
358 else
359 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000360
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000361 setOperationAction(ISD::FREM, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000362 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
363 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000364 setOperationAction(ISD::FPOW, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000365 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
366 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000367 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000368 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
369 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000370 setOperationAction(ISD::FCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000371 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
372 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000373 setOperationAction(ISD::FSIN, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000374 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
375 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000376 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000377 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
378 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000379 setOperationAction(ISD::FEXP, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000380 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
381 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000382 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000383 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
384 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000385 setOperationAction(ISD::FLOG, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000386 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
387 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000388 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000389 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
390 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000391 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000392 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
393 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000394
395 if (!Subtarget->hasFullFP16()) {
396 setOperationAction(ISD::SELECT, MVT::f16, Promote);
397 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
398 setOperationAction(ISD::SETCC, MVT::f16, Promote);
399 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
400 setOperationAction(ISD::FADD, MVT::f16, Promote);
401 setOperationAction(ISD::FSUB, MVT::f16, Promote);
402 setOperationAction(ISD::FMUL, MVT::f16, Promote);
403 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000404 setOperationAction(ISD::FMA, MVT::f16, Promote);
405 setOperationAction(ISD::FNEG, MVT::f16, Promote);
406 setOperationAction(ISD::FABS, MVT::f16, Promote);
407 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
408 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000409 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
410 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
411 setOperationAction(ISD::FRINT, MVT::f16, Promote);
412 setOperationAction(ISD::FROUND, MVT::f16, Promote);
413 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
414 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
415 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Thomas Lively30f1d692018-10-24 22:49:55 +0000416 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
417 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000418
419 // promote v4f16 to v4f32 when that is known to be safe.
420 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
421 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
422 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
423 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
424 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
425 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
426 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
427 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
428 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
429 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
430 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
431 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
432
433 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
434 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
435 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
436 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
437 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
438 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
439 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
440 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
441 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
442 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
443 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
444 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
445 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
446 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
447 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000448
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000449 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
450 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
451 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
452 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
453 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
454 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
455 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
456 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
457 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
458 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
459 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
460 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
461 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
462 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
463 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
464 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
465 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
466 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
467 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
468 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
469 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000470
Tim Northover3b0846e2014-05-24 12:50:23 +0000471 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000472 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000473 setOperationAction(ISD::FFLOOR, Ty, Legal);
474 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
475 setOperationAction(ISD::FCEIL, Ty, Legal);
476 setOperationAction(ISD::FRINT, Ty, Legal);
477 setOperationAction(ISD::FTRUNC, Ty, Legal);
478 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000479 setOperationAction(ISD::FMINNUM, Ty, Legal);
480 setOperationAction(ISD::FMAXNUM, Ty, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000481 setOperationAction(ISD::FMINIMUM, Ty, Legal);
482 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
Adhemerval Zanella2d28db62019-05-16 13:30:18 +0000483 setOperationAction(ISD::LROUND, Ty, Legal);
484 setOperationAction(ISD::LLROUND, Ty, Legal);
Adhemerval Zanella34d8daa2019-05-28 21:04:29 +0000485 setOperationAction(ISD::LRINT, Ty, Legal);
486 setOperationAction(ISD::LLRINT, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000487 }
488
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000489 if (Subtarget->hasFullFP16()) {
490 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
491 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
492 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
493 setOperationAction(ISD::FRINT, MVT::f16, Legal);
494 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
495 setOperationAction(ISD::FROUND, MVT::f16, Legal);
496 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
497 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000498 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
499 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000500 }
501
Tim Northover3b0846e2014-05-24 12:50:23 +0000502 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
503
Tim Northover70666e72018-06-20 12:09:01 +0000504 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
505
Tim Northovercdf15292016-04-14 17:03:29 +0000506 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000507 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000509 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000511
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000512 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
513 // This requires the Performance Monitors extension.
514 if (Subtarget->hasPerfMon())
515 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
516
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000517 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
518 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
519 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000520 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
521 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
522 } else {
523 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
524 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
525 }
526
Juergen Ributzka23266502014-12-10 19:43:32 +0000527 // Make floating-point constants legal for the large code model, so they don't
528 // become loads from the constant pool.
529 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
530 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
531 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
532 }
533
Tim Northover3b0846e2014-05-24 12:50:23 +0000534 // AArch64 does not have floating-point extending loads, i1 sign-extending
535 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000536 for (MVT VT : MVT::fp_valuetypes()) {
537 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
538 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
539 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
540 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
541 }
542 for (MVT VT : MVT::integer_valuetypes())
543 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
544
Tim Northover3b0846e2014-05-24 12:50:23 +0000545 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
546 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
547 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
548 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
549 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
550 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
551 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000552
553 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
554 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
555
Tim Northover3b0846e2014-05-24 12:50:23 +0000556 // Indexed loads and stores are supported.
557 for (unsigned im = (unsigned)ISD::PRE_INC;
558 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
559 setIndexedLoadAction(im, MVT::i8, Legal);
560 setIndexedLoadAction(im, MVT::i16, Legal);
561 setIndexedLoadAction(im, MVT::i32, Legal);
562 setIndexedLoadAction(im, MVT::i64, Legal);
563 setIndexedLoadAction(im, MVT::f64, Legal);
564 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000565 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000566 setIndexedStoreAction(im, MVT::i8, Legal);
567 setIndexedStoreAction(im, MVT::i16, Legal);
568 setIndexedStoreAction(im, MVT::i32, Legal);
569 setIndexedStoreAction(im, MVT::i64, Legal);
570 setIndexedStoreAction(im, MVT::f64, Legal);
571 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000572 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000573 }
574
575 // Trap.
576 setOperationAction(ISD::TRAP, MVT::Other, Legal);
Tom Tan7ecb5142019-06-21 23:38:05 +0000577 if (Subtarget->isTargetWindows())
578 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000579
580 // We combine OR nodes for bitfield operations.
581 setTargetDAGCombine(ISD::OR);
Nikita Popov1a261442019-03-15 21:04:34 +0000582 // Try to create BICs for vector ANDs.
583 setTargetDAGCombine(ISD::AND);
Tim Northover3b0846e2014-05-24 12:50:23 +0000584
585 // Vector add and sub nodes may conceal a high-half opportunity.
586 // Also, try to fold ADD into CSINC/CSINV..
587 setTargetDAGCombine(ISD::ADD);
588 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000589 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000590 setTargetDAGCombine(ISD::XOR);
591 setTargetDAGCombine(ISD::SINT_TO_FP);
592 setTargetDAGCombine(ISD::UINT_TO_FP);
593
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000594 setTargetDAGCombine(ISD::FP_TO_SINT);
595 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000596 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000597
Tim Northover3b0846e2014-05-24 12:50:23 +0000598 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
599
600 setTargetDAGCombine(ISD::ANY_EXTEND);
601 setTargetDAGCombine(ISD::ZERO_EXTEND);
602 setTargetDAGCombine(ISD::SIGN_EXTEND);
603 setTargetDAGCombine(ISD::BITCAST);
604 setTargetDAGCombine(ISD::CONCAT_VECTORS);
605 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000606 if (Subtarget->supportsAddressTopByteIgnored())
607 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000608
609 setTargetDAGCombine(ISD::MUL);
610
611 setTargetDAGCombine(ISD::SELECT);
612 setTargetDAGCombine(ISD::VSELECT);
613
614 setTargetDAGCombine(ISD::INTRINSIC_VOID);
615 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
616 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
617
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000618 setTargetDAGCombine(ISD::GlobalAddress);
619
Evandro Menezesf8425342018-05-29 15:58:50 +0000620 // In case of strict alignment, avoid an excessive number of byte wide stores.
621 MaxStoresPerMemsetOptSize = 8;
622 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
623 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000624
Evandro Menezesf8425342018-05-29 15:58:50 +0000625 MaxGluedStoresPerMemcpy = 4;
626 MaxStoresPerMemcpyOptSize = 4;
627 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
628 ? MaxStoresPerMemcpyOptSize : 16;
629
630 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000631
Evandro Menezesa005c1a2019-08-05 18:09:14 +0000632 MaxLoadsPerMemcmpOptSize = 4;
633 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
634 ? MaxLoadsPerMemcmpOptSize : 8;
635
Tim Northover3b0846e2014-05-24 12:50:23 +0000636 setStackPointerRegisterToSaveRestore(AArch64::SP);
637
638 setSchedulingPreference(Sched::Hybrid);
639
Quentin Colombet6843ac42015-03-31 20:52:32 +0000640 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000641
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000642 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000643 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000644 // Set preferred alignments.
645 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
646 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000647
Evandro Menezese45de8a2016-09-26 15:32:33 +0000648 // Only change the limit for entries in a jump table if specified by
Evandro Menezes0f797b82019-03-29 17:28:11 +0000649 // the sub target, but not at the command line.
Evandro Menezese45de8a2016-09-26 15:32:33 +0000650 unsigned MaxJT = STI.getMaximumJumpTableSize();
Evandro Menezes0f797b82019-03-29 17:28:11 +0000651 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
Evandro Menezese45de8a2016-09-26 15:32:33 +0000652 setMaximumJumpTableSize(MaxJT);
653
Tim Northover3b0846e2014-05-24 12:50:23 +0000654 setHasExtractBitsInsn(true);
655
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000656 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
657
Tim Northover3b0846e2014-05-24 12:50:23 +0000658 if (Subtarget->hasNEON()) {
659 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
660 // silliness like this:
661 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
662 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
663 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
664 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
665 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
666 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
667 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
668 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
669 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
670 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
671 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
672 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
673 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
674 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
675 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
676 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
677 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
678 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
679 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
680 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
681 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
682 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
683 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
684 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
685 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
686
687 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
688 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
689 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
690 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
691 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
692
693 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
694
695 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
696 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000697 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
698 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000699 // i8 vector elements also need promotion to i32 for v8i8
Craig Toppera4f99972018-01-01 19:21:35 +0000700 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
701 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000702 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
703 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
704 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
705 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
706 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000707 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
708 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
709 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
710 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000711
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000712 if (Subtarget->hasFullFP16()) {
713 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
714 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
715 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
716 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
717 } else {
718 // when AArch64 doesn't have fullfp16 support, promote the input
719 // to i32 first.
720 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
721 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
722 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
723 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
724 }
725
Craig Topperc5551bf2016-04-26 05:26:51 +0000726 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
727 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
728
Tim Northover3b0846e2014-05-24 12:50:23 +0000729 // AArch64 doesn't have MUL.2d:
730 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000731 // Custom handling for some quad-vector types to detect MULL.
732 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
733 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
734 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
735
Amara Emersonc9916d72017-05-16 21:29:22 +0000736 // Vector reductions
Nikita Popovaa7cfa72019-03-11 20:22:13 +0000737 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
738 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
Amara Emersonc9916d72017-05-16 21:29:22 +0000739 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
740 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
741 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
742 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
743 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
744 }
Nikita Popovaa7cfa72019-03-11 20:22:13 +0000745 for (MVT VT : { MVT::v4f16, MVT::v2f32,
746 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
Amara Emersonc9916d72017-05-16 21:29:22 +0000747 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
748 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
749 }
750
Tim Northover3b0846e2014-05-24 12:50:23 +0000751 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
752 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
753 // Likewise, narrowing and extending vector loads/stores aren't handled
754 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000755 for (MVT VT : MVT::vector_valuetypes()) {
756 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000757
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000758 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
Craig Topper129d5292018-11-29 19:36:17 +0000759 setOperationAction(ISD::MULHS, VT, Legal);
760 setOperationAction(ISD::MULHU, VT, Legal);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000761 } else {
762 setOperationAction(ISD::MULHS, VT, Expand);
763 setOperationAction(ISD::MULHU, VT, Expand);
764 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000765 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000766 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000767
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000768 setOperationAction(ISD::BSWAP, VT, Expand);
Nikita Popova3be17e2019-02-12 18:55:53 +0000769 setOperationAction(ISD::CTTZ, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000770
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000771 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000772 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000773 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
774 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
775 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
776 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000777 }
778
779 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000780 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000781 setOperationAction(ISD::FFLOOR, Ty, Legal);
782 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
783 setOperationAction(ISD::FCEIL, Ty, Legal);
784 setOperationAction(ISD::FRINT, Ty, Legal);
785 setOperationAction(ISD::FTRUNC, Ty, Legal);
786 setOperationAction(ISD::FROUND, Ty, Legal);
787 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000788
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +0000789 if (Subtarget->hasFullFP16()) {
790 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
791 setOperationAction(ISD::FFLOOR, Ty, Legal);
792 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
793 setOperationAction(ISD::FCEIL, Ty, Legal);
794 setOperationAction(ISD::FRINT, Ty, Legal);
795 setOperationAction(ISD::FTRUNC, Ty, Legal);
796 setOperationAction(ISD::FROUND, Ty, Legal);
797 }
798 }
799
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000800 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000801 }
James Molloyf089ab72014-08-06 10:42:18 +0000802
Matthias Braun651cff42016-06-02 18:03:53 +0000803 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000804}
805
Craig Topper18e69f42016-04-15 06:20:21 +0000806void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000807 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000808
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000809 if (VT.isFloatingPoint()) {
810 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
811 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
812 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000813 }
814
815 // Mark vector float intrinsics as expand.
816 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000817 setOperationAction(ISD::FSIN, VT, Expand);
818 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000819 setOperationAction(ISD::FPOW, VT, Expand);
820 setOperationAction(ISD::FLOG, VT, Expand);
821 setOperationAction(ISD::FLOG2, VT, Expand);
822 setOperationAction(ISD::FLOG10, VT, Expand);
823 setOperationAction(ISD::FEXP, VT, Expand);
824 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000825
826 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000827 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000828 }
829
Craig Topper18e69f42016-04-15 06:20:21 +0000830 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
831 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
832 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
833 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
834 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
835 setOperationAction(ISD::SRA, VT, Custom);
836 setOperationAction(ISD::SRL, VT, Custom);
837 setOperationAction(ISD::SHL, VT, Custom);
Craig Topper18e69f42016-04-15 06:20:21 +0000838 setOperationAction(ISD::OR, VT, Custom);
839 setOperationAction(ISD::SETCC, VT, Custom);
840 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000841
Craig Topper18e69f42016-04-15 06:20:21 +0000842 setOperationAction(ISD::SELECT, VT, Expand);
843 setOperationAction(ISD::SELECT_CC, VT, Expand);
844 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000845 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000846 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000847
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000848 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000849 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000850 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000851
Craig Topper18e69f42016-04-15 06:20:21 +0000852 setOperationAction(ISD::UDIV, VT, Expand);
853 setOperationAction(ISD::SDIV, VT, Expand);
854 setOperationAction(ISD::UREM, VT, Expand);
855 setOperationAction(ISD::SREM, VT, Expand);
856 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000857
Craig Topper18e69f42016-04-15 06:20:21 +0000858 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
859 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000860
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000861 if (!VT.isFloatingPoint())
862 setOperationAction(ISD::ABS, VT, Legal);
863
Hal Finkelcd8664c2015-12-11 23:11:52 +0000864 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000865 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000866 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000867 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000868
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000869 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
870 if (VT.isFloatingPoint() &&
871 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000872 for (unsigned Opcode :
873 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000874 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000875
Tim Northover3b0846e2014-05-24 12:50:23 +0000876 if (Subtarget->isLittleEndian()) {
877 for (unsigned im = (unsigned)ISD::PRE_INC;
878 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000879 setIndexedLoadAction(im, VT, Legal);
880 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000881 }
882 }
883}
884
885void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
886 addRegisterClass(VT, &AArch64::FPR64RegClass);
887 addTypeForNEON(VT, MVT::v2i32);
888}
889
890void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
891 addRegisterClass(VT, &AArch64::FPR128RegClass);
892 addTypeForNEON(VT, MVT::v4i32);
893}
894
Mehdi Amini44ede332015-07-09 02:09:04 +0000895EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
896 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000897 if (!VT.isVector())
898 return MVT::i32;
899 return VT.changeVectorElementTypeToInteger();
900}
901
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000902static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
903 const APInt &Demanded,
904 TargetLowering::TargetLoweringOpt &TLO,
905 unsigned NewOpc) {
906 uint64_t OldImm = Imm, NewImm, Enc;
907 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
908
909 // Return if the immediate is already all zeros, all ones, a bimm32 or a
910 // bimm64.
911 if (Imm == 0 || Imm == Mask ||
912 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
913 return false;
914
915 unsigned EltSize = Size;
916 uint64_t DemandedBits = Demanded.getZExtValue();
917
918 // Clear bits that are not demanded.
919 Imm &= DemandedBits;
920
921 while (true) {
922 // The goal here is to set the non-demanded bits in a way that minimizes
923 // the number of switching between 0 and 1. In order to achieve this goal,
924 // we set the non-demanded bits to the value of the preceding demanded bits.
925 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
926 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
927 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
928 // The final result is 0b11000011.
929 uint64_t NonDemandedBits = ~DemandedBits;
930 uint64_t InvertedImm = ~Imm & DemandedBits;
931 uint64_t RotatedImm =
932 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
933 NonDemandedBits;
934 uint64_t Sum = RotatedImm + NonDemandedBits;
935 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
936 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
937 NewImm = (Imm | Ones) & Mask;
938
939 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
940 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
941 // we halve the element size and continue the search.
942 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
943 break;
944
945 // We cannot shrink the element size any further if it is 2-bits.
946 if (EltSize == 2)
947 return false;
948
949 EltSize /= 2;
950 Mask >>= EltSize;
951 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
952
953 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
954 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
955 return false;
956
957 // Merge the upper and lower halves of Imm and DemandedBits.
958 Imm |= Hi;
959 DemandedBits |= DemandedBitsHi;
960 }
961
962 ++NumOptimizedImms;
963
964 // Replicate the element across the register width.
965 while (EltSize < Size) {
966 NewImm |= NewImm << EltSize;
967 EltSize *= 2;
968 }
969
970 (void)OldImm;
971 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
972 "demanded bits should never be altered");
973 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
974
975 // Create the new constant immediate node.
976 EVT VT = Op.getValueType();
977 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000978 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000979
980 // If the new constant immediate is all-zeros or all-ones, let the target
981 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000982 if (NewImm == 0 || NewImm == OrigMask) {
983 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
984 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000985 // Otherwise, create a machine node so that target independent DAG combine
986 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000987 } else {
988 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
989 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
990 New = SDValue(
991 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
992 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000993
994 return TLO.CombineTo(Op, New);
995}
996
997bool AArch64TargetLowering::targetShrinkDemandedConstant(
998 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
999 // Delay this optimization to as late as possible.
1000 if (!TLO.LegalOps)
1001 return false;
1002
1003 if (!EnableOptimizeLogicalImm)
1004 return false;
1005
1006 EVT VT = Op.getValueType();
1007 if (VT.isVector())
1008 return false;
1009
1010 unsigned Size = VT.getSizeInBits();
1011 assert((Size == 32 || Size == 64) &&
1012 "i32 or i64 is expected after legalization.");
1013
1014 // Exit early if we demand all bits.
1015 if (Demanded.countPopulation() == Size)
1016 return false;
1017
1018 unsigned NewOpc;
1019 switch (Op.getOpcode()) {
1020 default:
1021 return false;
1022 case ISD::AND:
1023 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1024 break;
1025 case ISD::OR:
1026 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1027 break;
1028 case ISD::XOR:
1029 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1030 break;
1031 }
1032 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1033 if (!C)
1034 return false;
1035 uint64_t Imm = C->getZExtValue();
1036 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1037}
1038
Tim Northover3b0846e2014-05-24 12:50:23 +00001039/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +00001040/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +00001041void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +00001042 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +00001043 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001044 switch (Op.getOpcode()) {
1045 default:
1046 break;
1047 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001048 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +00001049 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1050 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +00001051 Known.Zero &= Known2.Zero;
1052 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001053 break;
1054 }
1055 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001056 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001057 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1058 switch (IntID) {
1059 default: return;
1060 case Intrinsic::aarch64_ldaxr:
1061 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001062 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001063 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001064 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001065 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001066 return;
1067 }
1068 }
1069 break;
1070 }
1071 case ISD::INTRINSIC_WO_CHAIN:
1072 case ISD::INTRINSIC_VOID: {
1073 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1074 switch (IntNo) {
1075 default:
1076 break;
1077 case Intrinsic::aarch64_neon_umaxv:
1078 case Intrinsic::aarch64_neon_uminv: {
1079 // Figure out the datatype of the vector operand. The UMINV instruction
1080 // will zero extend the result, so we can mark as known zero all the
1081 // bits larger than the element datatype. 32-bit or larget doesn't need
1082 // this as those are legal types and will be handled by isel directly.
1083 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001084 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001085 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1086 assert(BitWidth >= 8 && "Unexpected width!");
1087 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001088 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001089 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1090 assert(BitWidth >= 16 && "Unexpected width!");
1091 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001092 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001093 }
1094 break;
1095 } break;
1096 }
1097 }
1098 }
1099}
1100
Mehdi Aminieaabc512015-07-09 15:12:23 +00001101MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1102 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001103 return MVT::i64;
1104}
1105
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00001106bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1107 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1108 bool *Fast) const {
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001109 if (Subtarget->requiresStrictAlign())
1110 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001111
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001112 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001113 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1114 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001115 // See comments in performSTORECombine() for more details about
1116 // these conditions.
1117
1118 // Code that uses clang vector extensions can mark that it
1119 // wants unaligned accesses to be treated as fast by
1120 // underspecifying alignment to be 1 or 2.
1121 Align <= 2 ||
1122
1123 // Disregard v2i64. Memcpy lowering produces those and splitting
1124 // them regresses performance on micro-benchmarks and olden/bh.
1125 VT == MVT::v2i64;
1126 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001127 return true;
1128}
1129
Amara Emerson13af1ed2019-07-24 22:17:31 +00001130// Same as above but handling LLTs instead.
1131bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1132 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1133 bool *Fast) const {
1134 if (Subtarget->requiresStrictAlign())
1135 return false;
1136
1137 if (Fast) {
1138 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1139 *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1140 Ty.getSizeInBytes() != 16 ||
1141 // See comments in performSTORECombine() for more details about
1142 // these conditions.
1143
1144 // Code that uses clang vector extensions can mark that it
1145 // wants unaligned accesses to be treated as fast by
1146 // underspecifying alignment to be 1 or 2.
1147 Align <= 2 ||
1148
1149 // Disregard v2i64. Memcpy lowering produces those and splitting
1150 // them regresses performance on micro-benchmarks and olden/bh.
1151 Ty == LLT::vector(2, 64);
1152 }
1153 return true;
1154}
1155
Tim Northover3b0846e2014-05-24 12:50:23 +00001156FastISel *
1157AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1158 const TargetLibraryInfo *libInfo) const {
1159 return AArch64::createFastISel(funcInfo, libInfo);
1160}
1161
1162const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001163 switch ((AArch64ISD::NodeType)Opcode) {
1164 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001165 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1166 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001167 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001168 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1169 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1170 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1171 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1172 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1173 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1174 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1175 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1176 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1177 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001178 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001179 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1180 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1181 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1182 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1183 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1184 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1185 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001186 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1187 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1188 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001189 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001190 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1191 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1192 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1193 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1194 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1195 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1196 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1197 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1198 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1199 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1200 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1201 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1202 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1203 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1204 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1205 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1206 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1207 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1208 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1209 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1210 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1211 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1212 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1213 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1214 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1215 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1216 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1217 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1218 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1219 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1220 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1221 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1222 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1223 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1224 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1225 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1226 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1227 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1228 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1229 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1230 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1231 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1232 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1233 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1234 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1235 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1236 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1237 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001238 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1239 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1240 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1241 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1242 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1243 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001244 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1245 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1246 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1247 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1248 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1249 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1250 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001251 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001252 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1253 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001254 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001255 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1256 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1257 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1258 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1259 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1260 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1261 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1262 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1263 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1264 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1265 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1266 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1267 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1268 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1269 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1270 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1271 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1272 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1273 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1274 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1275 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1276 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1277 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1278 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1279 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1280 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1281 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1282 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1283 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001284 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1285 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001286 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001287 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1288 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1289 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Evgeniy Stepanovd752f5e2019-07-17 19:24:02 +00001290 case AArch64ISD::STG: return "AArch64ISD::STG";
1291 case AArch64ISD::STZG: return "AArch64ISD::STZG";
1292 case AArch64ISD::ST2G: return "AArch64ISD::ST2G";
1293 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G";
Tim Northover3b0846e2014-05-24 12:50:23 +00001294 }
Matthias Braund04893f2015-05-07 21:33:59 +00001295 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001296}
1297
1298MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001299AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001300 MachineBasicBlock *MBB) const {
1301 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1302 // phi node:
1303
1304 // OrigBB:
1305 // [... previous instrs leading to comparison ...]
1306 // b.ne TrueBB
1307 // b EndBB
1308 // TrueBB:
1309 // ; Fallthrough
1310 // EndBB:
1311 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1312
Tim Northover3b0846e2014-05-24 12:50:23 +00001313 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001314 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001315 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001316 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001317 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001318
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001319 unsigned DestReg = MI.getOperand(0).getReg();
1320 unsigned IfTrueReg = MI.getOperand(1).getReg();
1321 unsigned IfFalseReg = MI.getOperand(2).getReg();
1322 unsigned CondCode = MI.getOperand(3).getImm();
1323 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001324
1325 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1326 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1327 MF->insert(It, TrueBB);
1328 MF->insert(It, EndBB);
1329
1330 // Transfer rest of current basic-block to EndBB
1331 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1332 MBB->end());
1333 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1334
1335 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1336 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1337 MBB->addSuccessor(TrueBB);
1338 MBB->addSuccessor(EndBB);
1339
1340 // TrueBB falls through to the end.
1341 TrueBB->addSuccessor(EndBB);
1342
1343 if (!NZCVKilled) {
1344 TrueBB->addLiveIn(AArch64::NZCV);
1345 EndBB->addLiveIn(AArch64::NZCV);
1346 }
1347
1348 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1349 .addReg(IfTrueReg)
1350 .addMBB(TrueBB)
1351 .addReg(IfFalseReg)
1352 .addMBB(MBB);
1353
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001354 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001355 return EndBB;
1356}
1357
Eli Friedmanad1151c2018-11-09 23:33:30 +00001358MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1359 MachineInstr &MI, MachineBasicBlock *BB) const {
1360 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1361 BB->getParent()->getFunction().getPersonalityFn())) &&
1362 "SEH does not use catchret!");
1363 return BB;
1364}
1365
1366MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1367 MachineInstr &MI, MachineBasicBlock *BB) const {
1368 MI.eraseFromParent();
1369 return BB;
1370}
1371
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001372MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1373 MachineInstr &MI, MachineBasicBlock *BB) const {
1374 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001375 default:
1376#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001377 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001378#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001379 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001380
1381 case AArch64::F128CSEL:
1382 return EmitF128CSEL(MI, BB);
1383
1384 case TargetOpcode::STACKMAP:
1385 case TargetOpcode::PATCHPOINT:
1386 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001387
1388 case AArch64::CATCHRET:
1389 return EmitLoweredCatchRet(MI, BB);
1390 case AArch64::CATCHPAD:
1391 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001392 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001393}
1394
1395//===----------------------------------------------------------------------===//
1396// AArch64 Lowering private implementation.
1397//===----------------------------------------------------------------------===//
1398
1399//===----------------------------------------------------------------------===//
1400// Lowering Code
1401//===----------------------------------------------------------------------===//
1402
1403/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1404/// CC
1405static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1406 switch (CC) {
1407 default:
1408 llvm_unreachable("Unknown condition code!");
1409 case ISD::SETNE:
1410 return AArch64CC::NE;
1411 case ISD::SETEQ:
1412 return AArch64CC::EQ;
1413 case ISD::SETGT:
1414 return AArch64CC::GT;
1415 case ISD::SETGE:
1416 return AArch64CC::GE;
1417 case ISD::SETLT:
1418 return AArch64CC::LT;
1419 case ISD::SETLE:
1420 return AArch64CC::LE;
1421 case ISD::SETUGT:
1422 return AArch64CC::HI;
1423 case ISD::SETUGE:
1424 return AArch64CC::HS;
1425 case ISD::SETULT:
1426 return AArch64CC::LO;
1427 case ISD::SETULE:
1428 return AArch64CC::LS;
1429 }
1430}
1431
1432/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1433static void changeFPCCToAArch64CC(ISD::CondCode CC,
1434 AArch64CC::CondCode &CondCode,
1435 AArch64CC::CondCode &CondCode2) {
1436 CondCode2 = AArch64CC::AL;
1437 switch (CC) {
1438 default:
1439 llvm_unreachable("Unknown FP condition!");
1440 case ISD::SETEQ:
1441 case ISD::SETOEQ:
1442 CondCode = AArch64CC::EQ;
1443 break;
1444 case ISD::SETGT:
1445 case ISD::SETOGT:
1446 CondCode = AArch64CC::GT;
1447 break;
1448 case ISD::SETGE:
1449 case ISD::SETOGE:
1450 CondCode = AArch64CC::GE;
1451 break;
1452 case ISD::SETOLT:
1453 CondCode = AArch64CC::MI;
1454 break;
1455 case ISD::SETOLE:
1456 CondCode = AArch64CC::LS;
1457 break;
1458 case ISD::SETONE:
1459 CondCode = AArch64CC::MI;
1460 CondCode2 = AArch64CC::GT;
1461 break;
1462 case ISD::SETO:
1463 CondCode = AArch64CC::VC;
1464 break;
1465 case ISD::SETUO:
1466 CondCode = AArch64CC::VS;
1467 break;
1468 case ISD::SETUEQ:
1469 CondCode = AArch64CC::EQ;
1470 CondCode2 = AArch64CC::VS;
1471 break;
1472 case ISD::SETUGT:
1473 CondCode = AArch64CC::HI;
1474 break;
1475 case ISD::SETUGE:
1476 CondCode = AArch64CC::PL;
1477 break;
1478 case ISD::SETLT:
1479 case ISD::SETULT:
1480 CondCode = AArch64CC::LT;
1481 break;
1482 case ISD::SETLE:
1483 case ISD::SETULE:
1484 CondCode = AArch64CC::LE;
1485 break;
1486 case ISD::SETNE:
1487 case ISD::SETUNE:
1488 CondCode = AArch64CC::NE;
1489 break;
1490 }
1491}
1492
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001493/// Convert a DAG fp condition code to an AArch64 CC.
1494/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1495/// should be AND'ed instead of OR'ed.
1496static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1497 AArch64CC::CondCode &CondCode,
1498 AArch64CC::CondCode &CondCode2) {
1499 CondCode2 = AArch64CC::AL;
1500 switch (CC) {
1501 default:
1502 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1503 assert(CondCode2 == AArch64CC::AL);
1504 break;
1505 case ISD::SETONE:
1506 // (a one b)
1507 // == ((a olt b) || (a ogt b))
1508 // == ((a ord b) && (a une b))
1509 CondCode = AArch64CC::VC;
1510 CondCode2 = AArch64CC::NE;
1511 break;
1512 case ISD::SETUEQ:
1513 // (a ueq b)
1514 // == ((a uno b) || (a oeq b))
1515 // == ((a ule b) && (a uge b))
1516 CondCode = AArch64CC::PL;
1517 CondCode2 = AArch64CC::LE;
1518 break;
1519 }
1520}
1521
Tim Northover3b0846e2014-05-24 12:50:23 +00001522/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1523/// CC usable with the vector instructions. Fewer operations are available
1524/// without a real NZCV register, so we have to use less efficient combinations
1525/// to get the same effect.
1526static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1527 AArch64CC::CondCode &CondCode,
1528 AArch64CC::CondCode &CondCode2,
1529 bool &Invert) {
1530 Invert = false;
1531 switch (CC) {
1532 default:
1533 // Mostly the scalar mappings work fine.
1534 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1535 break;
1536 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001537 Invert = true;
1538 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001539 case ISD::SETO:
1540 CondCode = AArch64CC::MI;
1541 CondCode2 = AArch64CC::GE;
1542 break;
1543 case ISD::SETUEQ:
1544 case ISD::SETULT:
1545 case ISD::SETULE:
1546 case ISD::SETUGT:
1547 case ISD::SETUGE:
1548 // All of the compare-mask comparisons are ordered, but we can switch
1549 // between the two by a double inversion. E.g. ULE == !OGT.
1550 Invert = true;
1551 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1552 break;
1553 }
1554}
1555
1556static bool isLegalArithImmed(uint64_t C) {
1557 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001558 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001559 LLVM_DEBUG(dbgs() << "Is imm " << C
1560 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001561 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001562}
1563
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001564// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1565// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1566// can be set differently by this operation. It comes down to whether
1567// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1568// everything is fine. If not then the optimization is wrong. Thus general
1569// comparisons are only valid if op2 != 0.
1570//
1571// So, finally, the only LLVM-native comparisons that don't mention C and V
1572// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1573// the absence of information about op2.
1574static bool isCMN(SDValue Op, ISD::CondCode CC) {
1575 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1576 (CC == ISD::SETEQ || CC == ISD::SETNE);
1577}
1578
Tim Northover3b0846e2014-05-24 12:50:23 +00001579static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001580 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001581 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001582 const bool FullFP16 =
1583 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001584
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001585 if (VT.isFloatingPoint()) {
1586 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001587 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001588 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1589 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001590 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001591 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001592 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001593 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001594
1595 // The CMP instruction is just an alias for SUBS, and representing it as
1596 // SUBS means that it's possible to get CSE with subtract operations.
1597 // A later phase can perform the optimization of setting the destination
1598 // register to WZR/XZR if it ends up being unused.
1599 unsigned Opcode = AArch64ISD::SUBS;
1600
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001601 if (isCMN(RHS, CC)) {
1602 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001603 Opcode = AArch64ISD::ADDS;
1604 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001605 } else if (isCMN(LHS, CC)) {
1606 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1607 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1608 Opcode = AArch64ISD::ADDS;
1609 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001610 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001611 !isUnsignedIntSetCC(CC)) {
1612 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1613 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1614 // of the signed comparisons.
1615 Opcode = AArch64ISD::ANDS;
1616 RHS = LHS.getOperand(1);
1617 LHS = LHS.getOperand(0);
1618 }
1619
Matthias Braunaf7d7702015-07-16 20:02:37 +00001620 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001621 .getValue(1);
1622}
1623
Matthias Braunaf7d7702015-07-16 20:02:37 +00001624/// \defgroup AArch64CCMP CMP;CCMP matching
1625///
1626/// These functions deal with the formation of CMP;CCMP;... sequences.
1627/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1628/// a comparison. They set the NZCV flags to a predefined value if their
1629/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001630/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001631/// expressed as:
1632/// cmp A
1633/// ccmp B, inv(CB), CA
1634/// check for CB flags
1635///
Matthias Braund0412122018-12-06 01:40:23 +00001636/// This naturally lets us implement chains of AND operations with SETCC
1637/// operands. And we can even implement some other situations by transforming
1638/// them:
1639/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1640/// negating the flags used in a CCMP/FCCMP operations.
1641/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1642/// by negating the flags we test for afterwards. i.e.
1643/// NEG (CMP CCMP CCCMP ...) can be implemented.
1644/// - Note that we can only ever negate all previously processed results.
1645/// What we can not implement by flipping the flags to test is a negation
1646/// of two sub-trees (because the negation affects all sub-trees emitted so
1647/// far, so the 2nd sub-tree we emit would also affect the first).
1648/// With those tools we can implement some OR operations:
1649/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1650/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1651/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1652/// elimination rules from earlier to implement the whole thing as a
1653/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001654///
Matthias Braund0412122018-12-06 01:40:23 +00001655/// As complete example:
1656/// or (or (setCA (cmp A)) (setCB (cmp B)))
1657/// (and (setCC (cmp C)) (setCD (cmp D)))"
1658/// can be reassociated to:
1659/// or (and (setCC (cmp C)) setCD (cmp D))
1660// (or (setCA (cmp A)) (setCB (cmp B)))
1661/// can be transformed to:
1662/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1663/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1664/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001665/// cmp C
1666/// ccmp D, inv(CD), CC
1667/// ccmp A, CA, inv(CD)
1668/// ccmp B, CB, inv(CA)
1669/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001670///
1671/// A counterexample is "or (and A B) (and C D)" which translates to
1672/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1673/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001674/// @{
1675
Geoff Berrye41c2df2015-07-20 22:03:52 +00001676/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001677static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1678 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001679 AArch64CC::CondCode Predicate,
1680 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001681 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001682 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001683 const bool FullFP16 =
1684 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1685
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001686 if (LHS.getValueType().isFloatingPoint()) {
1687 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001688 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001689 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1690 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1691 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001692 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001693 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001694 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001695 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001696 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1697 Opcode = AArch64ISD::CCMN;
1698 RHS = RHS.getOperand(1);
1699 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001700 }
1701 if (Opcode == 0)
1702 Opcode = AArch64ISD::CCMP;
1703
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001704 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1705 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1706 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001707 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1708 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1709}
1710
Matthias Braun96d12512018-11-06 03:15:22 +00001711/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1712/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001713/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1714/// changing the conditions on the SETCC tests.
1715/// (this means we can call emitConjunctionRec() with
1716/// Negate==true on this sub-tree)
1717/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1718/// cannot do the negation naturally. We are required to
1719/// emit the subtree first in this case.
1720/// \param WillNegate Is true if are called when the result of this
1721/// subexpression must be negated. This happens when the
1722/// outer expression is an OR. We can use this fact to know
1723/// that we have a double negation (or (or ...) ...) that
1724/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001725static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001726 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001727 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001728 if (!Val.hasOneUse())
1729 return false;
1730 unsigned Opcode = Val->getOpcode();
1731 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001732 if (Val->getOperand(0).getValueType() == MVT::f128)
1733 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001734 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001735 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001736 return true;
1737 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001738 // Protect against exponential runtime and stack overflow.
1739 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001740 return false;
1741 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001742 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001743 SDValue O0 = Val->getOperand(0);
1744 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001745 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001746 bool MustBeFirstL;
1747 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001748 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001749 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001750 bool MustBeFirstR;
1751 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001752 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001753
Matthias Braund0412122018-12-06 01:40:23 +00001754 if (MustBeFirstL && MustBeFirstR)
1755 return false;
1756
1757 if (IsOR) {
1758 // For an OR expression we need to be able to naturally negate at least
1759 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001760 if (!CanNegateL && !CanNegateR)
1761 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001762 // If we the result of the OR will be negated and we can naturally negate
1763 // the leafs, then this sub-tree as a whole negates naturally.
1764 CanNegate = WillNegate && CanNegateL && CanNegateR;
1765 // If we cannot naturally negate the whole sub-tree, then this must be
1766 // emitted first.
1767 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001768 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001769 assert(Opcode == ISD::AND && "Must be OR or AND");
1770 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001771 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001772 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001773 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001774 return true;
1775 }
1776 return false;
1777}
1778
1779/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1780/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1781/// Tries to transform the given i1 producing node @p Val to a series compare
1782/// and conditional compare operations. @returns an NZCV flags producing node
1783/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1784/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001785/// \p Negate is true if we want this sub-tree being negated just by changing
1786/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001787static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001788 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001789 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001790 // We're at a tree leaf, produce a conditional comparison operation.
1791 unsigned Opcode = Val->getOpcode();
1792 if (Opcode == ISD::SETCC) {
1793 SDValue LHS = Val->getOperand(0);
1794 SDValue RHS = Val->getOperand(1);
1795 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1796 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001797 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001798 CC = getSetCCInverse(CC, isInteger);
1799 SDLoc DL(Val);
1800 // Determine OutCC and handle FP special case.
1801 if (isInteger) {
1802 OutCC = changeIntCCToAArch64CC(CC);
1803 } else {
1804 assert(LHS.getValueType().isFloatingPoint());
1805 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001806 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1807 // Some floating point conditions can't be tested with a single condition
1808 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001809 if (ExtraCC != AArch64CC::AL) {
1810 SDValue ExtraCmp;
1811 if (!CCOp.getNode())
1812 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001813 else
1814 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001815 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001816 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001817 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001818 }
1819 }
1820
1821 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001822 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001823 return emitComparison(LHS, RHS, CC, DL, DAG);
1824 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001825 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001826 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001827 }
Matthias Braund0412122018-12-06 01:40:23 +00001828 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001829
Matthias Braund0412122018-12-06 01:40:23 +00001830 bool IsOR = Opcode == ISD::OR;
1831
Matthias Braunaf7d7702015-07-16 20:02:37 +00001832 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001833 bool CanNegateL;
1834 bool MustBeFirstL;
1835 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1836 assert(ValidL && "Valid conjunction/disjunction tree");
1837 (void)ValidL;
1838
Matthias Braunaf7d7702015-07-16 20:02:37 +00001839 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001840 bool CanNegateR;
1841 bool MustBeFirstR;
1842 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1843 assert(ValidR && "Valid conjunction/disjunction tree");
1844 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001845
Matthias Braund0412122018-12-06 01:40:23 +00001846 // Swap sub-tree that must come first to the right side.
1847 if (MustBeFirstL) {
1848 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1849 std::swap(LHS, RHS);
1850 std::swap(CanNegateL, CanNegateR);
1851 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001852 }
1853
Matthias Braund0412122018-12-06 01:40:23 +00001854 bool NegateR;
1855 bool NegateAfterR;
1856 bool NegateL;
1857 bool NegateAfterAll;
1858 if (Opcode == ISD::OR) {
1859 // Swap the sub-tree that we can negate naturally to the left.
1860 if (!CanNegateL) {
1861 assert(CanNegateR && "at least one side must be negatable");
1862 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1863 assert(!Negate);
1864 std::swap(LHS, RHS);
1865 NegateR = false;
1866 NegateAfterR = true;
1867 } else {
1868 // Negate the left sub-tree if possible, otherwise negate the result.
1869 NegateR = CanNegateR;
1870 NegateAfterR = !CanNegateR;
1871 }
1872 NegateL = true;
1873 NegateAfterAll = !Negate;
1874 } else {
1875 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1876 assert(!Negate && "Valid conjunction/disjunction tree");
1877
1878 NegateL = false;
1879 NegateR = false;
1880 NegateAfterR = false;
1881 NegateAfterAll = false;
1882 }
1883
1884 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001885 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001886 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1887 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001888 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001889 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1890 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001891 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1892 return CmpL;
1893}
1894
Matthias Braun96d12512018-11-06 03:15:22 +00001895/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1896/// In some cases this is even possible with OR operations in the expression.
1897/// See \ref AArch64CCMP.
1898/// \see emitConjunctionRec().
1899static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1900 AArch64CC::CondCode &OutCC) {
1901 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001902 bool DummyMustBeFirst;
1903 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001904 return SDValue();
1905
Matthias Braun96d12512018-11-06 03:15:22 +00001906 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001907}
1908
Matthias Braunaf7d7702015-07-16 20:02:37 +00001909/// @}
1910
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001911/// Returns how profitable it is to fold a comparison's operand's shift and/or
1912/// extension operations.
1913static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1914 auto isSupportedExtend = [&](SDValue V) {
1915 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1916 return true;
1917
1918 if (V.getOpcode() == ISD::AND)
1919 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1920 uint64_t Mask = MaskCst->getZExtValue();
1921 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1922 }
1923
1924 return false;
1925 };
1926
1927 if (!Op.hasOneUse())
1928 return 0;
1929
1930 if (isSupportedExtend(Op))
1931 return 1;
1932
1933 unsigned Opc = Op.getOpcode();
1934 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1935 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1936 uint64_t Shift = ShiftCst->getZExtValue();
1937 if (isSupportedExtend(Op.getOperand(0)))
1938 return (Shift <= 4) ? 2 : 1;
1939 EVT VT = Op.getValueType();
1940 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1941 return 1;
1942 }
1943
1944 return 0;
1945}
1946
Tim Northover3b0846e2014-05-24 12:50:23 +00001947static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001948 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001949 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001950 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1951 EVT VT = RHS.getValueType();
1952 uint64_t C = RHSC->getZExtValue();
1953 if (!isLegalArithImmed(C)) {
1954 // Constant does not fit, try adjusting it by one?
1955 switch (CC) {
1956 default:
1957 break;
1958 case ISD::SETLT:
1959 case ISD::SETGE:
1960 if ((VT == MVT::i32 && C != 0x80000000 &&
1961 isLegalArithImmed((uint32_t)(C - 1))) ||
1962 (VT == MVT::i64 && C != 0x80000000ULL &&
1963 isLegalArithImmed(C - 1ULL))) {
1964 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1965 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001966 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001967 }
1968 break;
1969 case ISD::SETULT:
1970 case ISD::SETUGE:
1971 if ((VT == MVT::i32 && C != 0 &&
1972 isLegalArithImmed((uint32_t)(C - 1))) ||
1973 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1974 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1975 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001976 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001977 }
1978 break;
1979 case ISD::SETLE:
1980 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001981 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001982 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001983 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001984 isLegalArithImmed(C + 1ULL))) {
1985 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1986 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001987 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001988 }
1989 break;
1990 case ISD::SETULE:
1991 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001992 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001993 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001994 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001995 isLegalArithImmed(C + 1ULL))) {
1996 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1997 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001998 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001999 }
2000 break;
2001 }
2002 }
2003 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00002004
2005 // Comparisons are canonicalized so that the RHS operand is simpler than the
2006 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2007 // can fold some shift+extend operations on the RHS operand, so swap the
2008 // operands if that can be done.
2009 //
2010 // For example:
2011 // lsl w13, w11, #1
2012 // cmp w13, w12
2013 // can be turned into:
2014 // cmp w12, w11, lsl #1
2015 if (!isa<ConstantSDNode>(RHS) ||
2016 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2017 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2018
2019 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2020 std::swap(LHS, RHS);
2021 CC = ISD::getSetCCSwappedOperands(CC);
2022 }
2023 }
2024
Matthias Braunaf7d7702015-07-16 20:02:37 +00002025 SDValue Cmp;
2026 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00002027 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002028 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2029
2030 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2031 // For the i8 operand, the largest immediate is 255, so this can be easily
2032 // encoded in the compare instruction. For the i16 operand, however, the
2033 // largest immediate cannot be encoded in the compare.
2034 // Therefore, use a sign extending load and cmn to avoid materializing the
2035 // -1 constant. For example,
2036 // movz w1, #65535
2037 // ldrh w0, [x0, #0]
2038 // cmp w0, w1
2039 // >
2040 // ldrsh w0, [x0, #0]
2041 // cmn w0, #1
2042 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2043 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002044 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00002045 // transformation is profitable.
2046 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2047 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2048 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2049 LHS.getNode()->hasNUsesOfValue(1, 0)) {
2050 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2051 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2052 SDValue SExt =
2053 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2054 DAG.getValueType(MVT::i16));
2055 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2056 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002057 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002058 AArch64CC = changeIntCCToAArch64CC(CC);
2059 }
2060 }
2061
2062 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00002063 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002064 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2065 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00002066 }
2067 }
2068 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00002069
2070 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002071 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002072 AArch64CC = changeIntCCToAArch64CC(CC);
2073 }
2074 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00002075 return Cmp;
2076}
2077
2078static std::pair<SDValue, SDValue>
2079getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2080 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2081 "Unsupported value type");
2082 SDValue Value, Overflow;
2083 SDLoc DL(Op);
2084 SDValue LHS = Op.getOperand(0);
2085 SDValue RHS = Op.getOperand(1);
2086 unsigned Opc = 0;
2087 switch (Op.getOpcode()) {
2088 default:
2089 llvm_unreachable("Unknown overflow instruction!");
2090 case ISD::SADDO:
2091 Opc = AArch64ISD::ADDS;
2092 CC = AArch64CC::VS;
2093 break;
2094 case ISD::UADDO:
2095 Opc = AArch64ISD::ADDS;
2096 CC = AArch64CC::HS;
2097 break;
2098 case ISD::SSUBO:
2099 Opc = AArch64ISD::SUBS;
2100 CC = AArch64CC::VS;
2101 break;
2102 case ISD::USUBO:
2103 Opc = AArch64ISD::SUBS;
2104 CC = AArch64CC::LO;
2105 break;
2106 // Multiply needs a little bit extra work.
2107 case ISD::SMULO:
2108 case ISD::UMULO: {
2109 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002110 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002111 if (Op.getValueType() == MVT::i32) {
2112 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2113 // For a 32 bit multiply with overflow check we want the instruction
2114 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2115 // need to generate the following pattern:
2116 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2117 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2118 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2119 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2120 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002121 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002122 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2123 // operation. We need to clear out the upper 32 bits, because we used a
2124 // widening multiply that wrote all 64 bits. In the end this should be a
2125 // noop.
2126 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2127 if (IsSigned) {
2128 // The signed overflow check requires more than just a simple check for
2129 // any bit set in the upper 32 bits of the result. These bits could be
2130 // just the sign bits of a negative number. To perform the overflow
2131 // check we have to arithmetic shift right the 32nd bit of the result by
2132 // 31 bits. Then we compare the result to the upper 32 bits.
2133 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002134 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002135 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2136 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002137 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002138 // It is important that LowerBits is last, otherwise the arithmetic
2139 // shift will not be folded into the compare (SUBS).
2140 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2141 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2142 .getValue(1);
2143 } else {
2144 // The overflow check for unsigned multiply is easy. We only need to
2145 // check if any of the upper 32 bits are set. This can be done with a
2146 // CMP (shifted register). For that we need to generate the following
2147 // pattern:
2148 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2149 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002150 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002151 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2152 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002153 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2154 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002155 UpperBits).getValue(1);
2156 }
2157 break;
2158 }
2159 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2160 // For the 64 bit multiply
2161 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2162 if (IsSigned) {
2163 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2164 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002165 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002166 // It is important that LowerBits is last, otherwise the arithmetic
2167 // shift will not be folded into the compare (SUBS).
2168 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2169 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2170 .getValue(1);
2171 } else {
2172 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2173 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2174 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002175 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2176 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002177 UpperBits).getValue(1);
2178 }
2179 break;
2180 }
2181 } // switch (...)
2182
2183 if (Opc) {
2184 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2185
2186 // Emit the AArch64 operation with overflow check.
2187 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2188 Overflow = Value.getValue(1);
2189 }
2190 return std::make_pair(Value, Overflow);
2191}
2192
2193SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2194 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002195 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002196 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002197}
2198
Amara Emerson24ca39c2017-10-09 15:15:09 +00002199// Returns true if the given Op is the overflow flag result of an overflow
2200// intrinsic operation.
2201static bool isOverflowIntrOpRes(SDValue Op) {
2202 unsigned Opc = Op.getOpcode();
2203 return (Op.getResNo() == 1 &&
2204 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2205 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2206}
2207
Tim Northover3b0846e2014-05-24 12:50:23 +00002208static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2209 SDValue Sel = Op.getOperand(0);
2210 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002211 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002212
Amara Emerson24ca39c2017-10-09 15:15:09 +00002213 // If the operand is an overflow checking operation, invert the condition
2214 // code and kill the Not operation. I.e., transform:
2215 // (xor (overflow_op_bool, 1))
2216 // -->
2217 // (csel 1, 0, invert(cc), overflow_op_bool)
2218 // ... which later gets transformed to just a cset instruction with an
2219 // inverted condition code, rather than a cset + eor sequence.
2220 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2221 // Only lower legal XALUO ops.
2222 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2223 return SDValue();
2224
2225 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2226 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2227 AArch64CC::CondCode CC;
2228 SDValue Value, Overflow;
2229 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2230 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2231 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2232 CCVal, Overflow);
2233 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002234 // If neither operand is a SELECT_CC, give up.
2235 if (Sel.getOpcode() != ISD::SELECT_CC)
2236 std::swap(Sel, Other);
2237 if (Sel.getOpcode() != ISD::SELECT_CC)
2238 return Op;
2239
2240 // The folding we want to perform is:
2241 // (xor x, (select_cc a, b, cc, 0, -1) )
2242 // -->
2243 // (csel x, (xor x, -1), cc ...)
2244 //
2245 // The latter will get matched to a CSINV instruction.
2246
2247 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2248 SDValue LHS = Sel.getOperand(0);
2249 SDValue RHS = Sel.getOperand(1);
2250 SDValue TVal = Sel.getOperand(2);
2251 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002252
2253 // FIXME: This could be generalized to non-integer comparisons.
2254 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2255 return Op;
2256
2257 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2258 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2259
Eric Christopher572e03a2015-06-19 01:53:21 +00002260 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002261 if (!CFVal || !CTVal)
2262 return Op;
2263
2264 // We can commute the SELECT_CC by inverting the condition. This
2265 // might be needed to make this fit into a CSINV pattern.
2266 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2267 std::swap(TVal, FVal);
2268 std::swap(CTVal, CFVal);
2269 CC = ISD::getSetCCInverse(CC, true);
2270 }
2271
2272 // If the constants line up, perform the transform!
2273 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2274 SDValue CCVal;
2275 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2276
2277 FVal = Other;
2278 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002279 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002280
2281 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2282 CCVal, Cmp);
2283 }
2284
2285 return Op;
2286}
2287
2288static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2289 EVT VT = Op.getValueType();
2290
2291 // Let legalize expand this if it isn't a legal type yet.
2292 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2293 return SDValue();
2294
2295 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2296
2297 unsigned Opc;
2298 bool ExtraOp = false;
2299 switch (Op.getOpcode()) {
2300 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002301 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002302 case ISD::ADDC:
2303 Opc = AArch64ISD::ADDS;
2304 break;
2305 case ISD::SUBC:
2306 Opc = AArch64ISD::SUBS;
2307 break;
2308 case ISD::ADDE:
2309 Opc = AArch64ISD::ADCS;
2310 ExtraOp = true;
2311 break;
2312 case ISD::SUBE:
2313 Opc = AArch64ISD::SBCS;
2314 ExtraOp = true;
2315 break;
2316 }
2317
2318 if (!ExtraOp)
2319 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2320 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2321 Op.getOperand(2));
2322}
2323
2324static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2325 // Let legalize expand this if it isn't a legal type yet.
2326 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2327 return SDValue();
2328
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002329 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002330 AArch64CC::CondCode CC;
2331 // The actual operation that sets the overflow or carry flag.
2332 SDValue Value, Overflow;
2333 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2334
2335 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002336 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2337 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002338
2339 // We use an inverted condition, because the conditional select is inverted
2340 // too. This will allow it to be selected to a single instruction:
2341 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002342 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2343 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002344 CCVal, Overflow);
2345
2346 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002347 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002348}
2349
2350// Prefetch operands are:
2351// 1: Address to prefetch
2352// 2: bool isWrite
2353// 3: int locality (0 = no locality ... 3 = extreme locality)
2354// 4: bool isDataCache
2355static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2356 SDLoc DL(Op);
2357 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2358 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002359 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002360
2361 bool IsStream = !Locality;
2362 // When the locality number is set
2363 if (Locality) {
2364 // The front-end should have filtered out the out-of-range values
2365 assert(Locality <= 3 && "Prefetch locality out-of-range");
2366 // The locality degree is the opposite of the cache speed.
2367 // Put the number the other way around.
2368 // The encoding starts at 0 for level 1
2369 Locality = 3 - Locality;
2370 }
2371
2372 // built the mask value encoding the expected behavior.
2373 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002374 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002375 (Locality << 1) | // Cache level bits
2376 (unsigned)IsStream; // Stream bit
2377 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002378 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002379}
2380
2381SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2382 SelectionDAG &DAG) const {
2383 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2384
2385 RTLIB::Libcall LC;
2386 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2387
2388 return LowerF128Call(Op, DAG, LC);
2389}
2390
2391SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2392 SelectionDAG &DAG) const {
2393 if (Op.getOperand(0).getValueType() != MVT::f128) {
2394 // It's legal except when f128 is involved
2395 return Op;
2396 }
2397
2398 RTLIB::Libcall LC;
2399 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2400
2401 // FP_ROUND node has a second operand indicating whether it is known to be
2402 // precise. That doesn't take part in the LibCall so we can't directly use
2403 // LowerF128Call.
2404 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002405 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2406 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002407}
2408
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002409SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2410 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002411 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2412 // Any additional optimization in this function should be recorded
2413 // in the cost tables.
2414 EVT InVT = Op.getOperand(0).getValueType();
2415 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002416 unsigned NumElts = InVT.getVectorNumElements();
2417
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002418 // f16 conversions are promoted to f32 when full fp16 is not supported.
2419 if (InVT.getVectorElementType() == MVT::f16 &&
2420 !Subtarget->hasFullFP16()) {
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002421 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2422 SDLoc dl(Op);
2423 return DAG.getNode(
2424 Op.getOpcode(), dl, Op.getValueType(),
2425 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2426 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002427
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002428 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002429 SDLoc dl(Op);
2430 SDValue Cv =
2431 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2432 Op.getOperand(0));
2433 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002434 }
2435
2436 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002437 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002438 MVT ExtVT =
2439 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2440 VT.getVectorNumElements());
2441 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002442 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2443 }
2444
2445 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002446 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002447}
2448
2449SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2450 SelectionDAG &DAG) const {
2451 if (Op.getOperand(0).getValueType().isVector())
2452 return LowerVectorFP_TO_INT(Op, DAG);
2453
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002454 // f16 conversions are promoted to f32 when full fp16 is not supported.
2455 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2456 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002457 SDLoc dl(Op);
2458 return DAG.getNode(
2459 Op.getOpcode(), dl, Op.getValueType(),
2460 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2461 }
2462
Tim Northover3b0846e2014-05-24 12:50:23 +00002463 if (Op.getOperand(0).getValueType() != MVT::f128) {
2464 // It's legal except when f128 is involved
2465 return Op;
2466 }
2467
2468 RTLIB::Libcall LC;
2469 if (Op.getOpcode() == ISD::FP_TO_SINT)
2470 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2471 else
2472 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2473
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002474 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002475 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002476}
2477
2478static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2479 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2480 // Any additional optimization in this function should be recorded
2481 // in the cost tables.
2482 EVT VT = Op.getValueType();
2483 SDLoc dl(Op);
2484 SDValue In = Op.getOperand(0);
2485 EVT InVT = In.getValueType();
2486
Tim Northoveref0d7602014-06-15 09:27:06 +00002487 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2488 MVT CastVT =
2489 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2490 InVT.getVectorNumElements());
2491 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002492 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002493 }
2494
Tim Northoveref0d7602014-06-15 09:27:06 +00002495 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2496 unsigned CastOpc =
2497 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2498 EVT CastVT = VT.changeVectorElementTypeToInteger();
2499 In = DAG.getNode(CastOpc, dl, CastVT, In);
2500 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002501 }
2502
Tim Northoveref0d7602014-06-15 09:27:06 +00002503 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002504}
2505
2506SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2507 SelectionDAG &DAG) const {
2508 if (Op.getValueType().isVector())
2509 return LowerVectorINT_TO_FP(Op, DAG);
2510
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002511 // f16 conversions are promoted to f32 when full fp16 is not supported.
2512 if (Op.getValueType() == MVT::f16 &&
2513 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002514 SDLoc dl(Op);
2515 return DAG.getNode(
2516 ISD::FP_ROUND, dl, MVT::f16,
2517 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002518 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002519 }
2520
Tim Northover3b0846e2014-05-24 12:50:23 +00002521 // i128 conversions are libcalls.
2522 if (Op.getOperand(0).getValueType() == MVT::i128)
2523 return SDValue();
2524
2525 // Other conversions are legal, unless it's to the completely software-based
2526 // fp128.
2527 if (Op.getValueType() != MVT::f128)
2528 return Op;
2529
2530 RTLIB::Libcall LC;
2531 if (Op.getOpcode() == ISD::SINT_TO_FP)
2532 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2533 else
2534 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2535
2536 return LowerF128Call(Op, DAG, LC);
2537}
2538
2539SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2540 SelectionDAG &DAG) const {
2541 // For iOS, we want to call an alternative entry point: __sincos_stret,
2542 // which returns the values in two S / D registers.
2543 SDLoc dl(Op);
2544 SDValue Arg = Op.getOperand(0);
2545 EVT ArgVT = Arg.getValueType();
2546 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2547
2548 ArgListTy Args;
2549 ArgListEntry Entry;
2550
2551 Entry.Node = Arg;
2552 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002553 Entry.IsSExt = false;
2554 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002555 Args.push_back(Entry);
2556
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002557 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2558 : RTLIB::SINCOS_STRET_F32;
2559 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002560 SDValue Callee =
2561 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002562
Serge Gueltone38003f2017-05-09 19:31:13 +00002563 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002564 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002565 CLI.setDebugLoc(dl)
2566 .setChain(DAG.getEntryNode())
2567 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002568
2569 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2570 return CallResult.first;
2571}
2572
Tim Northoverf8bfe212014-07-18 13:07:05 +00002573static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2574 if (Op.getValueType() != MVT::f16)
2575 return SDValue();
2576
2577 assert(Op.getOperand(0).getValueType() == MVT::i16);
2578 SDLoc DL(Op);
2579
2580 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2581 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2582 return SDValue(
2583 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002584 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002585 0);
2586}
2587
Chad Rosierd9d0f862014-10-08 02:31:24 +00002588static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2589 if (OrigVT.getSizeInBits() >= 64)
2590 return OrigVT;
2591
2592 assert(OrigVT.isSimple() && "Expecting a simple value type");
2593
2594 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2595 switch (OrigSimpleTy) {
2596 default: llvm_unreachable("Unexpected Vector Type");
2597 case MVT::v2i8:
2598 case MVT::v2i16:
2599 return MVT::v2i32;
2600 case MVT::v4i8:
2601 return MVT::v4i16;
2602 }
2603}
2604
2605static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2606 const EVT &OrigTy,
2607 const EVT &ExtTy,
2608 unsigned ExtOpcode) {
2609 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2610 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2611 // 64-bits we need to insert a new extension so that it will be 64-bits.
2612 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2613 if (OrigTy.getSizeInBits() >= 64)
2614 return N;
2615
2616 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2617 EVT NewVT = getExtensionTo64Bits(OrigTy);
2618
2619 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2620}
2621
2622static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2623 bool isSigned) {
2624 EVT VT = N->getValueType(0);
2625
2626 if (N->getOpcode() != ISD::BUILD_VECTOR)
2627 return false;
2628
Pete Cooper3af9a252015-06-26 18:17:36 +00002629 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002630 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002631 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002632 unsigned HalfSize = EltSize / 2;
2633 if (isSigned) {
2634 if (!isIntN(HalfSize, C->getSExtValue()))
2635 return false;
2636 } else {
2637 if (!isUIntN(HalfSize, C->getZExtValue()))
2638 return false;
2639 }
2640 continue;
2641 }
2642 return false;
2643 }
2644
2645 return true;
2646}
2647
2648static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2649 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2650 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2651 N->getOperand(0)->getValueType(0),
2652 N->getValueType(0),
2653 N->getOpcode());
2654
2655 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2656 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002657 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002658 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002659 unsigned NumElts = VT.getVectorNumElements();
2660 MVT TruncVT = MVT::getIntegerVT(EltSize);
2661 SmallVector<SDValue, 8> Ops;
2662 for (unsigned i = 0; i != NumElts; ++i) {
2663 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2664 const APInt &CInt = C->getAPIntValue();
2665 // Element types smaller than 32 bits are not legal, so use i32 elements.
2666 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002667 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002668 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002669 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002670}
2671
2672static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002673 return N->getOpcode() == ISD::SIGN_EXTEND ||
2674 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002675}
2676
2677static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002678 return N->getOpcode() == ISD::ZERO_EXTEND ||
2679 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002680}
2681
2682static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2683 unsigned Opcode = N->getOpcode();
2684 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2685 SDNode *N0 = N->getOperand(0).getNode();
2686 SDNode *N1 = N->getOperand(1).getNode();
2687 return N0->hasOneUse() && N1->hasOneUse() &&
2688 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2689 }
2690 return false;
2691}
2692
2693static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2694 unsigned Opcode = N->getOpcode();
2695 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2696 SDNode *N0 = N->getOperand(0).getNode();
2697 SDNode *N1 = N->getOperand(1).getNode();
2698 return N0->hasOneUse() && N1->hasOneUse() &&
2699 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2700 }
2701 return false;
2702}
2703
Tim Northover70666e72018-06-20 12:09:01 +00002704SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2705 SelectionDAG &DAG) const {
2706 // The rounding mode is in bits 23:22 of the FPSCR.
2707 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2708 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2709 // so that the shift + and get folded into a bitfield extract.
2710 SDLoc dl(Op);
2711
2712 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2713 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2714 MVT::i64));
2715 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2716 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2717 DAG.getConstant(1U << 22, dl, MVT::i32));
2718 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2719 DAG.getConstant(22, dl, MVT::i32));
2720 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2721 DAG.getConstant(3, dl, MVT::i32));
2722}
2723
Chad Rosierd9d0f862014-10-08 02:31:24 +00002724static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2725 // Multiplications are only custom-lowered for 128-bit vectors so that
2726 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2727 EVT VT = Op.getValueType();
2728 assert(VT.is128BitVector() && VT.isInteger() &&
2729 "unexpected type for custom-lowering ISD::MUL");
2730 SDNode *N0 = Op.getOperand(0).getNode();
2731 SDNode *N1 = Op.getOperand(1).getNode();
2732 unsigned NewOpc = 0;
2733 bool isMLA = false;
2734 bool isN0SExt = isSignExtended(N0, DAG);
2735 bool isN1SExt = isSignExtended(N1, DAG);
2736 if (isN0SExt && isN1SExt)
2737 NewOpc = AArch64ISD::SMULL;
2738 else {
2739 bool isN0ZExt = isZeroExtended(N0, DAG);
2740 bool isN1ZExt = isZeroExtended(N1, DAG);
2741 if (isN0ZExt && isN1ZExt)
2742 NewOpc = AArch64ISD::UMULL;
2743 else if (isN1SExt || isN1ZExt) {
2744 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2745 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2746 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2747 NewOpc = AArch64ISD::SMULL;
2748 isMLA = true;
2749 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2750 NewOpc = AArch64ISD::UMULL;
2751 isMLA = true;
2752 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2753 std::swap(N0, N1);
2754 NewOpc = AArch64ISD::UMULL;
2755 isMLA = true;
2756 }
2757 }
2758
2759 if (!NewOpc) {
2760 if (VT == MVT::v2i64)
2761 // Fall through to expand this. It is not legal.
2762 return SDValue();
2763 else
2764 // Other vector multiplications are legal.
2765 return Op;
2766 }
2767 }
2768
2769 // Legalize to a S/UMULL instruction
2770 SDLoc DL(Op);
2771 SDValue Op0;
2772 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2773 if (!isMLA) {
2774 Op0 = skipExtensionForVectorMULL(N0, DAG);
2775 assert(Op0.getValueType().is64BitVector() &&
2776 Op1.getValueType().is64BitVector() &&
2777 "unexpected types for extended operands to VMULL");
2778 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2779 }
2780 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2781 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2782 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2783 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2784 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2785 EVT Op1VT = Op1.getValueType();
2786 return DAG.getNode(N0->getOpcode(), DL, VT,
2787 DAG.getNode(NewOpc, DL, VT,
2788 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2789 DAG.getNode(NewOpc, DL, VT,
2790 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2791}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002792
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002793SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2794 SelectionDAG &DAG) const {
2795 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2796 SDLoc dl(Op);
2797 switch (IntNo) {
2798 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002799 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002800 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2801 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2802 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002803 case Intrinsic::aarch64_neon_abs: {
2804 EVT Ty = Op.getValueType();
2805 if (Ty == MVT::i64) {
2806 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2807 Op.getOperand(1));
2808 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2809 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2810 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2811 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2812 } else {
2813 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2814 }
2815 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002816 case Intrinsic::aarch64_neon_smax:
2817 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2818 Op.getOperand(1), Op.getOperand(2));
2819 case Intrinsic::aarch64_neon_umax:
2820 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2821 Op.getOperand(1), Op.getOperand(2));
2822 case Intrinsic::aarch64_neon_smin:
2823 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2824 Op.getOperand(1), Op.getOperand(2));
2825 case Intrinsic::aarch64_neon_umin:
2826 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2827 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002828
2829 case Intrinsic::localaddress: {
Mandeep Singh Grang70d484d2019-02-01 21:41:33 +00002830 const auto &MF = DAG.getMachineFunction();
2831 const auto *RegInfo = Subtarget->getRegisterInfo();
2832 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002833 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2834 Op.getSimpleValueType());
2835 }
2836
2837 case Intrinsic::eh_recoverfp: {
2838 // FIXME: This needs to be implemented to correctly handle highly aligned
2839 // stack objects. For now we simply return the incoming FP. Refer D53541
2840 // for more details.
2841 SDValue FnOp = Op.getOperand(1);
2842 SDValue IncomingFPOp = Op.getOperand(2);
2843 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2844 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2845 if (!Fn)
2846 report_fatal_error(
2847 "llvm.eh.recoverfp must take a function as the first argument");
2848 return IncomingFPOp;
2849 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002850 }
2851}
2852
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002853// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2854static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2855 EVT VT, EVT MemVT,
2856 SelectionDAG &DAG) {
2857 assert(VT.isVector() && "VT should be a vector type");
2858 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2859
2860 SDValue Value = ST->getValue();
2861
2862 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2863 // the word lane which represent the v4i8 subvector. It optimizes the store
2864 // to:
2865 //
2866 // xtn v0.8b, v0.8h
2867 // str s0, [x0]
2868
2869 SDValue Undef = DAG.getUNDEF(MVT::i16);
2870 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2871 {Undef, Undef, Undef, Undef});
2872
2873 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2874 Value, UndefVec);
2875 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2876
2877 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2878 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2879 Trunc, DAG.getConstant(0, DL, MVT::i64));
2880
2881 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2882 ST->getBasePtr(), ST->getMemOperand());
2883}
2884
2885// Custom lowering for any store, vector or scalar and/or default or with
2886// a truncate operations. Currently only custom lower truncate operation
2887// from vector v4i16 to v4i8.
2888SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2889 SelectionDAG &DAG) const {
2890 SDLoc Dl(Op);
2891 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2892 assert (StoreNode && "Can only custom lower store nodes");
2893
2894 SDValue Value = StoreNode->getValue();
2895
2896 EVT VT = Value.getValueType();
2897 EVT MemVT = StoreNode->getMemoryVT();
2898
2899 assert (VT.isVector() && "Can only custom lower vector store types");
2900
2901 unsigned AS = StoreNode->getAddressSpace();
2902 unsigned Align = StoreNode->getAlignment();
2903 if (Align < MemVT.getStoreSize() &&
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00002904 !allowsMisalignedMemoryAccesses(
2905 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002906 return scalarizeVectorStore(StoreNode, DAG);
2907 }
2908
2909 if (StoreNode->isTruncatingStore()) {
2910 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2911 }
2912
2913 return SDValue();
2914}
2915
Tim Northover3b0846e2014-05-24 12:50:23 +00002916SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2917 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002918 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2919 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002920
Tim Northover3b0846e2014-05-24 12:50:23 +00002921 switch (Op.getOpcode()) {
2922 default:
2923 llvm_unreachable("unimplemented operand");
2924 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002925 case ISD::BITCAST:
2926 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002927 case ISD::GlobalAddress:
2928 return LowerGlobalAddress(Op, DAG);
2929 case ISD::GlobalTLSAddress:
2930 return LowerGlobalTLSAddress(Op, DAG);
2931 case ISD::SETCC:
2932 return LowerSETCC(Op, DAG);
2933 case ISD::BR_CC:
2934 return LowerBR_CC(Op, DAG);
2935 case ISD::SELECT:
2936 return LowerSELECT(Op, DAG);
2937 case ISD::SELECT_CC:
2938 return LowerSELECT_CC(Op, DAG);
2939 case ISD::JumpTable:
2940 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002941 case ISD::BR_JT:
2942 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002943 case ISD::ConstantPool:
2944 return LowerConstantPool(Op, DAG);
2945 case ISD::BlockAddress:
2946 return LowerBlockAddress(Op, DAG);
2947 case ISD::VASTART:
2948 return LowerVASTART(Op, DAG);
2949 case ISD::VACOPY:
2950 return LowerVACOPY(Op, DAG);
2951 case ISD::VAARG:
2952 return LowerVAARG(Op, DAG);
2953 case ISD::ADDC:
2954 case ISD::ADDE:
2955 case ISD::SUBC:
2956 case ISD::SUBE:
2957 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2958 case ISD::SADDO:
2959 case ISD::UADDO:
2960 case ISD::SSUBO:
2961 case ISD::USUBO:
2962 case ISD::SMULO:
2963 case ISD::UMULO:
2964 return LowerXALUO(Op, DAG);
2965 case ISD::FADD:
2966 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2967 case ISD::FSUB:
2968 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2969 case ISD::FMUL:
2970 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2971 case ISD::FDIV:
2972 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2973 case ISD::FP_ROUND:
2974 return LowerFP_ROUND(Op, DAG);
2975 case ISD::FP_EXTEND:
2976 return LowerFP_EXTEND(Op, DAG);
2977 case ISD::FRAMEADDR:
2978 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002979 case ISD::SPONENTRY:
2980 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002981 case ISD::RETURNADDR:
2982 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002983 case ISD::ADDROFRETURNADDR:
2984 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002985 case ISD::INSERT_VECTOR_ELT:
2986 return LowerINSERT_VECTOR_ELT(Op, DAG);
2987 case ISD::EXTRACT_VECTOR_ELT:
2988 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2989 case ISD::BUILD_VECTOR:
2990 return LowerBUILD_VECTOR(Op, DAG);
2991 case ISD::VECTOR_SHUFFLE:
2992 return LowerVECTOR_SHUFFLE(Op, DAG);
2993 case ISD::EXTRACT_SUBVECTOR:
2994 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2995 case ISD::SRA:
2996 case ISD::SRL:
2997 case ISD::SHL:
2998 return LowerVectorSRA_SRL_SHL(Op, DAG);
2999 case ISD::SHL_PARTS:
3000 return LowerShiftLeftParts(Op, DAG);
3001 case ISD::SRL_PARTS:
3002 case ISD::SRA_PARTS:
3003 return LowerShiftRightParts(Op, DAG);
3004 case ISD::CTPOP:
3005 return LowerCTPOP(Op, DAG);
3006 case ISD::FCOPYSIGN:
3007 return LowerFCOPYSIGN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003008 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00003009 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003010 case ISD::XOR:
3011 return LowerXOR(Op, DAG);
3012 case ISD::PREFETCH:
3013 return LowerPREFETCH(Op, DAG);
3014 case ISD::SINT_TO_FP:
3015 case ISD::UINT_TO_FP:
3016 return LowerINT_TO_FP(Op, DAG);
3017 case ISD::FP_TO_SINT:
3018 case ISD::FP_TO_UINT:
3019 return LowerFP_TO_INT(Op, DAG);
3020 case ISD::FSINCOS:
3021 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00003022 case ISD::FLT_ROUNDS_:
3023 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00003024 case ISD::MUL:
3025 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00003026 case ISD::INTRINSIC_WO_CHAIN:
3027 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00003028 case ISD::STORE:
3029 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00003030 case ISD::VECREDUCE_ADD:
3031 case ISD::VECREDUCE_SMAX:
3032 case ISD::VECREDUCE_SMIN:
3033 case ISD::VECREDUCE_UMAX:
3034 case ISD::VECREDUCE_UMIN:
3035 case ISD::VECREDUCE_FMAX:
3036 case ISD::VECREDUCE_FMIN:
3037 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00003038 case ISD::ATOMIC_LOAD_SUB:
3039 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00003040 case ISD::ATOMIC_LOAD_AND:
3041 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00003042 case ISD::DYNAMIC_STACKALLOC:
3043 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003044 }
3045}
3046
Tim Northover3b0846e2014-05-24 12:50:23 +00003047//===----------------------------------------------------------------------===//
3048// Calling Convention Implementation
3049//===----------------------------------------------------------------------===//
3050
Robin Morisset039781e2014-08-29 21:53:01 +00003051/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00003052CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3053 bool IsVarArg) const {
3054 switch (CC) {
3055 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00003056 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00003057 case CallingConv::WebKit_JS:
3058 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00003059 case CallingConv::GHC:
3060 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00003061 case CallingConv::C:
3062 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00003063 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00003064 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00003065 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00003066 if (Subtarget->isTargetWindows() && IsVarArg)
3067 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00003068 if (!Subtarget->isTargetDarwin())
3069 return CC_AArch64_AAPCS;
3070 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00003071 case CallingConv::Win64:
3072 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00003073 case CallingConv::AArch64_VectorCall:
3074 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00003075 }
3076}
3077
Tim Northover406024a2016-08-10 21:44:01 +00003078CCAssignFn *
3079AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3080 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3081 : RetCC_AArch64_AAPCS;
3082}
3083
Tim Northover3b0846e2014-05-24 12:50:23 +00003084SDValue AArch64TargetLowering::LowerFormalArguments(
3085 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003086 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3087 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003088 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003089 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003090 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003091
3092 // Assign locations to all of the incoming arguments.
3093 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003094 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3095 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003096
3097 // At this point, Ins[].VT may already be promoted to i32. To correctly
3098 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3099 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3100 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3101 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3102 // LocVT.
3103 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003104 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003105 unsigned CurArgIdx = 0;
3106 for (unsigned i = 0; i != NumArgs; ++i) {
3107 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003108 if (Ins[i].isOrigArg()) {
3109 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3110 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003111
Andrew Trick05938a52015-02-16 18:10:47 +00003112 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003113 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3114 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003115 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3116 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3117 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3118 ValVT = MVT::i8;
3119 else if (ActualMVT == MVT::i16)
3120 ValVT = MVT::i16;
3121 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003122 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3123 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003124 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003125 assert(!Res && "Call operand has unhandled type");
3126 (void)Res;
3127 }
3128 assert(ArgLocs.size() == Ins.size());
3129 SmallVector<SDValue, 16> ArgValues;
3130 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3131 CCValAssign &VA = ArgLocs[i];
3132
3133 if (Ins[i].Flags.isByVal()) {
3134 // Byval is used for HFAs in the PCS, but the system should work in a
3135 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003136 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003137 int Size = Ins[i].Flags.getByValSize();
3138 unsigned NumRegs = (Size + 7) / 8;
3139
3140 // FIXME: This works on big-endian for composite byvals, which are the common
3141 // case. It should also work for fundamental types too.
3142 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003143 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003144 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003145 InVals.push_back(FrameIdxN);
3146
3147 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003148 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003149
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003150 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003151 // Arguments stored in registers.
3152 EVT RegVT = VA.getLocVT();
3153
3154 SDValue ArgValue;
3155 const TargetRegisterClass *RC;
3156
3157 if (RegVT == MVT::i32)
3158 RC = &AArch64::GPR32RegClass;
3159 else if (RegVT == MVT::i64)
3160 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003161 else if (RegVT == MVT::f16)
3162 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003163 else if (RegVT == MVT::f32)
3164 RC = &AArch64::FPR32RegClass;
3165 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3166 RC = &AArch64::FPR64RegClass;
3167 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3168 RC = &AArch64::FPR128RegClass;
Cullen Rhodes2a481762019-08-05 13:44:10 +00003169 else if (RegVT.isScalableVector() &&
3170 RegVT.getVectorElementType() == MVT::i1)
3171 RC = &AArch64::PPRRegClass;
3172 else if (RegVT.isScalableVector())
3173 RC = &AArch64::ZPRRegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003174 else
3175 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3176
3177 // Transform the arguments in physical registers into virtual ones.
3178 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3179 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3180
3181 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3182 // to 64 bits. Insert an assert[sz]ext to capture this, then
3183 // truncate to the right size.
3184 switch (VA.getLocInfo()) {
3185 default:
3186 llvm_unreachable("Unknown loc info!");
3187 case CCValAssign::Full:
3188 break;
Cullen Rhodes2a481762019-08-05 13:44:10 +00003189 case CCValAssign::Indirect:
3190 assert(VA.getValVT().isScalableVector() &&
3191 "Only scalable vectors can be passed indirectly");
3192 llvm_unreachable("Spilling of SVE vectors not yet implemented");
Tim Northover3b0846e2014-05-24 12:50:23 +00003193 case CCValAssign::BCvt:
3194 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3195 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003196 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003197 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003198 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003199 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3200 // nodes after our lowering.
3201 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003202 break;
3203 }
3204
3205 InVals.push_back(ArgValue);
3206
3207 } else { // VA.isRegLoc()
3208 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3209 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003210 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003211
3212 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003213 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3214 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003215 BEAlign = 8 - ArgSize;
3216
Matthias Braun941a7052016-07-28 18:40:00 +00003217 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003218
3219 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003220 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003221 SDValue ArgValue;
3222
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003223 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003224 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003225 MVT MemVT = VA.getValVT();
3226
Tim Northover47e003c2014-05-26 17:21:53 +00003227 switch (VA.getLocInfo()) {
3228 default:
3229 break;
Tim Northover6890add2014-06-03 13:54:53 +00003230 case CCValAssign::BCvt:
3231 MemVT = VA.getLocVT();
3232 break;
Cullen Rhodes2a481762019-08-05 13:44:10 +00003233 case CCValAssign::Indirect:
3234 assert(VA.getValVT().isScalableVector() &&
3235 "Only scalable vectors can be passed indirectly");
3236 llvm_unreachable("Spilling of SVE vectors not yet implemented");
Tim Northover47e003c2014-05-26 17:21:53 +00003237 case CCValAssign::SExt:
3238 ExtType = ISD::SEXTLOAD;
3239 break;
3240 case CCValAssign::ZExt:
3241 ExtType = ISD::ZEXTLOAD;
3242 break;
3243 case CCValAssign::AExt:
3244 ExtType = ISD::EXTLOAD;
3245 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003246 }
3247
Alex Lorenze40c8a22015-08-11 23:09:45 +00003248 ArgValue = DAG.getExtLoad(
3249 ExtType, DL, VA.getLocVT(), Chain, FIN,
3250 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003251 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003252
Tim Northover3b0846e2014-05-24 12:50:23 +00003253 InVals.push_back(ArgValue);
3254 }
3255 }
3256
3257 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003258 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003259 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003260 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003261 // The AAPCS variadic function ABI is identical to the non-variadic
3262 // one. As a result there may be more arguments in registers and we should
3263 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003264 // Win64 variadic functions also pass arguments in registers, but all float
3265 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003266 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3267 }
3268
Tim Northover3b0846e2014-05-24 12:50:23 +00003269 // This will point to the next argument passed via stack.
3270 unsigned StackOffset = CCInfo.getNextStackOffset();
3271 // We currently pass all varargs at 8-byte alignment.
3272 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003273 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003274
3275 if (MFI.hasMustTailInVarArgFunc()) {
3276 SmallVector<MVT, 2> RegParmTypes;
3277 RegParmTypes.push_back(MVT::i64);
3278 RegParmTypes.push_back(MVT::f128);
3279 // Compute the set of forwarded registers. The rest are scratch.
3280 SmallVectorImpl<ForwardedRegister> &Forwards =
3281 FuncInfo->getForwardedMustTailRegParms();
3282 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3283 CC_AArch64_AAPCS);
Reid Klecknerb7a78c72019-05-24 01:27:20 +00003284
3285 // Conservatively forward X8, since it might be used for aggregate return.
3286 if (!CCInfo.isAllocated(AArch64::X8)) {
3287 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3288 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3289 }
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003290 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003291 }
3292
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003293 // On Windows, InReg pointers must be returned, so record the pointer in a
3294 // virtual register at the start of the function so it can be returned in the
3295 // epilogue.
3296 if (IsWin64) {
3297 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3298 if (Ins[I].Flags.isInReg()) {
3299 assert(!FuncInfo->getSRetReturnReg());
3300
3301 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3302 unsigned Reg =
3303 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3304 FuncInfo->setSRetReturnReg(Reg);
3305
3306 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3307 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3308 break;
3309 }
3310 }
3311 }
3312
Tim Northover3b0846e2014-05-24 12:50:23 +00003313 unsigned StackArgSize = CCInfo.getNextStackOffset();
3314 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3315 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3316 // This is a non-standard ABI so by fiat I say we're allowed to make full
3317 // use of the stack area to be popped, which must be aligned to 16 bytes in
3318 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003319 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003320
3321 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3322 // a multiple of 16.
3323 FuncInfo->setArgumentStackToRestore(StackArgSize);
3324
3325 // This realignment carries over to the available bytes below. Our own
3326 // callers will guarantee the space is free by giving an aligned value to
3327 // CALLSEQ_START.
3328 }
3329 // Even if we're not expected to free up the space, it's useful to know how
3330 // much is there while considering tail calls (because we can reuse it).
3331 FuncInfo->setBytesInStackArgArea(StackArgSize);
3332
Tri Vo6c47c622018-09-22 22:17:50 +00003333 if (Subtarget->hasCustomCallingConv())
3334 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3335
Tim Northover3b0846e2014-05-24 12:50:23 +00003336 return Chain;
3337}
3338
3339void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003340 SelectionDAG &DAG,
3341 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003342 SDValue &Chain) const {
3343 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003344 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003345 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003346 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003347 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003348
3349 SmallVector<SDValue, 8> MemOps;
3350
3351 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3352 AArch64::X3, AArch64::X4, AArch64::X5,
3353 AArch64::X6, AArch64::X7 };
3354 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003355 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003356
3357 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3358 int GPRIdx = 0;
3359 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003360 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003361 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003362 if (GPRSaveSize & 15)
3363 // The extra size here, if triggered, will always be 8.
3364 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3365 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003366 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003367
Mehdi Amini44ede332015-07-09 02:09:04 +00003368 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003369
3370 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3371 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3372 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003373 SDValue Store = DAG.getStore(
3374 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003375 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003376 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3377 GPRIdx,
3378 (i - FirstVariadicGPR) * 8)
3379 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003380 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003381 FIN =
3382 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003383 }
3384 }
3385 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3386 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3387
Martin Storsjo2f24e932017-07-17 20:05:19 +00003388 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003389 static const MCPhysReg FPRArgRegs[] = {
3390 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3391 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3392 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003393 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003394
3395 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3396 int FPRIdx = 0;
3397 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003398 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003399
Mehdi Amini44ede332015-07-09 02:09:04 +00003400 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003401
3402 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3403 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3404 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3405
Alex Lorenze40c8a22015-08-11 23:09:45 +00003406 SDValue Store = DAG.getStore(
3407 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003408 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003409 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003410 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3411 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003412 }
3413 }
3414 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3415 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3416 }
3417
3418 if (!MemOps.empty()) {
3419 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3420 }
3421}
3422
3423/// LowerCallResult - Lower the result values of a call into the
3424/// appropriate copies out of appropriate physical registers.
3425SDValue AArch64TargetLowering::LowerCallResult(
3426 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003427 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3428 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003429 SDValue ThisVal) const {
3430 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3431 ? RetCC_AArch64_WebKit_JS
3432 : RetCC_AArch64_AAPCS;
3433 // Assign locations to each value returned by this call.
3434 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003435 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3436 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003437 CCInfo.AnalyzeCallResult(Ins, RetCC);
3438
3439 // Copy all of the result registers out of their specified physreg.
3440 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3441 CCValAssign VA = RVLocs[i];
3442
3443 // Pass 'this' value directly from the argument to return value, to avoid
3444 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003445 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003446 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3447 "unexpected return calling convention register assignment");
3448 InVals.push_back(ThisVal);
3449 continue;
3450 }
3451
3452 SDValue Val =
3453 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3454 Chain = Val.getValue(1);
3455 InFlag = Val.getValue(2);
3456
3457 switch (VA.getLocInfo()) {
3458 default:
3459 llvm_unreachable("Unknown loc info!");
3460 case CCValAssign::Full:
3461 break;
3462 case CCValAssign::BCvt:
3463 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3464 break;
3465 }
3466
3467 InVals.push_back(Val);
3468 }
3469
3470 return Chain;
3471}
3472
Matthias Braun1af14142016-09-13 19:27:38 +00003473/// Return true if the calling convention is one that we can guarantee TCO for.
3474static bool canGuaranteeTCO(CallingConv::ID CC) {
3475 return CC == CallingConv::Fast;
3476}
3477
3478/// Return true if we might ever do TCO for calls with this calling convention.
3479static bool mayTailCallThisCC(CallingConv::ID CC) {
3480 switch (CC) {
3481 case CallingConv::C:
3482 case CallingConv::PreserveMost:
3483 case CallingConv::Swift:
3484 return true;
3485 default:
3486 return canGuaranteeTCO(CC);
3487 }
3488}
3489
Tim Northover3b0846e2014-05-24 12:50:23 +00003490bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3491 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003492 const SmallVectorImpl<ISD::OutputArg> &Outs,
3493 const SmallVectorImpl<SDValue> &OutVals,
3494 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003495 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003496 return false;
3497
Matthias Braun8d414362016-03-30 22:46:04 +00003498 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003499 const Function &CallerF = MF.getFunction();
3500 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003501 bool CCMatch = CallerCC == CalleeCC;
3502
3503 // Byval parameters hand the function a pointer directly into the stack area
3504 // we want to reuse during a tail call. Working around this *is* possible (see
3505 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003506 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3507 e = CallerF.arg_end();
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003508 i != e; ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003509 if (i->hasByValAttr())
3510 return false;
3511
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003512 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3513 // In this case, it is necessary to save/restore X0 in the callee. Tail
3514 // call opt interferes with this. So we disable tail call opt when the
3515 // caller has an argument with "inreg" attribute.
3516
3517 // FIXME: Check whether the callee also has an "inreg" argument.
3518 if (i->hasInRegAttr())
3519 return false;
3520 }
3521
Matthias Braun1af14142016-09-13 19:27:38 +00003522 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3523 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003524
Oliver Stannard12993dd2014-08-18 12:42:15 +00003525 // Externally-defined functions with weak linkage should not be
3526 // tail-called on AArch64 when the OS does not support dynamic
3527 // pre-emption of symbols, as the AAELF spec requires normal calls
3528 // to undefined weak functions to be replaced with a NOP or jump to the
3529 // next instruction. The behaviour of branch instructions in this
3530 // situation (as used for tail calls) is implementation-defined, so we
3531 // cannot rely on the linker replacing the tail call with a return.
3532 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3533 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003534 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003535 if (GV->hasExternalWeakLinkage() &&
3536 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003537 return false;
3538 }
3539
Tim Northover3b0846e2014-05-24 12:50:23 +00003540 // Now we search for cases where we can use a tail call without changing the
3541 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3542 // concept.
3543
3544 // I want anyone implementing a new calling convention to think long and hard
3545 // about this assert.
3546 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3547 "Unexpected variadic calling convention");
3548
Matthias Braun8d414362016-03-30 22:46:04 +00003549 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003550 if (isVarArg && !Outs.empty()) {
3551 // At least two cases here: if caller is fastcc then we can't have any
3552 // memory arguments (we'd be expected to clean up the stack afterwards). If
3553 // caller is C then we could potentially use its argument area.
3554
3555 // FIXME: for now we take the most conservative of these in both cases:
3556 // disallow all variadic memory operands.
3557 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003558 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003559
3560 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003561 for (const CCValAssign &ArgLoc : ArgLocs)
3562 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003563 return false;
3564 }
3565
Matthias Braun8d414362016-03-30 22:46:04 +00003566 // Check that the call results are passed in the same way.
3567 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3568 CCAssignFnForCall(CalleeCC, isVarArg),
3569 CCAssignFnForCall(CallerCC, isVarArg)))
3570 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003571 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003572 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3573 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003574 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003575 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003576 if (Subtarget->hasCustomCallingConv()) {
3577 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3578 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3579 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003580 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003581 return false;
3582 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003583
3584 // Nothing more to check if the callee is taking no arguments
3585 if (Outs.empty())
3586 return true;
3587
3588 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003589 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003590
3591 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3592
3593 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3594
Matthias Braun74a0bd32016-04-13 21:43:16 +00003595 // If the stack arguments for this call do not fit into our own save area then
3596 // the call cannot be made tail.
3597 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3598 return false;
3599
Matthias Braun46b0f032016-04-14 01:10:42 +00003600 const MachineRegisterInfo &MRI = MF.getRegInfo();
3601 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3602 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003603
3604 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003605}
3606
3607SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3608 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003609 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003610 int ClobberedFI) const {
3611 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003612 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3613 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003614
3615 // Include the original chain at the beginning of the list. When this is
3616 // used by target LowerCall hooks, this helps legalize find the
3617 // CALLSEQ_BEGIN node.
3618 ArgChains.push_back(Chain);
3619
3620 // Add a chain value for each stack argument corresponding
3621 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3622 UE = DAG.getEntryNode().getNode()->use_end();
3623 U != UE; ++U)
3624 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3625 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3626 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003627 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003628 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003629 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003630
3631 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3632 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3633 ArgChains.push_back(SDValue(L, 1));
3634 }
3635
3636 // Build a tokenfactor for all the chains.
3637 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3638}
3639
3640bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3641 bool TailCallOpt) const {
3642 return CallCC == CallingConv::Fast && TailCallOpt;
3643}
3644
Tim Northover3b0846e2014-05-24 12:50:23 +00003645/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3646/// and add input and output parameter nodes.
3647SDValue
3648AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3649 SmallVectorImpl<SDValue> &InVals) const {
3650 SelectionDAG &DAG = CLI.DAG;
3651 SDLoc &DL = CLI.DL;
3652 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3653 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3654 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3655 SDValue Chain = CLI.Chain;
3656 SDValue Callee = CLI.Callee;
3657 bool &IsTailCall = CLI.IsTailCall;
3658 CallingConv::ID CallConv = CLI.CallConv;
3659 bool IsVarArg = CLI.IsVarArg;
3660
3661 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003662 bool IsThisReturn = false;
3663
3664 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3665 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3666 bool IsSibCall = false;
3667
3668 if (IsTailCall) {
3669 // Check if it's really possible to do a tail call.
3670 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003671 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003672 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003673 report_fatal_error("failed to perform tail call elimination on a call "
3674 "site marked musttail");
3675
3676 // A sibling call is one where we're under the usual C ABI and not planning
3677 // to change that but can still do a tail call:
3678 if (!TailCallOpt && IsTailCall)
3679 IsSibCall = true;
3680
3681 if (IsTailCall)
3682 ++NumTailCalls;
3683 }
3684
3685 // Analyze operands of the call, assigning locations to each operand.
3686 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003687 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3688 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003689
3690 if (IsVarArg) {
3691 // Handle fixed and variable vector arguments differently.
3692 // Variable vector arguments always go into memory.
3693 unsigned NumArgs = Outs.size();
3694
3695 for (unsigned i = 0; i != NumArgs; ++i) {
3696 MVT ArgVT = Outs[i].VT;
3697 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3698 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3699 /*IsVarArg=*/ !Outs[i].IsFixed);
3700 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3701 assert(!Res && "Call operand has unhandled type");
3702 (void)Res;
3703 }
3704 } else {
3705 // At this point, Outs[].VT may already be promoted to i32. To correctly
3706 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3707 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3708 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3709 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3710 // LocVT.
3711 unsigned NumArgs = Outs.size();
3712 for (unsigned i = 0; i != NumArgs; ++i) {
3713 MVT ValVT = Outs[i].VT;
3714 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003715 EVT ActualVT = getValueType(DAG.getDataLayout(),
3716 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003717 /*AllowUnknown*/ true);
3718 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3719 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3720 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003721 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003722 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003723 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003724 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003725
3726 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003727 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003728 assert(!Res && "Call operand has unhandled type");
3729 (void)Res;
3730 }
3731 }
3732
3733 // Get a count of how many bytes are to be pushed on the stack.
3734 unsigned NumBytes = CCInfo.getNextStackOffset();
3735
3736 if (IsSibCall) {
3737 // Since we're not changing the ABI to make this a tail call, the memory
3738 // operands are already available in the caller's incoming argument space.
3739 NumBytes = 0;
3740 }
3741
3742 // FPDiff is the byte offset of the call's argument area from the callee's.
3743 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3744 // by this amount for a tail call. In a sibling call it must be 0 because the
3745 // caller will deallocate the entire stack and the callee still expects its
3746 // arguments to begin at SP+0. Completely unused for non-tail calls.
3747 int FPDiff = 0;
3748
3749 if (IsTailCall && !IsSibCall) {
3750 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3751
3752 // Since callee will pop argument stack as a tail call, we must keep the
3753 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003754 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003755
3756 // FPDiff will be negative if this tail call requires more space than we
3757 // would automatically have in our incoming argument space. Positive if we
3758 // can actually shrink the stack.
3759 FPDiff = NumReusableBytes - NumBytes;
3760
3761 // The stack pointer must be 16-byte aligned at all times it's used for a
3762 // memory operation, which in practice means at *all* times and in
3763 // particular across call boundaries. Therefore our own arguments started at
3764 // a 16-byte aligned SP and the delta applied for the tail call should
3765 // satisfy the same constraint.
3766 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3767 }
3768
3769 // Adjust the stack pointer for the new arguments...
3770 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003771 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003772 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003773
Mehdi Amini44ede332015-07-09 02:09:04 +00003774 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3775 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003776
3777 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3778 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003779 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003780
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003781 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3782 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3783 for (const auto &F : Forwards) {
3784 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3785 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3786 }
3787 }
3788
Tim Northover3b0846e2014-05-24 12:50:23 +00003789 // Walk the register/memloc assignments, inserting copies/loads.
3790 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3791 ++i, ++realArgIdx) {
3792 CCValAssign &VA = ArgLocs[i];
3793 SDValue Arg = OutVals[realArgIdx];
3794 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3795
3796 // Promote the value if needed.
3797 switch (VA.getLocInfo()) {
3798 default:
3799 llvm_unreachable("Unknown loc info!");
3800 case CCValAssign::Full:
3801 break;
3802 case CCValAssign::SExt:
3803 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3804 break;
3805 case CCValAssign::ZExt:
3806 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3807 break;
3808 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003809 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3810 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3811 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3812 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3813 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003814 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3815 break;
3816 case CCValAssign::BCvt:
3817 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3818 break;
3819 case CCValAssign::FPExt:
3820 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3821 break;
Cullen Rhodes2a481762019-08-05 13:44:10 +00003822 case CCValAssign::Indirect:
3823 assert(VA.getValVT().isScalableVector() &&
3824 "Only scalable vectors can be passed indirectly");
3825 llvm_unreachable("Spilling of SVE vectors not yet implemented");
Tim Northover3b0846e2014-05-24 12:50:23 +00003826 }
3827
3828 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003829 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3830 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003831 assert(VA.getLocVT() == MVT::i64 &&
3832 "unexpected calling convention register assignment");
3833 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3834 "unexpected use of 'returned'");
3835 IsThisReturn = true;
3836 }
3837 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3838 } else {
3839 assert(VA.isMemLoc());
3840
3841 SDValue DstAddr;
3842 MachinePointerInfo DstInfo;
3843
3844 // FIXME: This works on big-endian for composite byvals, which are the
3845 // common case. It should also work for fundamental types too.
3846 uint32_t BEAlign = 0;
3847 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003848 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003849 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003850 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3851 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003852 if (OpSize < 8)
3853 BEAlign = 8 - OpSize;
3854 }
3855 unsigned LocMemOffset = VA.getLocMemOffset();
3856 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003857 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003858 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003859
3860 if (IsTailCall) {
3861 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003862 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003863
Mehdi Amini44ede332015-07-09 02:09:04 +00003864 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003865 DstInfo =
3866 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003867
3868 // Make sure any stack arguments overlapping with where we're storing
3869 // are loaded before this eventual operation. Otherwise they'll be
3870 // clobbered.
3871 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3872 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003873 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003874
Mehdi Amini44ede332015-07-09 02:09:04 +00003875 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003876 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3877 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003878 }
3879
3880 if (Outs[i].Flags.isByVal()) {
3881 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003882 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003883 SDValue Cpy = DAG.getMemcpy(
3884 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003885 /*isVol = */ false, /*AlwaysInline = */ false,
3886 /*isTailCall = */ false,
3887 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003888
3889 MemOpChains.push_back(Cpy);
3890 } else {
3891 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3892 // promoted to a legal register type i32, we should truncate Arg back to
3893 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003894 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3895 VA.getValVT() == MVT::i16)
3896 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003897
Justin Lebar9c375812016-07-15 18:27:10 +00003898 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003899 MemOpChains.push_back(Store);
3900 }
3901 }
3902 }
3903
3904 if (!MemOpChains.empty())
3905 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3906
3907 // Build a sequence of copy-to-reg nodes chained together with token chain
3908 // and flag operands which copy the outgoing args into the appropriate regs.
3909 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003910 for (auto &RegToPass : RegsToPass) {
3911 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3912 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003913 InFlag = Chain.getValue(1);
3914 }
3915
3916 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3917 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3918 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003919 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3920 auto GV = G->getGlobal();
3921 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3922 AArch64II::MO_GOT) {
3923 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3924 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003925 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3926 assert(Subtarget->isTargetWindows() &&
3927 "Windows is the only supported COFF target");
3928 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003929 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003930 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003931 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3932 }
3933 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3934 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3935 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003936 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003937 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3938 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003939 } else {
3940 const char *Sym = S->getSymbol();
3941 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003942 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003943 }
3944
3945 // We don't usually want to end the call-sequence here because we would tidy
3946 // the frame up *after* the call, however in the ABI-changing tail-call case
3947 // we've carefully laid out the parameters so that when sp is reset they'll be
3948 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003949 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003950 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3951 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003952 InFlag = Chain.getValue(1);
3953 }
3954
3955 std::vector<SDValue> Ops;
3956 Ops.push_back(Chain);
3957 Ops.push_back(Callee);
3958
3959 if (IsTailCall) {
3960 // Each tail call may have to adjust the stack by a different amount, so
3961 // this information must travel along with the operation for eventual
3962 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003963 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003964 }
3965
3966 // Add argument registers to the end of the list so that they are known live
3967 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003968 for (auto &RegToPass : RegsToPass)
3969 Ops.push_back(DAG.getRegister(RegToPass.first,
3970 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003971
Cullen Rhodes2a481762019-08-05 13:44:10 +00003972 // Check callee args/returns for SVE registers and set calling convention
3973 // accordingly.
3974 if (CallConv == CallingConv::C) {
3975 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
3976 return Out.VT.isScalableVector();
3977 });
3978 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
3979 return In.VT.isScalableVector();
3980 });
3981
3982 if (CalleeInSVE || CalleeOutSVE)
3983 CallConv = CallingConv::AArch64_SVE_VectorCall;
3984 }
3985
Tim Northover3b0846e2014-05-24 12:50:23 +00003986 // Add a register mask operand representing the call-preserved registers.
3987 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003988 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003989 if (IsThisReturn) {
3990 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003991 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003992 if (!Mask) {
3993 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003994 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003995 }
3996 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003997 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003998
Tri Vo6c47c622018-09-22 22:17:50 +00003999 if (Subtarget->hasCustomCallingConv())
4000 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4001
Nick Desaulniers287a3be2018-09-07 20:58:57 +00004002 if (TRI->isAnyArgRegReserved(MF))
4003 TRI->emitReservedArgRegCallError(MF);
4004
Tim Northover3b0846e2014-05-24 12:50:23 +00004005 assert(Mask && "Missing call preserved mask for calling convention");
4006 Ops.push_back(DAG.getRegisterMask(Mask));
4007
4008 if (InFlag.getNode())
4009 Ops.push_back(InFlag);
4010
4011 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4012
4013 // If we're doing a tall call, use a TC_RETURN here rather than an
4014 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00004015 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00004016 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00004017 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00004018 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004019
4020 // Returns a chain and a flag for retval copy to use.
4021 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4022 InFlag = Chain.getValue(1);
4023
Rui Ueyamada00f2f2016-01-14 21:06:47 +00004024 uint64_t CalleePopBytes =
4025 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004026
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00004027 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4028 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4029 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00004030 if (!Ins.empty())
4031 InFlag = Chain.getValue(1);
4032
4033 // Handle result values, copying them out of physregs into vregs that we
4034 // return.
4035 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4036 InVals, IsThisReturn,
4037 IsThisReturn ? OutVals[0] : SDValue());
4038}
4039
4040bool AArch64TargetLowering::CanLowerReturn(
4041 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4042 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4043 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4044 ? RetCC_AArch64_WebKit_JS
4045 : RetCC_AArch64_AAPCS;
4046 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00004047 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00004048 return CCInfo.CheckReturn(Outs, RetCC);
4049}
4050
4051SDValue
4052AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4053 bool isVarArg,
4054 const SmallVectorImpl<ISD::OutputArg> &Outs,
4055 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004056 const SDLoc &DL, SelectionDAG &DAG) const {
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00004057 auto &MF = DAG.getMachineFunction();
4058 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4059
Tim Northover3b0846e2014-05-24 12:50:23 +00004060 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4061 ? RetCC_AArch64_WebKit_JS
4062 : RetCC_AArch64_AAPCS;
4063 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00004064 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4065 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00004066 CCInfo.AnalyzeReturn(Outs, RetCC);
4067
4068 // Copy the result values into the output registers.
4069 SDValue Flag;
4070 SmallVector<SDValue, 4> RetOps(1, Chain);
4071 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4072 ++i, ++realRVLocIdx) {
4073 CCValAssign &VA = RVLocs[i];
4074 assert(VA.isRegLoc() && "Can only return in registers!");
4075 SDValue Arg = OutVals[realRVLocIdx];
4076
4077 switch (VA.getLocInfo()) {
4078 default:
4079 llvm_unreachable("Unknown loc info!");
4080 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00004081 if (Outs[i].ArgVT == MVT::i1) {
4082 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4083 // value. This is strictly redundant on Darwin (which uses "zeroext
4084 // i1"), but will be optimised out before ISel.
4085 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4086 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4087 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004088 break;
4089 case CCValAssign::BCvt:
4090 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4091 break;
4092 }
4093
4094 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
4095 Flag = Chain.getValue(1);
4096 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4097 }
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00004098
4099 // Windows AArch64 ABIs require that for returning structs by value we copy
4100 // the sret argument into X0 for the return.
4101 // We saved the argument into a virtual register in the entry block,
4102 // so now we copy the value out and into X0.
4103 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4104 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4105 getPointerTy(MF.getDataLayout()));
4106
4107 unsigned RetValReg = AArch64::X0;
4108 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4109 Flag = Chain.getValue(1);
4110
4111 RetOps.push_back(
4112 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4113 }
4114
Manman Rencbe4f942015-12-16 21:04:19 +00004115 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4116 const MCPhysReg *I =
4117 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4118 if (I) {
4119 for (; *I; ++I) {
4120 if (AArch64::GPR64RegClass.contains(*I))
4121 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4122 else if (AArch64::FPR64RegClass.contains(*I))
4123 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4124 else
4125 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4126 }
4127 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004128
4129 RetOps[0] = Chain; // Update chain.
4130
4131 // Add the flag if we have it.
4132 if (Flag.getNode())
4133 RetOps.push_back(Flag);
4134
4135 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4136}
4137
4138//===----------------------------------------------------------------------===//
4139// Other Lowering Code
4140//===----------------------------------------------------------------------===//
4141
Joel Jonesa7c4a522017-04-21 17:31:03 +00004142SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4143 SelectionDAG &DAG,
4144 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004145 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4146 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004147}
4148
4149SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4150 SelectionDAG &DAG,
4151 unsigned Flag) const {
4152 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4153}
4154
4155SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4156 SelectionDAG &DAG,
4157 unsigned Flag) const {
4158 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4159 N->getOffset(), Flag);
4160}
4161
4162SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4163 SelectionDAG &DAG,
4164 unsigned Flag) const {
4165 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4166}
4167
4168// (loadGOT sym)
4169template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004170SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4171 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004172 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004173 SDLoc DL(N);
4174 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004175 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004176 // FIXME: Once remat is capable of dealing with instructions with register
4177 // operands, expand this into two nodes instead of using a wrapper node.
4178 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4179}
4180
4181// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4182template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004183SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4184 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004185 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004186 SDLoc DL(N);
4187 EVT Ty = getPointerTy(DAG.getDataLayout());
4188 const unsigned char MO_NC = AArch64II::MO_NC;
4189 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004190 AArch64ISD::WrapperLarge, DL, Ty,
4191 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4192 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4193 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4194 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004195}
4196
4197// (addlow (adrp %hi(sym)) %lo(sym))
4198template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004199SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4200 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004201 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004202 SDLoc DL(N);
4203 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004204 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004205 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004206 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004207 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4208 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4209}
4210
David Green9dd1d452018-08-22 11:31:39 +00004211// (adr sym)
4212template <class NodeTy>
4213SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4214 unsigned Flags) const {
4215 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4216 SDLoc DL(N);
4217 EVT Ty = getPointerTy(DAG.getDataLayout());
4218 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4219 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4220}
4221
Tim Northover3b0846e2014-05-24 12:50:23 +00004222SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4223 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004224 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004225 const GlobalValue *GV = GN->getGlobal();
Peter Collingbourne33773d52019-07-31 20:14:09 +00004226 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004227
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004228 if (OpFlags != AArch64II::MO_NO_FLAG)
4229 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4230 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004231
David Green9dd1d452018-08-22 11:31:39 +00004232 // This also catches the large code model case for Darwin, and tiny code
4233 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004234 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004235 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004236 }
4237
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004238 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004239 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004240 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004241 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004242 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004243 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004244 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004245 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004246 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4247 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004248 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004249 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4250 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4251 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004252}
4253
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004254/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004255/// and calls to compute the variable's address (for Darwin, currently) and
4256/// return an SDValue containing the final node.
4257
4258/// Darwin only has one TLS scheme which must be capable of dealing with the
4259/// fully general situation, in the worst case. This means:
4260/// + "extern __thread" declaration.
4261/// + Defined in a possibly unknown dynamic library.
4262///
4263/// The general system is that each __thread variable has a [3 x i64] descriptor
4264/// which contains information used by the runtime to calculate the address. The
4265/// only part of this the compiler needs to know about is the first xword, which
4266/// contains a function pointer that must be called with the address of the
4267/// entire descriptor in "x0".
4268///
4269/// Since this descriptor may be in a different unit, in general even the
4270/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4271/// is:
4272/// adrp x0, _var@TLVPPAGE
4273/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4274/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4275/// ; the function pointer
4276/// blr x1 ; Uses descriptor address in x0
4277/// ; Address of _var is now in x0.
4278///
4279/// If the address of _var's descriptor *is* known to the linker, then it can
4280/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4281/// a slight efficiency gain.
4282SDValue
4283AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4284 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004285 assert(Subtarget->isTargetDarwin() &&
4286 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004287
4288 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004289 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004290 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4291
4292 SDValue TLVPAddr =
4293 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4294 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4295
4296 // The first entry in the descriptor is a function pointer that we must call
4297 // to obtain the address of the variable.
4298 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004299 SDValue FuncTLVGet = DAG.getLoad(
4300 MVT::i64, DL, Chain, DescAddr,
4301 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4302 /* Alignment = */ 8,
4303 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4304 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004305 Chain = FuncTLVGet.getValue(1);
4306
Matthias Braun941a7052016-07-28 18:40:00 +00004307 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4308 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004309
4310 // TLS calls preserve all registers except those that absolutely must be
4311 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4312 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004313 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4314 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4315 if (Subtarget->hasCustomCallingConv())
4316 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004317
4318 // Finally, we can make the call. This is just a degenerate version of a
4319 // normal AArch64 call node: x0 takes the address of the descriptor, and
4320 // returns the address of the variable in this thread.
4321 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4322 Chain =
4323 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4324 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4325 DAG.getRegisterMask(Mask), Chain.getValue(1));
4326 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4327}
4328
4329/// When accessing thread-local variables under either the general-dynamic or
4330/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4331/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004332/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004333///
Kristof Beylsaea84612015-03-04 09:12:08 +00004334/// The sequence is:
4335/// adrp x0, :tlsdesc:var
4336/// ldr x1, [x0, #:tlsdesc_lo12:var]
4337/// add x0, x0, #:tlsdesc_lo12:var
4338/// .tlsdesccall var
4339/// blr x1
4340/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004341///
Kristof Beylsaea84612015-03-04 09:12:08 +00004342/// The above sequence must be produced unscheduled, to enable the linker to
4343/// optimize/relax this sequence.
4344/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4345/// above sequence, and expanded really late in the compilation flow, to ensure
4346/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004347SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4348 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004349 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004350 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004351
Kristof Beylsaea84612015-03-04 09:12:08 +00004352 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004353 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004354
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004355 Chain =
4356 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004357 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004358
4359 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4360}
4361
4362SDValue
4363AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4364 SelectionDAG &DAG) const {
4365 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004366 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4367 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004368 // Different choices can be made for the maximum size of the TLS area for a
4369 // module. For the small address model, the default TLS size is 16MiB and the
4370 // maximum TLS size is 4GiB.
4371 // FIXME: add -mtls-size command line option and make it control the 16MiB
4372 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004373 // FIXME: add tiny codemodel support. We currently generate the same code as
4374 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004375 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4376
4377 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004378
Kristof Beylsaea84612015-03-04 09:12:08 +00004379 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4380 if (Model == TLSModel::LocalDynamic)
4381 Model = TLSModel::GeneralDynamic;
4382 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004383
4384 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004385 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004386 SDLoc DL(Op);
4387 const GlobalValue *GV = GA->getGlobal();
4388
4389 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4390
4391 if (Model == TLSModel::LocalExec) {
4392 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004393 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004394 SDValue LoVar = DAG.getTargetGlobalAddress(
4395 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004396 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004397
Kristof Beylsaea84612015-03-04 09:12:08 +00004398 SDValue TPWithOff_lo =
4399 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004400 HiVar,
4401 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004402 0);
4403 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004404 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4405 LoVar,
4406 DAG.getTargetConstant(0, DL, MVT::i32)),
4407 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004408 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004409 } else if (Model == TLSModel::InitialExec) {
4410 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4411 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4412 } else if (Model == TLSModel::LocalDynamic) {
4413 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4414 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4415 // the beginning of the module's TLS region, followed by a DTPREL offset
4416 // calculation.
4417
4418 // These accesses will need deduplicating if there's more than one.
4419 AArch64FunctionInfo *MFI =
4420 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4421 MFI->incNumLocalDynamicTLSAccesses();
4422
Tim Northover3b0846e2014-05-24 12:50:23 +00004423 // The call needs a relocation too for linker relaxation. It doesn't make
4424 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4425 // the address.
4426 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4427 AArch64II::MO_TLS);
4428
4429 // Now we can calculate the offset from TPIDR_EL0 to this module's
4430 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004431 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004432
4433 // Now use :dtprel_whatever: operations to calculate this variable's offset
4434 // in its thread-storage area.
4435 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004436 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004437 SDValue LoVar = DAG.getTargetGlobalAddress(
4438 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004439 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4440
Kristof Beylsaea84612015-03-04 09:12:08 +00004441 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004442 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004443 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004444 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4445 DAG.getTargetConstant(0, DL, MVT::i32)),
4446 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004447 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004448 // The call needs a relocation too for linker relaxation. It doesn't make
4449 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4450 // the address.
4451 SDValue SymAddr =
4452 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4453
4454 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004455 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004456 } else
4457 llvm_unreachable("Unsupported ELF TLS access model");
4458
4459 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4460}
4461
Martin Storsjocc240962018-03-10 19:05:21 +00004462SDValue
4463AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4464 SelectionDAG &DAG) const {
4465 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4466
4467 SDValue Chain = DAG.getEntryNode();
4468 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4469 SDLoc DL(Op);
4470
4471 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4472
4473 // Load the ThreadLocalStoragePointer from the TEB
4474 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4475 SDValue TLSArray =
4476 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4477 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4478 Chain = TLSArray.getValue(1);
4479
4480 // Load the TLS index from the C runtime;
4481 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4482 // This also does the same as LOADgot, but using a generic i32 load,
4483 // while LOADgot only loads i64.
4484 SDValue TLSIndexHi =
4485 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4486 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4487 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4488 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4489 SDValue TLSIndex =
4490 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4491 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4492 Chain = TLSIndex.getValue(1);
4493
4494 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4495 // offset into the TLSArray.
4496 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4497 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4498 DAG.getConstant(3, DL, PtrVT));
4499 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4500 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4501 MachinePointerInfo());
4502 Chain = TLS.getValue(1);
4503
4504 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4505 const GlobalValue *GV = GA->getGlobal();
4506 SDValue TGAHi = DAG.getTargetGlobalAddress(
4507 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4508 SDValue TGALo = DAG.getTargetGlobalAddress(
4509 GV, DL, PtrVT, 0,
4510 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4511
4512 // Add the offset from the start of the .tls section (section base).
4513 SDValue Addr =
4514 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4515 DAG.getTargetConstant(0, DL, MVT::i32)),
4516 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004517 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004518 return Addr;
4519}
4520
Tim Northover3b0846e2014-05-24 12:50:23 +00004521SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4522 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004523 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004524 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004525 return LowerToTLSEmulatedModel(GA, DAG);
4526
Tim Northover3b0846e2014-05-24 12:50:23 +00004527 if (Subtarget->isTargetDarwin())
4528 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004529 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004530 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004531 if (Subtarget->isTargetWindows())
4532 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004533
4534 llvm_unreachable("Unexpected platform trying to use TLS");
4535}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004536
Tim Northover3b0846e2014-05-24 12:50:23 +00004537SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4538 SDValue Chain = Op.getOperand(0);
4539 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4540 SDValue LHS = Op.getOperand(2);
4541 SDValue RHS = Op.getOperand(3);
4542 SDValue Dest = Op.getOperand(4);
4543 SDLoc dl(Op);
4544
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004545 MachineFunction &MF = DAG.getMachineFunction();
4546 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4547 // will not be produced, as they are conditional branch instructions that do
4548 // not set flags.
4549 bool ProduceNonFlagSettingCondBr =
4550 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4551
Tim Northover3b0846e2014-05-24 12:50:23 +00004552 // Handle f128 first, since lowering it will result in comparing the return
4553 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4554 // is expecting to deal with.
4555 if (LHS.getValueType() == MVT::f128) {
4556 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4557
4558 // If softenSetCCOperands returned a scalar, we need to compare the result
4559 // against zero to select between true and false values.
4560 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004561 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004562 CC = ISD::SETNE;
4563 }
4564 }
4565
4566 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4567 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004568 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4569 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004570 // Only lower legal XALUO ops.
4571 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4572 return SDValue();
4573
4574 // The actual operation with overflow check.
4575 AArch64CC::CondCode OFCC;
4576 SDValue Value, Overflow;
4577 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4578
4579 if (CC == ISD::SETNE)
4580 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004581 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004582
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004583 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4584 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004585 }
4586
4587 if (LHS.getValueType().isInteger()) {
4588 assert((LHS.getValueType() == RHS.getValueType()) &&
4589 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4590
4591 // If the RHS of the comparison is zero, we can potentially fold this
4592 // to a specialized branch.
4593 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004594 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004595 if (CC == ISD::SETEQ) {
4596 // See if we can use a TBZ to fold in an AND as well.
4597 // TBZ has a smaller branch displacement than CBZ. If the offset is
4598 // out of bounds, a late MI-layer pass rewrites branches.
4599 // 403.gcc is an example that hits this case.
4600 if (LHS.getOpcode() == ISD::AND &&
4601 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4602 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4603 SDValue Test = LHS.getOperand(0);
4604 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004605 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004606 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4607 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004608 }
4609
4610 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4611 } else if (CC == ISD::SETNE) {
4612 // See if we can use a TBZ to fold in an AND as well.
4613 // TBZ has a smaller branch displacement than CBZ. If the offset is
4614 // out of bounds, a late MI-layer pass rewrites branches.
4615 // 403.gcc is an example that hits this case.
4616 if (LHS.getOpcode() == ISD::AND &&
4617 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4618 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4619 SDValue Test = LHS.getOperand(0);
4620 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004621 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004622 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4623 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004624 }
4625
4626 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004627 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4628 // Don't combine AND since emitComparison converts the AND to an ANDS
4629 // (a.k.a. TST) and the test in the test bit and branch instruction
4630 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004631 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004632 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004633 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004634 }
4635 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004636 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004637 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004638 // Don't combine AND since emitComparison converts the AND to an ANDS
4639 // (a.k.a. TST) and the test in the test bit and branch instruction
4640 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004641 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004642 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004643 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004644 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004645
4646 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004647 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004648 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4649 Cmp);
4650 }
4651
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004652 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4653 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004654
4655 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4656 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004657 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004658 AArch64CC::CondCode CC1, CC2;
4659 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004660 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004661 SDValue BR1 =
4662 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4663 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004664 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004665 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4666 Cmp);
4667 }
4668
4669 return BR1;
4670}
4671
4672SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4673 SelectionDAG &DAG) const {
4674 EVT VT = Op.getValueType();
4675 SDLoc DL(Op);
4676
4677 SDValue In1 = Op.getOperand(0);
4678 SDValue In2 = Op.getOperand(1);
4679 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004680
4681 if (SrcVT.bitsLT(VT))
4682 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4683 else if (SrcVT.bitsGT(VT))
4684 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004685
4686 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004687 uint64_t EltMask;
4688 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004689
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004690 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004691 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004692 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004693 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004694 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004695 DAG.getUNDEF(VecVT), In2);
4696 } else {
4697 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4698 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4699 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004700 };
4701
4702 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4703 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4704 EltMask = 0x80000000ULL;
4705 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004706 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004707 VecVT = MVT::v2i64;
4708
Eric Christopher572e03a2015-06-19 01:53:21 +00004709 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004710 // immediate moves cannot materialize that in a single instruction for
4711 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004712 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004713
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004714 setVecVal(AArch64::dsub);
4715 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4716 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4717 EltMask = 0x8000ULL;
4718 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004719 } else {
4720 llvm_unreachable("Invalid type for copysign!");
4721 }
4722
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004723 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004724
4725 // If we couldn't materialize the mask above, then the mask vector will be
4726 // the zero vector, and we need to negate it here.
4727 if (VT == MVT::f64 || VT == MVT::v2f64) {
4728 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4729 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4730 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4731 }
4732
4733 SDValue Sel =
4734 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4735
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004736 if (VT == MVT::f16)
4737 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004738 if (VT == MVT::f32)
4739 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4740 else if (VT == MVT::f64)
4741 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4742 else
4743 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4744}
4745
4746SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004747 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004748 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004749 return SDValue();
4750
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004751 if (!Subtarget->hasNEON())
4752 return SDValue();
4753
Tim Northover3b0846e2014-05-24 12:50:23 +00004754 // While there is no integer popcount instruction, it can
4755 // be more efficiently lowered to the following sequence that uses
4756 // AdvSIMD registers/instructions as long as the copies to/from
4757 // the AdvSIMD registers are cheap.
4758 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4759 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4760 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4761 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4762 SDValue Val = Op.getOperand(0);
4763 SDLoc DL(Op);
4764 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004765
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004766 if (VT == MVT::i32 || VT == MVT::i64) {
4767 if (VT == MVT::i32)
4768 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4769 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004770
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004771 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4772 SDValue UaddLV = DAG.getNode(
4773 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4774 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004775
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004776 if (VT == MVT::i64)
4777 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4778 return UaddLV;
4779 }
4780
4781 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4782 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4783 "Unexpected type for custom ctpop lowering");
4784
4785 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4786 Val = DAG.getBitcast(VT8Bit, Val);
4787 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4788
4789 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4790 unsigned EltSize = 8;
4791 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4792 while (EltSize != VT.getScalarSizeInBits()) {
4793 EltSize *= 2;
4794 NumElts /= 2;
4795 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4796 Val = DAG.getNode(
4797 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4798 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4799 }
4800
4801 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004802}
4803
4804SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4805
4806 if (Op.getValueType().isVector())
4807 return LowerVSETCC(Op, DAG);
4808
4809 SDValue LHS = Op.getOperand(0);
4810 SDValue RHS = Op.getOperand(1);
4811 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4812 SDLoc dl(Op);
4813
4814 // We chose ZeroOrOneBooleanContents, so use zero and one.
4815 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004816 SDValue TVal = DAG.getConstant(1, dl, VT);
4817 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004818
4819 // Handle f128 first, since one possible outcome is a normal integer
4820 // comparison which gets picked up by the next if statement.
4821 if (LHS.getValueType() == MVT::f128) {
4822 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4823
4824 // If softenSetCCOperands returned a scalar, use it.
4825 if (!RHS.getNode()) {
4826 assert(LHS.getValueType() == Op.getValueType() &&
4827 "Unexpected setcc expansion!");
4828 return LHS;
4829 }
4830 }
4831
4832 if (LHS.getValueType().isInteger()) {
4833 SDValue CCVal;
4834 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004835 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004836
4837 // Note that we inverted the condition above, so we reverse the order of
4838 // the true and false operands here. This will allow the setcc to be
4839 // matched to a single CSINC instruction.
4840 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4841 }
4842
4843 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004844 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4845 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004846
4847 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4848 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004849 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004850
4851 AArch64CC::CondCode CC1, CC2;
4852 changeFPCCToAArch64CC(CC, CC1, CC2);
4853 if (CC2 == AArch64CC::AL) {
4854 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004855 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004856
4857 // Note that we inverted the condition above, so we reverse the order of
4858 // the true and false operands here. This will allow the setcc to be
4859 // matched to a single CSINC instruction.
4860 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4861 } else {
4862 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4863 // totally clean. Some of them require two CSELs to implement. As is in
4864 // this case, we emit the first CSEL and then emit a second using the output
4865 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4866
4867 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004868 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004869 SDValue CS1 =
4870 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4871
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004872 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004873 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4874 }
4875}
4876
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004877SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4878 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004879 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004880 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004881 // Handle f128 first, because it will result in a comparison of some RTLIB
4882 // call result against zero.
4883 if (LHS.getValueType() == MVT::f128) {
4884 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4885
4886 // If softenSetCCOperands returned a scalar, we need to compare the result
4887 // against zero to select between true and false values.
4888 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004889 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004890 CC = ISD::SETNE;
4891 }
4892 }
4893
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004894 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004895 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004896 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4897 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4898 }
4899
4900 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004901 if (LHS.getValueType().isInteger()) {
4902 assert((LHS.getValueType() == RHS.getValueType()) &&
4903 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4904
4905 unsigned Opcode = AArch64ISD::CSEL;
4906
4907 // If both the TVal and the FVal are constants, see if we can swap them in
4908 // order to for a CSINV or CSINC out of them.
4909 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4910 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4911
4912 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4913 std::swap(TVal, FVal);
4914 std::swap(CTVal, CFVal);
4915 CC = ISD::getSetCCInverse(CC, true);
4916 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4917 std::swap(TVal, FVal);
4918 std::swap(CTVal, CFVal);
4919 CC = ISD::getSetCCInverse(CC, true);
4920 } else if (TVal.getOpcode() == ISD::XOR) {
4921 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4922 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004923 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004924 std::swap(TVal, FVal);
4925 std::swap(CTVal, CFVal);
4926 CC = ISD::getSetCCInverse(CC, true);
4927 }
4928 } else if (TVal.getOpcode() == ISD::SUB) {
4929 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4930 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004931 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004932 std::swap(TVal, FVal);
4933 std::swap(CTVal, CFVal);
4934 CC = ISD::getSetCCInverse(CC, true);
4935 }
4936 } else if (CTVal && CFVal) {
4937 const int64_t TrueVal = CTVal->getSExtValue();
4938 const int64_t FalseVal = CFVal->getSExtValue();
4939 bool Swap = false;
4940
4941 // If both TVal and FVal are constants, see if FVal is the
4942 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4943 // instead of a CSEL in that case.
4944 if (TrueVal == ~FalseVal) {
4945 Opcode = AArch64ISD::CSINV;
4946 } else if (TrueVal == -FalseVal) {
4947 Opcode = AArch64ISD::CSNEG;
4948 } else if (TVal.getValueType() == MVT::i32) {
4949 // If our operands are only 32-bit wide, make sure we use 32-bit
4950 // arithmetic for the check whether we can use CSINC. This ensures that
4951 // the addition in the check will wrap around properly in case there is
4952 // an overflow (which would not be the case if we do the check with
4953 // 64-bit arithmetic).
4954 const uint32_t TrueVal32 = CTVal->getZExtValue();
4955 const uint32_t FalseVal32 = CFVal->getZExtValue();
4956
4957 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4958 Opcode = AArch64ISD::CSINC;
4959
4960 if (TrueVal32 > FalseVal32) {
4961 Swap = true;
4962 }
4963 }
4964 // 64-bit check whether we can use CSINC.
4965 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4966 Opcode = AArch64ISD::CSINC;
4967
4968 if (TrueVal > FalseVal) {
4969 Swap = true;
4970 }
4971 }
4972
4973 // Swap TVal and FVal if necessary.
4974 if (Swap) {
4975 std::swap(TVal, FVal);
4976 std::swap(CTVal, CFVal);
4977 CC = ISD::getSetCCInverse(CC, true);
4978 }
4979
4980 if (Opcode != AArch64ISD::CSEL) {
4981 // Drop FVal since we can get its value by simply inverting/negating
4982 // TVal.
4983 FVal = TVal;
4984 }
4985 }
4986
Chad Rosier58f505b2016-08-26 18:05:50 +00004987 // Avoid materializing a constant when possible by reusing a known value in
4988 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004989 // is one, zero or negative one in the case of a CSEL. We can always
4990 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4991 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004992 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4993 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4994 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4995 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4996 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4997 // "a != C ? x : a" to avoid materializing C.
4998 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4999 TVal = LHS;
5000 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5001 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00005002 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5003 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5004 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5005 // avoid materializing C.
5006 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5007 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5008 Opcode = AArch64ISD::CSINV;
5009 TVal = LHS;
5010 FVal = DAG.getConstant(0, dl, FVal.getValueType());
5011 }
Chad Rosier58f505b2016-08-26 18:05:50 +00005012 }
5013
Tim Northover3b0846e2014-05-24 12:50:23 +00005014 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00005015 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005016 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00005017 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5018 }
5019
5020 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00005021 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5022 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005023 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005024 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00005025 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005026
5027 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5028 // clean. Some of them require two CSELs to implement.
5029 AArch64CC::CondCode CC1, CC2;
5030 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00005031
5032 if (DAG.getTarget().Options.UnsafeFPMath) {
5033 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5034 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5035 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5036 if (RHSVal && RHSVal->isZero()) {
5037 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5038 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5039
5040 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00005041 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00005042 TVal = LHS;
5043 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00005044 CFVal && CFVal->isZero() &&
5045 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00005046 FVal = LHS;
5047 }
5048 }
5049
5050 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005051 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00005052 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5053
5054 // If we need a second CSEL, emit it, using the output of the first as the
5055 // RHS. We're effectively OR'ing the two CC's together.
5056 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005057 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00005058 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5059 }
5060
5061 // Otherwise, return the output of the first CSEL.
5062 return CS1;
5063}
5064
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005065SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5066 SelectionDAG &DAG) const {
5067 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5068 SDValue LHS = Op.getOperand(0);
5069 SDValue RHS = Op.getOperand(1);
5070 SDValue TVal = Op.getOperand(2);
5071 SDValue FVal = Op.getOperand(3);
5072 SDLoc DL(Op);
5073 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5074}
5075
5076SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5077 SelectionDAG &DAG) const {
5078 SDValue CCVal = Op->getOperand(0);
5079 SDValue TVal = Op->getOperand(1);
5080 SDValue FVal = Op->getOperand(2);
5081 SDLoc DL(Op);
5082
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005083 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5084 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00005085 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005086 // Only lower legal XALUO ops.
5087 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5088 return SDValue();
5089
5090 AArch64CC::CondCode OFCC;
5091 SDValue Value, Overflow;
5092 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005093 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005094
5095 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5096 CCVal, Overflow);
5097 }
5098
5099 // Lower it the same way as we would lower a SELECT_CC node.
5100 ISD::CondCode CC;
5101 SDValue LHS, RHS;
5102 if (CCVal.getOpcode() == ISD::SETCC) {
5103 LHS = CCVal.getOperand(0);
5104 RHS = CCVal.getOperand(1);
5105 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5106 } else {
5107 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005108 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005109 CC = ISD::SETNE;
5110 }
5111 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5112}
5113
Tim Northover3b0846e2014-05-24 12:50:23 +00005114SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5115 SelectionDAG &DAG) const {
5116 // Jump table entries as PC relative offsets. No additional tweaking
5117 // is necessary here. Just get the address of the jump table.
5118 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005119
5120 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5121 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005122 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005123 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5124 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005125 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005126 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005127}
5128
Tim Northover1c353412018-10-24 20:19:09 +00005129SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5130 SelectionDAG &DAG) const {
5131 // Jump table entries as PC relative offsets. No additional tweaking
5132 // is necessary here. Just get the address of the jump table.
5133 SDLoc DL(Op);
5134 SDValue JT = Op.getOperand(1);
5135 SDValue Entry = Op.getOperand(2);
5136 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5137
5138 SDNode *Dest =
5139 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5140 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5141 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5142 SDValue(Dest, 0));
5143}
5144
Tim Northover3b0846e2014-05-24 12:50:23 +00005145SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5146 SelectionDAG &DAG) const {
5147 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005148
5149 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5150 // Use the GOT for the large code model on iOS.
5151 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005152 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005153 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005154 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005155 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5156 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005157 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005158 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005159 }
5160}
5161
5162SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5163 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005164 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005165 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5166 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005167 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005168 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5169 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005170 }
David Green9dd1d452018-08-22 11:31:39 +00005171 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005172}
5173
5174SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5175 SelectionDAG &DAG) const {
5176 AArch64FunctionInfo *FuncInfo =
5177 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5178
5179 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005180 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5181 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005182 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5183 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005184 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005185}
5186
Martin Storsjo68266fa2017-07-13 17:03:12 +00005187SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5188 SelectionDAG &DAG) const {
5189 AArch64FunctionInfo *FuncInfo =
5190 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5191
5192 SDLoc DL(Op);
5193 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5194 ? FuncInfo->getVarArgsGPRIndex()
5195 : FuncInfo->getVarArgsStackIndex(),
5196 getPointerTy(DAG.getDataLayout()));
5197 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5198 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5199 MachinePointerInfo(SV));
5200}
5201
Tim Northover3b0846e2014-05-24 12:50:23 +00005202SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5203 SelectionDAG &DAG) const {
5204 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5205 // Standard, section B.3.
5206 MachineFunction &MF = DAG.getMachineFunction();
5207 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005208 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005209 SDLoc DL(Op);
5210
5211 SDValue Chain = Op.getOperand(0);
5212 SDValue VAList = Op.getOperand(1);
5213 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5214 SmallVector<SDValue, 4> MemOps;
5215
5216 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005217 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005218 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005219 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005220
5221 // void *__gr_top at offset 8
5222 int GPRSize = FuncInfo->getVarArgsGPRSize();
5223 if (GPRSize > 0) {
5224 SDValue GRTop, GRTopAddr;
5225
Mehdi Amini44ede332015-07-09 02:09:04 +00005226 GRTopAddr =
5227 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005228
Mehdi Amini44ede332015-07-09 02:09:04 +00005229 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5230 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5231 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005232
5233 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005234 MachinePointerInfo(SV, 8),
5235 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005236 }
5237
5238 // void *__vr_top at offset 16
5239 int FPRSize = FuncInfo->getVarArgsFPRSize();
5240 if (FPRSize > 0) {
5241 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005242 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5243 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005244
Mehdi Amini44ede332015-07-09 02:09:04 +00005245 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5246 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5247 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005248
5249 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005250 MachinePointerInfo(SV, 16),
5251 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005252 }
5253
5254 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005255 SDValue GROffsAddr =
5256 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005257 MemOps.push_back(DAG.getStore(
5258 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5259 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005260
5261 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005262 SDValue VROffsAddr =
5263 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005264 MemOps.push_back(DAG.getStore(
5265 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5266 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005267
5268 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5269}
5270
5271SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5272 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005273 MachineFunction &MF = DAG.getMachineFunction();
5274
Matthias Braunf1caa282017-12-15 22:22:58 +00005275 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005276 return LowerWin64_VASTART(Op, DAG);
5277 else if (Subtarget->isTargetDarwin())
5278 return LowerDarwin_VASTART(Op, DAG);
5279 else
5280 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005281}
5282
5283SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5284 SelectionDAG &DAG) const {
5285 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5286 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005287 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005288 unsigned VaListSize =
5289 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005290 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5291 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5292
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005293 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5294 Op.getOperand(2),
5295 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005296 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005297 MachinePointerInfo(SrcSV));
5298}
5299
5300SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5301 assert(Subtarget->isTargetDarwin() &&
5302 "automatic va_arg instruction only works on Darwin");
5303
5304 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5305 EVT VT = Op.getValueType();
5306 SDLoc DL(Op);
5307 SDValue Chain = Op.getOperand(0);
5308 SDValue Addr = Op.getOperand(1);
5309 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005310 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005311
Justin Lebar9c375812016-07-15 18:27:10 +00005312 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005313 Chain = VAList.getValue(1);
5314
5315 if (Align > 8) {
5316 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005317 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5318 DAG.getConstant(Align - 1, DL, PtrVT));
5319 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5320 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005321 }
5322
5323 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005324 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005325
5326 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5327 // up to 64 bits. At the very least, we have to increase the striding of the
5328 // vaargs list to match this, and for FP values we need to introduce
5329 // FP_ROUND nodes as well.
5330 if (VT.isInteger() && !VT.isVector())
5331 ArgSize = 8;
5332 bool NeedFPTrunc = false;
5333 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5334 ArgSize = 8;
5335 NeedFPTrunc = true;
5336 }
5337
5338 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005339 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5340 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005341 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005342 SDValue APStore =
5343 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005344
5345 // Load the actual argument out of the pointer VAList
5346 if (NeedFPTrunc) {
5347 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005348 SDValue WideFP =
5349 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005350 // Round the value down to an f32.
5351 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005352 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005353 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5354 // Merge the rounded value with the chain output of the load.
5355 return DAG.getMergeValues(Ops, DL);
5356 }
5357
Justin Lebar9c375812016-07-15 18:27:10 +00005358 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005359}
5360
5361SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5362 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005363 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5364 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005365
5366 EVT VT = Op.getValueType();
5367 SDLoc DL(Op);
5368 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5369 SDValue FrameAddr =
5370 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5371 while (Depth--)
5372 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005373 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005374 return FrameAddr;
5375}
5376
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005377SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5378 SelectionDAG &DAG) const {
5379 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5380
5381 EVT VT = getPointerTy(DAG.getDataLayout());
5382 SDLoc DL(Op);
5383 int FI = MFI.CreateFixedObject(4, 0, false);
5384 return DAG.getFrameIndex(FI, VT);
5385}
5386
Petr Hosekfcbec022019-02-13 17:28:47 +00005387#define GET_REGISTER_MATCHER
5388#include "AArch64GenAsmMatcher.inc"
5389
Tim Northover3b0846e2014-05-24 12:50:23 +00005390// FIXME? Maybe this could be a TableGen attribute on some registers and
5391// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005392unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5393 SelectionDAG &DAG) const {
Petr Hosekfcbec022019-02-13 17:28:47 +00005394 unsigned Reg = MatchRegisterName(RegName);
5395 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5396 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5397 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5398 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5399 Reg = 0;
5400 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005401 if (Reg)
5402 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005403 report_fatal_error(Twine("Invalid register name \""
5404 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005405}
5406
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005407SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5408 SelectionDAG &DAG) const {
5409 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5410
5411 EVT VT = Op.getValueType();
5412 SDLoc DL(Op);
5413
5414 SDValue FrameAddr =
5415 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5416 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5417
5418 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5419}
5420
Tim Northover3b0846e2014-05-24 12:50:23 +00005421SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5422 SelectionDAG &DAG) const {
5423 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005424 MachineFrameInfo &MFI = MF.getFrameInfo();
5425 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005426
5427 EVT VT = Op.getValueType();
5428 SDLoc DL(Op);
5429 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5430 if (Depth) {
5431 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005432 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005433 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5434 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005435 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005436 }
5437
5438 // Return LR, which contains the return address. Mark it an implicit live-in.
5439 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5440 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5441}
5442
5443/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5444/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5445SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5446 SelectionDAG &DAG) const {
5447 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5448 EVT VT = Op.getValueType();
5449 unsigned VTBits = VT.getSizeInBits();
5450 SDLoc dl(Op);
5451 SDValue ShOpLo = Op.getOperand(0);
5452 SDValue ShOpHi = Op.getOperand(1);
5453 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005454 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5455
5456 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5457
5458 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005459 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005460 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5461
5462 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5463 // is "undef". We wanted 0, so CSEL it directly.
5464 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5465 ISD::SETEQ, dl, DAG);
5466 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5467 HiBitsForLo =
5468 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5469 HiBitsForLo, CCVal, Cmp);
5470
Tim Northover3b0846e2014-05-24 12:50:23 +00005471 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005472 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005473
Tim Northoverf3be9d52015-12-02 00:33:54 +00005474 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5475 SDValue LoForNormalShift =
5476 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005477
Tim Northoverf3be9d52015-12-02 00:33:54 +00005478 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5479 dl, DAG);
5480 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5481 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5482 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5483 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005484
5485 // AArch64 shifts larger than the register width are wrapped rather than
5486 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005487 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5488 SDValue HiForBigShift =
5489 Opc == ISD::SRA
5490 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5491 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5492 : DAG.getConstant(0, dl, VT);
5493 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5494 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005495
5496 SDValue Ops[2] = { Lo, Hi };
5497 return DAG.getMergeValues(Ops, dl);
5498}
5499
5500/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5501/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5502SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005503 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005504 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5505 EVT VT = Op.getValueType();
5506 unsigned VTBits = VT.getSizeInBits();
5507 SDLoc dl(Op);
5508 SDValue ShOpLo = Op.getOperand(0);
5509 SDValue ShOpHi = Op.getOperand(1);
5510 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005511
5512 assert(Op.getOpcode() == ISD::SHL_PARTS);
5513 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005514 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005515 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5516
5517 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5518 // is "undef". We wanted 0, so CSEL it directly.
5519 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5520 ISD::SETEQ, dl, DAG);
5521 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5522 LoBitsForHi =
5523 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5524 LoBitsForHi, CCVal, Cmp);
5525
Tim Northover3b0846e2014-05-24 12:50:23 +00005526 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005527 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005528 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5529 SDValue HiForNormalShift =
5530 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005531
Tim Northoverf3be9d52015-12-02 00:33:54 +00005532 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005533
Tim Northoverf3be9d52015-12-02 00:33:54 +00005534 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5535 dl, DAG);
5536 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5537 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5538 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005539
5540 // AArch64 shifts of larger than register sizes are wrapped rather than
5541 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005542 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5543 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5544 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5545 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005546
5547 SDValue Ops[2] = { Lo, Hi };
5548 return DAG.getMergeValues(Ops, dl);
5549}
5550
5551bool AArch64TargetLowering::isOffsetFoldingLegal(
5552 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005553 // Offsets are folded in the DAG combine rather than here so that we can
5554 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005555 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005556}
5557
Adhemerval Zanella664c1ef2019-03-18 18:40:07 +00005558bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5559 bool OptForSize) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005560 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005561 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5562 // 16-bit case when target has full fp16 support.
5563 // FIXME: We should be able to handle f128 as well with a clever lowering.
5564 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005565 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005566 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005567 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005568 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005569 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005570 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5571 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5572 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005573
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005574 // If we can not materialize in immediate field for fmov, check if the
5575 // value can be encoded as the immediate operand of a logical instruction.
5576 // The immediate value will be created with either MOVZ, MOVN, or ORR.
Adhemerval Zanellaa3cefa52019-03-18 18:45:57 +00005577 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5578 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5579 // however the mov+fmov sequence is always better because of the reduced
5580 // cache pressure. The timings are still the same if you consider
5581 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5582 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5583 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5584 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5585 Insn);
5586 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5587 IsLegal = Insn.size() <= Limit;
5588 }
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005589
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005590 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5591 << " imm value: "; Imm.dump(););
5592 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005593}
5594
5595//===----------------------------------------------------------------------===//
5596// AArch64 Optimization Hooks
5597//===----------------------------------------------------------------------===//
5598
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005599static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5600 SDValue Operand, SelectionDAG &DAG,
5601 int &ExtraSteps) {
5602 EVT VT = Operand.getValueType();
5603 if (ST->hasNEON() &&
5604 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5605 VT == MVT::f32 || VT == MVT::v1f32 ||
5606 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5607 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5608 // For the reciprocal estimates, convergence is quadratic, so the number
5609 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5610 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5611 // the result for float (23 mantissa bits) is 2 and for double (52
5612 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005613 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005614
5615 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5616 }
5617
5618 return SDValue();
5619}
5620
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005621SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5622 SelectionDAG &DAG, int Enabled,
5623 int &ExtraSteps,
5624 bool &UseOneConst,
5625 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005626 if (Enabled == ReciprocalEstimate::Enabled ||
5627 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5628 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5629 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005630 SDLoc DL(Operand);
5631 EVT VT = Operand.getValueType();
5632
5633 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005634 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005635
5636 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5637 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5638 for (int i = ExtraSteps; i > 0; --i) {
5639 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005640 Flags);
5641 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5642 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005643 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005644 if (!Reciprocal) {
5645 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5646 VT);
5647 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5648 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5649
Amara Emersond28f0cd42017-05-01 15:17:51 +00005650 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005651 // Correct the result if the operand is 0.0.
5652 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5653 VT, Eq, Operand, Estimate);
5654 }
5655
5656 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005657 return Estimate;
5658 }
5659
5660 return SDValue();
5661}
5662
5663SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5664 SelectionDAG &DAG, int Enabled,
5665 int &ExtraSteps) const {
5666 if (Enabled == ReciprocalEstimate::Enabled)
5667 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005668 DAG, ExtraSteps)) {
5669 SDLoc DL(Operand);
5670 EVT VT = Operand.getValueType();
5671
5672 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005673 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005674
5675 // Newton reciprocal iteration: E * (2 - X * E)
5676 // AArch64 reciprocal iteration instruction: (2 - M * N)
5677 for (int i = ExtraSteps; i > 0; --i) {
5678 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005679 Estimate, Flags);
5680 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005681 }
5682
5683 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005684 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005685 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005686
5687 return SDValue();
5688}
5689
Tim Northover3b0846e2014-05-24 12:50:23 +00005690//===----------------------------------------------------------------------===//
5691// AArch64 Inline Assembly Support
5692//===----------------------------------------------------------------------===//
5693
5694// Table of Constraints
5695// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005696// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005697//
5698// r - A general register
5699// w - An FP/SIMD register of some size in the range v0-v31
5700// x - An FP/SIMD register of some size in the range v0-v15
5701// I - Constant that can be used with an ADD instruction
5702// J - Constant that can be used with a SUB instruction
5703// K - Constant that can be used with a 32-bit logical instruction
5704// L - Constant that can be used with a 64-bit logical instruction
5705// M - Constant that can be used as a 32-bit MOV immediate
5706// N - Constant that can be used as a 64-bit MOV immediate
5707// Q - A memory reference with base register and no offset
5708// S - A symbolic address
5709// Y - Floating point constant zero
5710// Z - Integer constant zero
5711//
5712// Note that general register operands will be output using their 64-bit x
5713// register name, whatever the size of the variable, unless the asm operand
5714// is prefixed by the %w modifier. Floating-point and SIMD register operands
5715// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5716// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005717const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5718 // At this point, we have to lower this constraint to something else, so we
5719 // lower it to an "r" or "w". However, by doing this we will force the result
5720 // to be in register, while the X constraint is much more permissive.
5721 //
5722 // Although we are correct (we are free to emit anything, without
5723 // constraints), we might break use cases that would expect us to be more
5724 // efficient and emit something else.
5725 if (!Subtarget->hasFPARMv8())
5726 return "r";
5727
5728 if (ConstraintVT.isFloatingPoint())
5729 return "w";
5730
5731 if (ConstraintVT.isVector() &&
5732 (ConstraintVT.getSizeInBits() == 64 ||
5733 ConstraintVT.getSizeInBits() == 128))
5734 return "w";
5735
5736 return "r";
5737}
Tim Northover3b0846e2014-05-24 12:50:23 +00005738
5739/// getConstraintType - Given a constraint letter, return the type of
5740/// constraint it is for this target.
5741AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005742AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005743 if (Constraint.size() == 1) {
5744 switch (Constraint[0]) {
5745 default:
5746 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005747 case 'x':
5748 case 'w':
5749 return C_RegisterClass;
5750 // An address with a single base register. Due to the way we
5751 // currently handle addresses it is the same as 'r'.
5752 case 'Q':
5753 return C_Memory;
Bill Wendling41a28472019-08-03 05:52:47 +00005754 case 'I':
5755 case 'J':
5756 case 'K':
5757 case 'L':
5758 case 'M':
5759 case 'N':
5760 case 'Y':
5761 case 'Z':
5762 return C_Immediate;
5763 case 'z':
Peter Smithc8117582018-05-16 09:33:25 +00005764 case 'S': // A symbolic address
5765 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005766 }
5767 }
5768 return TargetLowering::getConstraintType(Constraint);
5769}
5770
5771/// Examine constraint type and operand type and determine a weight value.
5772/// This object must already have been set up with the operand type
5773/// and the current alternative constraint selected.
5774TargetLowering::ConstraintWeight
5775AArch64TargetLowering::getSingleConstraintMatchWeight(
5776 AsmOperandInfo &info, const char *constraint) const {
5777 ConstraintWeight weight = CW_Invalid;
5778 Value *CallOperandVal = info.CallOperandVal;
5779 // If we don't have a value, we can't do a match,
5780 // but allow it at the lowest weight.
5781 if (!CallOperandVal)
5782 return CW_Default;
5783 Type *type = CallOperandVal->getType();
5784 // Look at the constraint type.
5785 switch (*constraint) {
5786 default:
5787 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5788 break;
5789 case 'x':
5790 case 'w':
5791 if (type->isFloatingPointTy() || type->isVectorTy())
5792 weight = CW_Register;
5793 break;
5794 case 'z':
5795 weight = CW_Constant;
5796 break;
5797 }
5798 return weight;
5799}
5800
5801std::pair<unsigned, const TargetRegisterClass *>
5802AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005803 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005804 if (Constraint.size() == 1) {
5805 switch (Constraint[0]) {
5806 case 'r':
5807 if (VT.getSizeInBits() == 64)
5808 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5809 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5810 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005811 if (!Subtarget->hasFPARMv8())
5812 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005813 if (VT.getSizeInBits() == 16)
5814 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005815 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005816 return std::make_pair(0U, &AArch64::FPR32RegClass);
5817 if (VT.getSizeInBits() == 64)
5818 return std::make_pair(0U, &AArch64::FPR64RegClass);
5819 if (VT.getSizeInBits() == 128)
5820 return std::make_pair(0U, &AArch64::FPR128RegClass);
5821 break;
5822 // The instructions that this constraint is designed for can
5823 // only take 128-bit registers so just use that regclass.
5824 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005825 if (!Subtarget->hasFPARMv8())
5826 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005827 if (VT.getSizeInBits() == 128)
5828 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5829 break;
5830 }
5831 }
5832 if (StringRef("{cc}").equals_lower(Constraint))
5833 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5834
5835 // Use the default implementation in TargetLowering to convert the register
5836 // constraint into a member of a register class.
5837 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005838 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005839
5840 // Not found as a standard register?
5841 if (!Res.second) {
5842 unsigned Size = Constraint.size();
5843 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5844 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005845 int RegNo;
5846 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5847 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005848 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005849 // By default we'll emit v0-v31 for this unless there's a modifier where
5850 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005851 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5852 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5853 Res.second = &AArch64::FPR64RegClass;
5854 } else {
5855 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5856 Res.second = &AArch64::FPR128RegClass;
5857 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005858 }
5859 }
5860 }
5861
Eli Friedman071203b2018-08-24 19:12:13 +00005862 if (Res.second && !Subtarget->hasFPARMv8() &&
5863 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5864 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5865 return std::make_pair(0U, nullptr);
5866
Tim Northover3b0846e2014-05-24 12:50:23 +00005867 return Res;
5868}
5869
5870/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5871/// vector. If it is invalid, don't add anything to Ops.
5872void AArch64TargetLowering::LowerAsmOperandForConstraint(
5873 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5874 SelectionDAG &DAG) const {
5875 SDValue Result;
5876
5877 // Currently only support length 1 constraints.
5878 if (Constraint.length() != 1)
5879 return;
5880
5881 char ConstraintLetter = Constraint[0];
5882 switch (ConstraintLetter) {
5883 default:
5884 break;
5885
5886 // This set of constraints deal with valid constants for various instructions.
5887 // Validate and return a target constant for them if we can.
5888 case 'z': {
5889 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005890 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005891 return;
5892
5893 if (Op.getValueType() == MVT::i64)
5894 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5895 else
5896 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5897 break;
5898 }
Peter Smithc8117582018-05-16 09:33:25 +00005899 case 'S': {
5900 // An absolute symbolic address or label reference.
5901 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5902 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5903 GA->getValueType(0));
5904 } else if (const BlockAddressSDNode *BA =
5905 dyn_cast<BlockAddressSDNode>(Op)) {
5906 Result =
5907 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5908 } else if (const ExternalSymbolSDNode *ES =
5909 dyn_cast<ExternalSymbolSDNode>(Op)) {
5910 Result =
5911 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5912 } else
5913 return;
5914 break;
5915 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005916
5917 case 'I':
5918 case 'J':
5919 case 'K':
5920 case 'L':
5921 case 'M':
5922 case 'N':
5923 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5924 if (!C)
5925 return;
5926
5927 // Grab the value and do some validation.
5928 uint64_t CVal = C->getZExtValue();
5929 switch (ConstraintLetter) {
5930 // The I constraint applies only to simple ADD or SUB immediate operands:
5931 // i.e. 0 to 4095 with optional shift by 12
5932 // The J constraint applies only to ADD or SUB immediates that would be
5933 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5934 // instruction [or vice versa], in other words -1 to -4095 with optional
5935 // left shift by 12.
5936 case 'I':
5937 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5938 break;
5939 return;
5940 case 'J': {
5941 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005942 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5943 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005944 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005945 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005946 return;
5947 }
5948 // The K and L constraints apply *only* to logical immediates, including
5949 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5950 // been removed and MOV should be used). So these constraints have to
5951 // distinguish between bit patterns that are valid 32-bit or 64-bit
5952 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5953 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5954 // versa.
5955 case 'K':
5956 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5957 break;
5958 return;
5959 case 'L':
5960 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5961 break;
5962 return;
5963 // The M and N constraints are a superset of K and L respectively, for use
5964 // with the MOV (immediate) alias. As well as the logical immediates they
5965 // also match 32 or 64-bit immediates that can be loaded either using a
5966 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5967 // (M) or 64-bit 0x1234000000000000 (N) etc.
5968 // As a note some of this code is liberally stolen from the asm parser.
5969 case 'M': {
5970 if (!isUInt<32>(CVal))
5971 return;
5972 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5973 break;
5974 if ((CVal & 0xFFFF) == CVal)
5975 break;
5976 if ((CVal & 0xFFFF0000ULL) == CVal)
5977 break;
5978 uint64_t NCVal = ~(uint32_t)CVal;
5979 if ((NCVal & 0xFFFFULL) == NCVal)
5980 break;
5981 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5982 break;
5983 return;
5984 }
5985 case 'N': {
5986 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5987 break;
5988 if ((CVal & 0xFFFFULL) == CVal)
5989 break;
5990 if ((CVal & 0xFFFF0000ULL) == CVal)
5991 break;
5992 if ((CVal & 0xFFFF00000000ULL) == CVal)
5993 break;
5994 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5995 break;
5996 uint64_t NCVal = ~CVal;
5997 if ((NCVal & 0xFFFFULL) == NCVal)
5998 break;
5999 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6000 break;
6001 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6002 break;
6003 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6004 break;
6005 return;
6006 }
6007 default:
6008 return;
6009 }
6010
6011 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006012 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006013 break;
6014 }
6015
6016 if (Result.getNode()) {
6017 Ops.push_back(Result);
6018 return;
6019 }
6020
6021 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6022}
6023
6024//===----------------------------------------------------------------------===//
6025// AArch64 Advanced SIMD Support
6026//===----------------------------------------------------------------------===//
6027
6028/// WidenVector - Given a value in the V64 register class, produce the
6029/// equivalent value in the V128 register class.
6030static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6031 EVT VT = V64Reg.getValueType();
6032 unsigned NarrowSize = VT.getVectorNumElements();
6033 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6034 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6035 SDLoc DL(V64Reg);
6036
6037 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006038 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006039}
6040
6041/// getExtFactor - Determine the adjustment factor for the position when
6042/// generating an "extract from vector registers" instruction.
6043static unsigned getExtFactor(SDValue &V) {
6044 EVT EltType = V.getValueType().getVectorElementType();
6045 return EltType.getSizeInBits() / 8;
6046}
6047
6048/// NarrowVector - Given a value in the V128 register class, produce the
6049/// equivalent value in the V64 register class.
6050static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6051 EVT VT = V128Reg.getValueType();
6052 unsigned WideSize = VT.getVectorNumElements();
6053 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6054 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6055 SDLoc DL(V128Reg);
6056
6057 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6058}
6059
6060// Gather data to see if the operation can be modelled as a
6061// shuffle in combination with VEXTs.
6062SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6063 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00006064 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006065 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006066 SDLoc dl(Op);
6067 EVT VT = Op.getValueType();
6068 unsigned NumElts = VT.getVectorNumElements();
6069
Tim Northover7324e842014-07-24 15:39:55 +00006070 struct ShuffleSourceInfo {
6071 SDValue Vec;
6072 unsigned MinElt;
6073 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006074
Tim Northover7324e842014-07-24 15:39:55 +00006075 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6076 // be compatible with the shuffle we intend to construct. As a result
6077 // ShuffleVec will be some sliding window into the original Vec.
6078 SDValue ShuffleVec;
6079
6080 // Code should guarantee that element i in Vec starts at element "WindowBase
6081 // + i * WindowScale in ShuffleVec".
6082 int WindowBase;
6083 int WindowScale;
6084
Tim Northover7324e842014-07-24 15:39:55 +00006085 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00006086 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6087 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6088
6089 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00006090 };
6091
6092 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6093 // node.
6094 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00006095 for (unsigned i = 0; i < NumElts; ++i) {
6096 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006097 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006098 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00006099 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6100 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006101 LLVM_DEBUG(
6102 dbgs() << "Reshuffle failed: "
6103 "a shuffle can only come from building a vector from "
6104 "various elements of other vectors, provided their "
6105 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006106 return SDValue();
6107 }
6108
Tim Northover7324e842014-07-24 15:39:55 +00006109 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00006110 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00006111 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00006112 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00006113 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00006114
Tim Northover7324e842014-07-24 15:39:55 +00006115 // Update the minimum and maximum lane number seen.
6116 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6117 Source->MinElt = std::min(Source->MinElt, EltNo);
6118 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00006119 }
6120
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006121 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006122 LLVM_DEBUG(
6123 dbgs() << "Reshuffle failed: currently only do something sane when at "
6124 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006125 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006126 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006127
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006128 // Find out the smallest element size among result and two sources, and use
6129 // it as element size to build the shuffle_vector.
6130 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00006131 for (auto &Source : Sources) {
6132 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006133 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6134 SmallestEltTy = SrcEltTy;
6135 }
6136 }
6137 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006138 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006139 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6140 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00006141
Tim Northover7324e842014-07-24 15:39:55 +00006142 // If the source vector is too wide or too narrow, we may nevertheless be able
6143 // to construct a compatible shuffle either by concatenating it with UNDEF or
6144 // extracting a suitable range of elements.
6145 for (auto &Src : Sources) {
6146 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00006147
Tim Northover7324e842014-07-24 15:39:55 +00006148 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00006149 continue;
Tim Northover7324e842014-07-24 15:39:55 +00006150
6151 // This stage of the search produces a source with the same element type as
6152 // the original, but with a total width matching the BUILD_VECTOR output.
6153 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00006154 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6155 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00006156
6157 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6158 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006159 // We can pad out the smaller vector for free, so if it's part of a
6160 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00006161 Src.ShuffleVec =
6162 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6163 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00006164 continue;
6165 }
6166
Tim Northover7324e842014-07-24 15:39:55 +00006167 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006168
James Molloyf497d552014-10-17 17:06:31 +00006169 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006170 LLVM_DEBUG(
6171 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006172 return SDValue();
6173 }
6174
James Molloyf497d552014-10-17 17:06:31 +00006175 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006176 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00006177 Src.ShuffleVec =
6178 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006179 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00006180 Src.WindowBase = -NumSrcElts;
6181 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006182 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006183 Src.ShuffleVec =
6184 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006185 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006186 } else {
6187 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006188 SDValue VEXTSrc1 =
6189 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006190 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006191 SDValue VEXTSrc2 =
6192 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006193 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006194 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6195
6196 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006197 VEXTSrc2,
6198 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006199 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006200 }
6201 }
6202
Tim Northover7324e842014-07-24 15:39:55 +00006203 // Another possible incompatibility occurs from the vector element types. We
6204 // can fix this by bitcasting the source vectors to the same type we intend
6205 // for the shuffle.
6206 for (auto &Src : Sources) {
6207 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6208 if (SrcEltTy == SmallestEltTy)
6209 continue;
6210 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6211 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6212 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6213 Src.WindowBase *= Src.WindowScale;
6214 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006215
Tim Northover7324e842014-07-24 15:39:55 +00006216 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006217 LLVM_DEBUG(for (auto Src
6218 : Sources)
6219 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006220
6221 // The stars all align, our next step is to produce the mask for the shuffle.
6222 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006223 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006224 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006225 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006226 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006227 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006228
David Majnemer0d955d02016-08-11 22:21:41 +00006229 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006230 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6231
6232 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6233 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6234 // segment.
6235 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006236 int BitsDefined =
6237 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006238 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6239
6240 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6241 // starting at the appropriate offset.
6242 int *LaneMask = &Mask[i * ResMultiplier];
6243
6244 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6245 ExtractBase += NumElts * (Src - Sources.begin());
6246 for (int j = 0; j < LanesDefined; ++j)
6247 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006248 }
6249
6250 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006251 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006252 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006253 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006254 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006255
Tim Northover7324e842014-07-24 15:39:55 +00006256 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6257 for (unsigned i = 0; i < Sources.size(); ++i)
6258 ShuffleOps[i] = Sources[i].ShuffleVec;
6259
6260 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006261 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006262 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6263
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006264 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6265 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006266
6267 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006268}
6269
6270// check if an EXT instruction can handle the shuffle mask when the
6271// vector sources of the shuffle are the same.
6272static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6273 unsigned NumElts = VT.getVectorNumElements();
6274
6275 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6276 if (M[0] < 0)
6277 return false;
6278
6279 Imm = M[0];
6280
6281 // If this is a VEXT shuffle, the immediate value is the index of the first
6282 // element. The other shuffle indices must be the successive elements after
6283 // the first one.
6284 unsigned ExpectedElt = Imm;
6285 for (unsigned i = 1; i < NumElts; ++i) {
6286 // Increment the expected index. If it wraps around, just follow it
6287 // back to index zero and keep going.
6288 ++ExpectedElt;
6289 if (ExpectedElt == NumElts)
6290 ExpectedElt = 0;
6291
6292 if (M[i] < 0)
6293 continue; // ignore UNDEF indices
6294 if (ExpectedElt != static_cast<unsigned>(M[i]))
6295 return false;
6296 }
6297
6298 return true;
6299}
6300
6301// check if an EXT instruction can handle the shuffle mask when the
6302// vector sources of the shuffle are different.
6303static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6304 unsigned &Imm) {
6305 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006306 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006307
6308 // Benefit form APInt to handle overflow when calculating expected element.
6309 unsigned NumElts = VT.getVectorNumElements();
6310 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6311 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6312 // The following shuffle indices must be the successive elements after the
6313 // first real element.
6314 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6315 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6316 if (FirstWrongElt != M.end())
6317 return false;
6318
6319 // The index of an EXT is the first element if it is not UNDEF.
6320 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006321 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006322 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6323 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6324 // ExpectedElt is the last mask index plus 1.
6325 Imm = ExpectedElt.getZExtValue();
6326
6327 // There are two difference cases requiring to reverse input vectors.
6328 // For example, for vector <4 x i32> we have the following cases,
6329 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6330 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6331 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6332 // to reverse two input vectors.
6333 if (Imm < NumElts)
6334 ReverseEXT = true;
6335 else
6336 Imm -= NumElts;
6337
6338 return true;
6339}
6340
6341/// isREVMask - Check if a vector shuffle corresponds to a REV
6342/// instruction with the specified blocksize. (The order of the elements
6343/// within each block of the vector is reversed.)
6344static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6345 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6346 "Only possible block sizes for REV are: 16, 32, 64");
6347
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006348 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006349 if (EltSz == 64)
6350 return false;
6351
6352 unsigned NumElts = VT.getVectorNumElements();
6353 unsigned BlockElts = M[0] + 1;
6354 // If the first shuffle index is UNDEF, be optimistic.
6355 if (M[0] < 0)
6356 BlockElts = BlockSize / EltSz;
6357
6358 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6359 return false;
6360
6361 for (unsigned i = 0; i < NumElts; ++i) {
6362 if (M[i] < 0)
6363 continue; // ignore UNDEF indices
6364 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6365 return false;
6366 }
6367
6368 return true;
6369}
6370
6371static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6372 unsigned NumElts = VT.getVectorNumElements();
Florian Hahne3ea97b2019-08-05 11:12:23 +00006373 if (NumElts % 2 != 0)
6374 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006375 WhichResult = (M[0] == 0 ? 0 : 1);
6376 unsigned Idx = WhichResult * NumElts / 2;
6377 for (unsigned i = 0; i != NumElts; i += 2) {
6378 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6379 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6380 return false;
6381 Idx += 1;
6382 }
6383
6384 return true;
6385}
6386
6387static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6388 unsigned NumElts = VT.getVectorNumElements();
6389 WhichResult = (M[0] == 0 ? 0 : 1);
6390 for (unsigned i = 0; i != NumElts; ++i) {
6391 if (M[i] < 0)
6392 continue; // ignore UNDEF indices
6393 if ((unsigned)M[i] != 2 * i + WhichResult)
6394 return false;
6395 }
6396
6397 return true;
6398}
6399
6400static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6401 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006402 if (NumElts % 2 != 0)
6403 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006404 WhichResult = (M[0] == 0 ? 0 : 1);
6405 for (unsigned i = 0; i < NumElts; i += 2) {
6406 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6407 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6408 return false;
6409 }
6410 return true;
6411}
6412
6413/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6414/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6415/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6416static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6417 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006418 if (NumElts % 2 != 0)
6419 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006420 WhichResult = (M[0] == 0 ? 0 : 1);
6421 unsigned Idx = WhichResult * NumElts / 2;
6422 for (unsigned i = 0; i != NumElts; i += 2) {
6423 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6424 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6425 return false;
6426 Idx += 1;
6427 }
6428
6429 return true;
6430}
6431
6432/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6433/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6434/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6435static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6436 unsigned Half = VT.getVectorNumElements() / 2;
6437 WhichResult = (M[0] == 0 ? 0 : 1);
6438 for (unsigned j = 0; j != 2; ++j) {
6439 unsigned Idx = WhichResult;
6440 for (unsigned i = 0; i != Half; ++i) {
6441 int MIdx = M[i + j * Half];
6442 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6443 return false;
6444 Idx += 2;
6445 }
6446 }
6447
6448 return true;
6449}
6450
6451/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6452/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6453/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6454static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6455 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006456 if (NumElts % 2 != 0)
6457 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006458 WhichResult = (M[0] == 0 ? 0 : 1);
6459 for (unsigned i = 0; i < NumElts; i += 2) {
6460 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6461 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6462 return false;
6463 }
6464 return true;
6465}
6466
6467static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6468 bool &DstIsLeft, int &Anomaly) {
6469 if (M.size() != static_cast<size_t>(NumInputElements))
6470 return false;
6471
6472 int NumLHSMatch = 0, NumRHSMatch = 0;
6473 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6474
6475 for (int i = 0; i < NumInputElements; ++i) {
6476 if (M[i] == -1) {
6477 ++NumLHSMatch;
6478 ++NumRHSMatch;
6479 continue;
6480 }
6481
6482 if (M[i] == i)
6483 ++NumLHSMatch;
6484 else
6485 LastLHSMismatch = i;
6486
6487 if (M[i] == i + NumInputElements)
6488 ++NumRHSMatch;
6489 else
6490 LastRHSMismatch = i;
6491 }
6492
6493 if (NumLHSMatch == NumInputElements - 1) {
6494 DstIsLeft = true;
6495 Anomaly = LastLHSMismatch;
6496 return true;
6497 } else if (NumRHSMatch == NumInputElements - 1) {
6498 DstIsLeft = false;
6499 Anomaly = LastRHSMismatch;
6500 return true;
6501 }
6502
6503 return false;
6504}
6505
6506static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6507 if (VT.getSizeInBits() != 128)
6508 return false;
6509
6510 unsigned NumElts = VT.getVectorNumElements();
6511
6512 for (int I = 0, E = NumElts / 2; I != E; I++) {
6513 if (Mask[I] != I)
6514 return false;
6515 }
6516
6517 int Offset = NumElts / 2;
6518 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6519 if (Mask[I] != I + SplitLHS * Offset)
6520 return false;
6521 }
6522
6523 return true;
6524}
6525
6526static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6527 SDLoc DL(Op);
6528 EVT VT = Op.getValueType();
6529 SDValue V0 = Op.getOperand(0);
6530 SDValue V1 = Op.getOperand(1);
6531 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6532
6533 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6534 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6535 return SDValue();
6536
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006537 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006538
6539 if (!isConcatMask(Mask, VT, SplitV0))
6540 return SDValue();
6541
6542 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6543 VT.getVectorNumElements() / 2);
6544 if (SplitV0) {
6545 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006546 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006547 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006548 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006549 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006550 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006551 }
6552 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6553}
6554
6555/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6556/// the specified operations to build the shuffle.
6557static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6558 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006559 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006560 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6561 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6562 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6563
6564 enum {
6565 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6566 OP_VREV,
6567 OP_VDUP0,
6568 OP_VDUP1,
6569 OP_VDUP2,
6570 OP_VDUP3,
6571 OP_VEXT1,
6572 OP_VEXT2,
6573 OP_VEXT3,
6574 OP_VUZPL, // VUZP, left result
6575 OP_VUZPR, // VUZP, right result
6576 OP_VZIPL, // VZIP, left result
6577 OP_VZIPR, // VZIP, right result
6578 OP_VTRNL, // VTRN, left result
6579 OP_VTRNR // VTRN, right result
6580 };
6581
6582 if (OpNum == OP_COPY) {
6583 if (LHSID == (1 * 9 + 2) * 9 + 3)
6584 return LHS;
6585 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6586 return RHS;
6587 }
6588
6589 SDValue OpLHS, OpRHS;
6590 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6591 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6592 EVT VT = OpLHS.getValueType();
6593
6594 switch (OpNum) {
6595 default:
6596 llvm_unreachable("Unknown shuffle opcode!");
6597 case OP_VREV:
6598 // VREV divides the vector in half and swaps within the half.
6599 if (VT.getVectorElementType() == MVT::i32 ||
6600 VT.getVectorElementType() == MVT::f32)
6601 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6602 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006603 if (VT.getVectorElementType() == MVT::i16 ||
6604 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006605 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6606 // vrev <4 x i8> -> REV16
6607 assert(VT.getVectorElementType() == MVT::i8);
6608 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6609 case OP_VDUP0:
6610 case OP_VDUP1:
6611 case OP_VDUP2:
6612 case OP_VDUP3: {
6613 EVT EltTy = VT.getVectorElementType();
6614 unsigned Opcode;
6615 if (EltTy == MVT::i8)
6616 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006617 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006618 Opcode = AArch64ISD::DUPLANE16;
6619 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6620 Opcode = AArch64ISD::DUPLANE32;
6621 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6622 Opcode = AArch64ISD::DUPLANE64;
6623 else
6624 llvm_unreachable("Invalid vector element type?");
6625
6626 if (VT.getSizeInBits() == 64)
6627 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006628 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006629 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6630 }
6631 case OP_VEXT1:
6632 case OP_VEXT2:
6633 case OP_VEXT3: {
6634 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6635 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006636 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006637 }
6638 case OP_VUZPL:
6639 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6640 OpRHS);
6641 case OP_VUZPR:
6642 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6643 OpRHS);
6644 case OP_VZIPL:
6645 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6646 OpRHS);
6647 case OP_VZIPR:
6648 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6649 OpRHS);
6650 case OP_VTRNL:
6651 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6652 OpRHS);
6653 case OP_VTRNR:
6654 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6655 OpRHS);
6656 }
6657}
6658
6659static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6660 SelectionDAG &DAG) {
6661 // Check to see if we can use the TBL instruction.
6662 SDValue V1 = Op.getOperand(0);
6663 SDValue V2 = Op.getOperand(1);
6664 SDLoc DL(Op);
6665
6666 EVT EltVT = Op.getValueType().getVectorElementType();
6667 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6668
6669 SmallVector<SDValue, 8> TBLMask;
6670 for (int Val : ShuffleMask) {
6671 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6672 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006673 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006674 }
6675 }
6676
6677 MVT IndexVT = MVT::v8i8;
6678 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006679 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006680 IndexVT = MVT::v16i8;
6681 IndexLen = 16;
6682 }
6683
6684 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6685 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6686
6687 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006688 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006689 if (IndexLen == 8)
6690 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6691 Shuffle = DAG.getNode(
6692 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006693 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006694 DAG.getBuildVector(IndexVT, DL,
6695 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006696 } else {
6697 if (IndexLen == 8) {
6698 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6699 Shuffle = DAG.getNode(
6700 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006701 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006702 DAG.getBuildVector(IndexVT, DL,
6703 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006704 } else {
6705 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6706 // cannot currently represent the register constraints on the input
6707 // table registers.
6708 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006709 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6710 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006711 Shuffle = DAG.getNode(
6712 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006713 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6714 V2Cst, DAG.getBuildVector(IndexVT, DL,
6715 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006716 }
6717 }
6718 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6719}
6720
6721static unsigned getDUPLANEOp(EVT EltType) {
6722 if (EltType == MVT::i8)
6723 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006724 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006725 return AArch64ISD::DUPLANE16;
6726 if (EltType == MVT::i32 || EltType == MVT::f32)
6727 return AArch64ISD::DUPLANE32;
6728 if (EltType == MVT::i64 || EltType == MVT::f64)
6729 return AArch64ISD::DUPLANE64;
6730
6731 llvm_unreachable("Invalid vector element type?");
6732}
6733
6734SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6735 SelectionDAG &DAG) const {
6736 SDLoc dl(Op);
6737 EVT VT = Op.getValueType();
6738
6739 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6740
6741 // Convert shuffles that are directly supported on NEON to target-specific
6742 // DAG nodes, instead of keeping them as shuffles and matching them again
6743 // during code selection. This is more efficient and avoids the possibility
6744 // of inconsistencies between legalization and selection.
6745 ArrayRef<int> ShuffleMask = SVN->getMask();
6746
6747 SDValue V1 = Op.getOperand(0);
6748 SDValue V2 = Op.getOperand(1);
6749
Craig Topperbc56e3b2016-06-30 04:38:51 +00006750 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006751 int Lane = SVN->getSplatIndex();
6752 // If this is undef splat, generate it via "just" vdup, if possible.
6753 if (Lane == -1)
6754 Lane = 0;
6755
6756 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6757 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6758 V1.getOperand(0));
6759 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6760 // constant. If so, we can just reference the lane's definition directly.
6761 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6762 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6763 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6764
6765 // Otherwise, duplicate from the lane of the input vector.
6766 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6767
6768 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6769 // to make a vector of the same size as this SHUFFLE. We can ignore the
6770 // extract entirely, and canonicalise the concat using WidenVector.
6771 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6772 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6773 V1 = V1.getOperand(0);
6774 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6775 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6776 Lane -= Idx * VT.getVectorNumElements() / 2;
6777 V1 = WidenVector(V1.getOperand(Idx), DAG);
6778 } else if (VT.getSizeInBits() == 64)
6779 V1 = WidenVector(V1, DAG);
6780
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006781 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006782 }
6783
6784 if (isREVMask(ShuffleMask, VT, 64))
6785 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6786 if (isREVMask(ShuffleMask, VT, 32))
6787 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6788 if (isREVMask(ShuffleMask, VT, 16))
6789 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6790
6791 bool ReverseEXT = false;
6792 unsigned Imm;
6793 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6794 if (ReverseEXT)
6795 std::swap(V1, V2);
6796 Imm *= getExtFactor(V1);
6797 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006798 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006799 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006800 Imm *= getExtFactor(V1);
6801 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006802 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006803 }
6804
6805 unsigned WhichResult;
6806 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6807 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6808 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6809 }
6810 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6811 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6812 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6813 }
6814 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6815 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6816 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6817 }
6818
6819 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6820 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6821 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6822 }
6823 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6824 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6825 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6826 }
6827 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6828 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6829 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6830 }
6831
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006832 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006833 return Concat;
6834
6835 bool DstIsLeft;
6836 int Anomaly;
6837 int NumInputElements = V1.getValueType().getVectorNumElements();
6838 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6839 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006840 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006841
6842 SDValue SrcVec = V1;
6843 int SrcLane = ShuffleMask[Anomaly];
6844 if (SrcLane >= NumInputElements) {
6845 SrcVec = V2;
6846 SrcLane -= VT.getVectorNumElements();
6847 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006848 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006849
6850 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006851
6852 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006853 ScalarVT = MVT::i32;
6854
6855 return DAG.getNode(
6856 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6857 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6858 DstLaneV);
6859 }
6860
6861 // If the shuffle is not directly supported and it has 4 elements, use
6862 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6863 unsigned NumElts = VT.getVectorNumElements();
6864 if (NumElts == 4) {
6865 unsigned PFIndexes[4];
6866 for (unsigned i = 0; i != 4; ++i) {
6867 if (ShuffleMask[i] < 0)
6868 PFIndexes[i] = 8;
6869 else
6870 PFIndexes[i] = ShuffleMask[i];
6871 }
6872
6873 // Compute the index in the perfect shuffle table.
6874 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6875 PFIndexes[2] * 9 + PFIndexes[3];
6876 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6877 unsigned Cost = (PFEntry >> 30);
6878
6879 if (Cost <= 4)
6880 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6881 }
6882
6883 return GenerateTBL(Op, ShuffleMask, DAG);
6884}
6885
6886static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6887 APInt &UndefBits) {
6888 EVT VT = BVN->getValueType(0);
6889 APInt SplatBits, SplatUndef;
6890 unsigned SplatBitSize;
6891 bool HasAnyUndefs;
6892 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6893 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6894
6895 for (unsigned i = 0; i < NumSplats; ++i) {
6896 CnstBits <<= SplatBitSize;
6897 UndefBits <<= SplatBitSize;
6898 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6899 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6900 }
6901
6902 return true;
6903 }
6904
6905 return false;
6906}
6907
Evandro Menezes72f39832018-02-20 20:31:45 +00006908// Try 64-bit splatted SIMD immediate.
6909static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6910 const APInt &Bits) {
6911 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6912 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6913 EVT VT = Op.getValueType();
6914 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6915
6916 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6917 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6918
6919 SDLoc dl(Op);
6920 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6921 DAG.getConstant(Value, dl, MVT::i32));
6922 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6923 }
6924 }
6925
6926 return SDValue();
6927}
6928
6929// Try 32-bit splatted SIMD immediate.
6930static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6931 const APInt &Bits,
6932 const SDValue *LHS = nullptr) {
6933 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6934 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6935 EVT VT = Op.getValueType();
6936 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6937 bool isAdvSIMDModImm = false;
6938 uint64_t Shift;
6939
6940 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6941 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6942 Shift = 0;
6943 }
6944 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6945 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6946 Shift = 8;
6947 }
6948 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6949 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6950 Shift = 16;
6951 }
6952 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6953 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6954 Shift = 24;
6955 }
6956
6957 if (isAdvSIMDModImm) {
6958 SDLoc dl(Op);
6959 SDValue Mov;
6960
6961 if (LHS)
6962 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6963 DAG.getConstant(Value, dl, MVT::i32),
6964 DAG.getConstant(Shift, dl, MVT::i32));
6965 else
6966 Mov = DAG.getNode(NewOp, dl, MovTy,
6967 DAG.getConstant(Value, dl, MVT::i32),
6968 DAG.getConstant(Shift, dl, MVT::i32));
6969
6970 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6971 }
6972 }
6973
6974 return SDValue();
6975}
6976
6977// Try 16-bit splatted SIMD immediate.
6978static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6979 const APInt &Bits,
6980 const SDValue *LHS = nullptr) {
6981 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6982 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6983 EVT VT = Op.getValueType();
6984 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6985 bool isAdvSIMDModImm = false;
6986 uint64_t Shift;
6987
6988 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6989 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6990 Shift = 0;
6991 }
6992 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6993 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6994 Shift = 8;
6995 }
6996
6997 if (isAdvSIMDModImm) {
6998 SDLoc dl(Op);
6999 SDValue Mov;
7000
7001 if (LHS)
7002 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00007003 DAG.getConstant(Value, dl, MVT::i32),
7004 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00007005 else
7006 Mov = DAG.getNode(NewOp, dl, MovTy,
7007 DAG.getConstant(Value, dl, MVT::i32),
7008 DAG.getConstant(Shift, dl, MVT::i32));
7009
7010 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7011 }
7012 }
7013
7014 return SDValue();
7015}
7016
7017// Try 32-bit splatted SIMD immediate with shifted ones.
7018static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7019 SelectionDAG &DAG, const APInt &Bits) {
7020 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7021 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7022 EVT VT = Op.getValueType();
7023 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7024 bool isAdvSIMDModImm = false;
7025 uint64_t Shift;
7026
7027 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7028 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7029 Shift = 264;
7030 }
7031 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7032 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7033 Shift = 272;
7034 }
7035
7036 if (isAdvSIMDModImm) {
7037 SDLoc dl(Op);
7038 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7039 DAG.getConstant(Value, dl, MVT::i32),
7040 DAG.getConstant(Shift, dl, MVT::i32));
7041 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7042 }
7043 }
7044
7045 return SDValue();
7046}
7047
7048// Try 8-bit splatted SIMD immediate.
7049static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7050 const APInt &Bits) {
7051 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7052 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7053 EVT VT = Op.getValueType();
7054 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7055
7056 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7057 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7058
7059 SDLoc dl(Op);
7060 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7061 DAG.getConstant(Value, dl, MVT::i32));
7062 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7063 }
7064 }
7065
7066 return SDValue();
7067}
7068
7069// Try FP splatted SIMD immediate.
7070static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7071 const APInt &Bits) {
7072 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7073 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7074 EVT VT = Op.getValueType();
7075 bool isWide = (VT.getSizeInBits() == 128);
7076 MVT MovTy;
7077 bool isAdvSIMDModImm = false;
7078
7079 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7080 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7081 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7082 }
7083 else if (isWide &&
7084 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7085 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7086 MovTy = MVT::v2f64;
7087 }
7088
7089 if (isAdvSIMDModImm) {
7090 SDLoc dl(Op);
7091 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7092 DAG.getConstant(Value, dl, MVT::i32));
7093 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7094 }
7095 }
7096
7097 return SDValue();
7098}
7099
Tim Northover3b0846e2014-05-24 12:50:23 +00007100// Specialized code to quickly find if PotentialBVec is a BuildVector that
7101// consists of only the same constant int value, returned in reference arg
7102// ConstVal
7103static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7104 uint64_t &ConstVal) {
7105 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7106 if (!Bvec)
7107 return false;
7108 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7109 if (!FirstElt)
7110 return false;
7111 EVT VT = Bvec->getValueType(0);
7112 unsigned NumElts = VT.getVectorNumElements();
7113 for (unsigned i = 1; i < NumElts; ++i)
7114 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7115 return false;
7116 ConstVal = FirstElt->getZExtValue();
7117 return true;
7118}
7119
7120static unsigned getIntrinsicID(const SDNode *N) {
7121 unsigned Opcode = N->getOpcode();
7122 switch (Opcode) {
7123 default:
7124 return Intrinsic::not_intrinsic;
7125 case ISD::INTRINSIC_WO_CHAIN: {
7126 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7127 if (IID < Intrinsic::num_intrinsics)
7128 return IID;
7129 return Intrinsic::not_intrinsic;
7130 }
7131 }
7132}
7133
7134// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7135// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7136// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7137// Also, logical shift right -> sri, with the same structure.
7138static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7139 EVT VT = N->getValueType(0);
7140
7141 if (!VT.isVector())
7142 return SDValue();
7143
7144 SDLoc DL(N);
7145
7146 // Is the first op an AND?
7147 const SDValue And = N->getOperand(0);
7148 if (And.getOpcode() != ISD::AND)
7149 return SDValue();
7150
7151 // Is the second op an shl or lshr?
7152 SDValue Shift = N->getOperand(1);
7153 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7154 // or AArch64ISD::VLSHR vector, #shift
7155 unsigned ShiftOpc = Shift.getOpcode();
7156 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7157 return SDValue();
7158 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7159
7160 // Is the shift amount constant?
7161 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7162 if (!C2node)
7163 return SDValue();
7164
7165 // Is the and mask vector all constant?
7166 uint64_t C1;
7167 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7168 return SDValue();
7169
7170 // Is C1 == ~C2, taking into account how much one can shift elements of a
7171 // particular size?
7172 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007173 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007174 if (C2 > ElemSizeInBits)
7175 return SDValue();
7176 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7177 if ((C1 & ElemMask) != (~C2 & ElemMask))
7178 return SDValue();
7179
7180 SDValue X = And.getOperand(0);
7181 SDValue Y = Shift.getOperand(0);
7182
7183 unsigned Intrin =
7184 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7185 SDValue ResultSLI =
7186 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007187 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7188 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007189
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007190 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7191 LLVM_DEBUG(N->dump(&DAG));
7192 LLVM_DEBUG(dbgs() << "into: \n");
7193 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007194
7195 ++NumShiftInserts;
7196 return ResultSLI;
7197}
7198
7199SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7200 SelectionDAG &DAG) const {
7201 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7202 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007203 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007204 return Res;
7205 }
7206
Tim Northover3b0846e2014-05-24 12:50:23 +00007207 EVT VT = Op.getValueType();
7208
Evandro Menezescd855f72018-03-05 17:02:47 +00007209 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007210 BuildVectorSDNode *BVN =
7211 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007212 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007213 // OR commutes, so try swapping the operands.
7214 LHS = Op.getOperand(1);
7215 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007216 }
7217 if (!BVN)
7218 return Op;
7219
Evandro Menezes72f39832018-02-20 20:31:45 +00007220 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007221 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007222 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7223 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007224
Evandro Menezes72f39832018-02-20 20:31:45 +00007225 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7226 DefBits, &LHS)) ||
7227 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7228 DefBits, &LHS)))
7229 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007230
7231 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7232 UndefBits, &LHS)) ||
7233 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7234 UndefBits, &LHS)))
7235 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007236 }
7237
Evandro Menezes72f39832018-02-20 20:31:45 +00007238 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007239 return Op;
7240}
7241
Kevin Qin4473c192014-07-07 02:45:40 +00007242// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7243// be truncated to fit element width.
7244static SDValue NormalizeBuildVector(SDValue Op,
7245 SelectionDAG &DAG) {
7246 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007247 SDLoc dl(Op);
7248 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007249 EVT EltTy= VT.getVectorElementType();
7250
7251 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7252 return Op;
7253
7254 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007255 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007256 // For integer vectors, type legalization would have promoted the
7257 // operands already. Otherwise, if Op is a floating-point splat
7258 // (with operands cast to integers), then the only possibilities
7259 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007260 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007261 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007262 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007263 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007264 } else if (Lane.getNode()->isUndef()) {
7265 Lane = DAG.getUNDEF(MVT::i32);
7266 } else {
7267 assert(Lane.getValueType() == MVT::i32 &&
7268 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007269 }
7270 Ops.push_back(Lane);
7271 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007272 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007273}
7274
Evandro Menezescd855f72018-03-05 17:02:47 +00007275static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007276 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007277
Evandro Menezes72f39832018-02-20 20:31:45 +00007278 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007279 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007280 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007281 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007282 SDValue NewOp;
7283 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7284 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7285 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7286 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7287 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7288 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7289 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007290
Evandro Menezes72f39832018-02-20 20:31:45 +00007291 DefBits = ~DefBits;
7292 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7293 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7294 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7295 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007296
Evandro Menezes72f39832018-02-20 20:31:45 +00007297 DefBits = UndefBits;
7298 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7299 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7300 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7301 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7302 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7303 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7304 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007305
Evandro Menezes72f39832018-02-20 20:31:45 +00007306 DefBits = ~UndefBits;
7307 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7308 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7309 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7310 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007311 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007312
Evandro Menezescd855f72018-03-05 17:02:47 +00007313 return SDValue();
7314}
7315
7316SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7317 SelectionDAG &DAG) const {
7318 EVT VT = Op.getValueType();
7319
7320 // Try to build a simple constant vector.
7321 Op = NormalizeBuildVector(Op, DAG);
7322 if (VT.isInteger()) {
7323 // Certain vector constants, used to express things like logical NOT and
7324 // arithmetic NEG, are passed through unmodified. This allows special
7325 // patterns for these operations to match, which will lower these constants
7326 // to whatever is proven necessary.
7327 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7328 if (BVN->isConstant())
7329 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7330 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7331 APInt Val(BitSize,
7332 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7333 if (Val.isNullValue() || Val.isAllOnesValue())
7334 return Op;
7335 }
7336 }
7337
7338 if (SDValue V = ConstantBuildVector(Op, DAG))
7339 return V;
7340
Tim Northover3b0846e2014-05-24 12:50:23 +00007341 // Scan through the operands to find some interesting properties we can
7342 // exploit:
7343 // 1) If only one value is used, we can use a DUP, or
7344 // 2) if only the low element is not undef, we can just insert that, or
7345 // 3) if only one constant value is used (w/ some non-constant lanes),
7346 // we can splat the constant value into the whole vector then fill
7347 // in the non-constant lanes.
7348 // 4) FIXME: If different constant values are used, but we can intelligently
7349 // select the values we'll be overwriting for the non-constant
7350 // lanes such that we can directly materialize the vector
7351 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007352 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007353 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007354 unsigned NumElts = VT.getVectorNumElements();
7355 bool isOnlyLowElement = true;
7356 bool usesOnlyOneValue = true;
7357 bool usesOnlyOneConstantValue = true;
7358 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007359 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007360 unsigned NumConstantLanes = 0;
7361 SDValue Value;
7362 SDValue ConstantValue;
7363 for (unsigned i = 0; i < NumElts; ++i) {
7364 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007365 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7366 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007367 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007368 continue;
7369 if (i > 0)
7370 isOnlyLowElement = false;
7371 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7372 isConstant = false;
7373
7374 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7375 ++NumConstantLanes;
7376 if (!ConstantValue.getNode())
7377 ConstantValue = V;
7378 else if (ConstantValue != V)
7379 usesOnlyOneConstantValue = false;
7380 }
7381
7382 if (!Value.getNode())
7383 Value = V;
7384 else if (V != Value)
7385 usesOnlyOneValue = false;
7386 }
7387
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007388 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007389 LLVM_DEBUG(
7390 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007391 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007392 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007393
John Brawnd6e0ebe2018-11-22 11:45:23 +00007394 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7395 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7396 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7397 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007398 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7399 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007400 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007401 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007402
Sebastian Popc33af712018-03-01 15:47:39 +00007403 if (AllLanesExtractElt) {
7404 SDNode *Vector = nullptr;
7405 bool Even = false;
7406 bool Odd = false;
7407 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7408 // the Odd pattern <1,3,5,...>.
7409 for (unsigned i = 0; i < NumElts; ++i) {
7410 SDValue V = Op.getOperand(i);
7411 const SDNode *N = V.getNode();
7412 if (!isa<ConstantSDNode>(N->getOperand(1)))
7413 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007414 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007415
7416 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007417 if (!Vector) {
7418 Vector = N0.getNode();
7419 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7420 // BUILD_VECTOR.
7421 if (VT.getVectorElementType() !=
7422 N0.getValueType().getVectorElementType())
7423 break;
7424 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007425 Odd = false;
7426 Even = false;
7427 break;
7428 }
7429
7430 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7431 // indices <1,3,5,...>.
7432 uint64_t Val = N->getConstantOperandVal(1);
7433 if (Val == 2 * i) {
7434 Even = true;
7435 continue;
7436 }
7437 if (Val - 1 == 2 * i) {
7438 Odd = true;
7439 continue;
7440 }
7441
7442 // Something does not match: abort.
7443 Odd = false;
7444 Even = false;
7445 break;
7446 }
7447 if (Even || Odd) {
7448 SDValue LHS =
7449 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7450 DAG.getConstant(0, dl, MVT::i64));
7451 SDValue RHS =
7452 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7453 DAG.getConstant(NumElts, dl, MVT::i64));
7454
7455 if (Even && !Odd)
7456 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7457 RHS);
7458 if (Odd && !Even)
7459 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7460 RHS);
7461 }
7462 }
7463
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007464 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007465 // i32 and try again.
7466 if (usesOnlyOneValue) {
7467 if (!isConstant) {
7468 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007469 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007470 LLVM_DEBUG(
7471 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007472 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007473 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007474
7475 // This is actually a DUPLANExx operation, which keeps everything vectory.
7476
Tim Northover3b0846e2014-05-24 12:50:23 +00007477 SDValue Lane = Value.getOperand(1);
7478 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007479 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007480 LLVM_DEBUG(
7481 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7482 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007483 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007484 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007485
7486 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7487 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7488 }
7489
7490 if (VT.getVectorElementType().isFloatingPoint()) {
7491 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007492 EVT EltTy = VT.getVectorElementType();
7493 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7494 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007495 LLVM_DEBUG(
7496 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7497 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007498 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007499 for (unsigned i = 0; i < NumElts; ++i)
7500 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7501 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007502 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007503 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7504 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007505 Val = LowerBUILD_VECTOR(Val, DAG);
7506 if (Val.getNode())
7507 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7508 }
7509 }
7510
7511 // If there was only one constant value used and for more than one lane,
7512 // start by splatting that value, then replace the non-constant lanes. This
7513 // is better than the default, which will perform a separate initialization
7514 // for each lane.
7515 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007516 // Firstly, try to materialize the splat constant.
7517 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7518 Val = ConstantBuildVector(Vec, DAG);
7519 if (!Val) {
7520 // Otherwise, materialize the constant and splat it.
7521 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7522 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7523 }
7524
Tim Northover3b0846e2014-05-24 12:50:23 +00007525 // Now insert the non-constant lanes.
7526 for (unsigned i = 0; i < NumElts; ++i) {
7527 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007528 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007529 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007530 // Note that type legalization likely mucked about with the VT of the
7531 // source operand, so we may have to convert it here before inserting.
7532 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007533 }
7534 return Val;
7535 }
7536
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007537 // This will generate a load from the constant pool.
7538 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007539 LLVM_DEBUG(
7540 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7541 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007542 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007543 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007544
7545 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7546 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007547 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007548 return shuffle;
7549 }
7550
7551 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7552 // know the default expansion would otherwise fall back on something even
7553 // worse. For a vector with one or two non-undef values, that's
7554 // scalar_to_vector for the elements followed by a shuffle (provided the
7555 // shuffle is valid for the target) and materialization element by element
7556 // on the stack followed by a load for everything else.
7557 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007558 LLVM_DEBUG(
7559 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7560 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007561
Tim Northover3b0846e2014-05-24 12:50:23 +00007562 SDValue Vec = DAG.getUNDEF(VT);
7563 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007564 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007565
7566 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007567 // a) Avoid a RMW dependency on the full vector register, and
7568 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007569 // value is already in an S or D register, and we're forced to emit an
7570 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007571 //
7572 // We also allow types like i8 and i16 which are illegal scalar but legal
7573 // vector element types. After type-legalization the inserted value is
7574 // extended (i32) and it is safe to cast them to the vector type by ignoring
7575 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7576 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007577 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007578 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007579 ++i;
7580 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007581 LLVM_DEBUG(if (i < NumElts) dbgs()
7582 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007583 for (; i < NumElts; ++i) {
7584 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007585 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007586 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007587 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007588 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7589 }
7590 return Vec;
7591 }
7592
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007593 LLVM_DEBUG(
7594 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7595 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007596 return SDValue();
7597}
7598
7599SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7600 SelectionDAG &DAG) const {
7601 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7602
Tim Northovere4b8e132014-07-15 10:00:26 +00007603 // Check for non-constant or out of range lane.
7604 EVT VT = Op.getOperand(0).getValueType();
7605 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7606 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007607 return SDValue();
7608
Tim Northover3b0846e2014-05-24 12:50:23 +00007609
7610 // Insertion/extraction are legal for V128 types.
7611 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007612 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7613 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007614 return Op;
7615
7616 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007617 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007618 return SDValue();
7619
7620 // For V64 types, we perform insertion by expanding the value
7621 // to a V128 type and perform the insertion on that.
7622 SDLoc DL(Op);
7623 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7624 EVT WideTy = WideVec.getValueType();
7625
7626 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7627 Op.getOperand(1), Op.getOperand(2));
7628 // Re-narrow the resultant vector.
7629 return NarrowVector(Node, DAG);
7630}
7631
7632SDValue
7633AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7634 SelectionDAG &DAG) const {
7635 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7636
Tim Northovere4b8e132014-07-15 10:00:26 +00007637 // Check for non-constant or out of range lane.
7638 EVT VT = Op.getOperand(0).getValueType();
7639 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7640 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007641 return SDValue();
7642
Tim Northover3b0846e2014-05-24 12:50:23 +00007643
7644 // Insertion/extraction are legal for V128 types.
7645 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007646 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7647 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007648 return Op;
7649
7650 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007651 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007652 return SDValue();
7653
7654 // For V64 types, we perform extraction by expanding the value
7655 // to a V128 type and perform the extraction on that.
7656 SDLoc DL(Op);
7657 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7658 EVT WideTy = WideVec.getValueType();
7659
7660 EVT ExtrTy = WideTy.getVectorElementType();
7661 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7662 ExtrTy = MVT::i32;
7663
7664 // For extractions, we just return the result directly.
7665 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7666 Op.getOperand(1));
7667}
7668
7669SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7670 SelectionDAG &DAG) const {
7671 EVT VT = Op.getOperand(0).getValueType();
7672 SDLoc dl(Op);
7673 // Just in case...
7674 if (!VT.isVector())
7675 return SDValue();
7676
7677 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7678 if (!Cst)
7679 return SDValue();
7680 unsigned Val = Cst->getZExtValue();
7681
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007682 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007683
7684 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7685 if (Val == 0)
7686 return Op;
7687
Tim Northover3b0846e2014-05-24 12:50:23 +00007688 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7689 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007690 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007691 return Op;
7692
7693 return SDValue();
7694}
7695
Zvi Rackover1b736822017-07-26 08:06:58 +00007696bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007697 if (VT.getVectorNumElements() == 4 &&
7698 (VT.is128BitVector() || VT.is64BitVector())) {
7699 unsigned PFIndexes[4];
7700 for (unsigned i = 0; i != 4; ++i) {
7701 if (M[i] < 0)
7702 PFIndexes[i] = 8;
7703 else
7704 PFIndexes[i] = M[i];
7705 }
7706
7707 // Compute the index in the perfect shuffle table.
7708 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7709 PFIndexes[2] * 9 + PFIndexes[3];
7710 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7711 unsigned Cost = (PFEntry >> 30);
7712
7713 if (Cost <= 4)
7714 return true;
7715 }
7716
7717 bool DummyBool;
7718 int DummyInt;
7719 unsigned DummyUnsigned;
7720
7721 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7722 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7723 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7724 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7725 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7726 isZIPMask(M, VT, DummyUnsigned) ||
7727 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7728 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7729 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7730 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7731 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7732}
7733
7734/// getVShiftImm - Check if this is a valid build_vector for the immediate
7735/// operand of a vector shift operation, where all the elements of the
7736/// build_vector must have the same constant integer value.
7737static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7738 // Ignore bit_converts.
7739 while (Op.getOpcode() == ISD::BITCAST)
7740 Op = Op.getOperand(0);
7741 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7742 APInt SplatBits, SplatUndef;
7743 unsigned SplatBitSize;
7744 bool HasAnyUndefs;
7745 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7746 HasAnyUndefs, ElementBits) ||
7747 SplatBitSize > ElementBits)
7748 return false;
7749 Cnt = SplatBits.getSExtValue();
7750 return true;
7751}
7752
7753/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7754/// operand of a vector shift left operation. That value must be in the range:
7755/// 0 <= Value < ElementBits for a left shift; or
7756/// 0 <= Value <= ElementBits for a long left shift.
7757static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7758 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007759 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007760 if (!getVShiftImm(Op, ElementBits, Cnt))
7761 return false;
7762 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7763}
7764
7765/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007766/// operand of a vector shift right operation. The value must be in the range:
7767/// 1 <= Value <= ElementBits for a right shift; or
7768static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007769 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007770 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007771 if (!getVShiftImm(Op, ElementBits, Cnt))
7772 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007773 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7774}
7775
7776SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7777 SelectionDAG &DAG) const {
7778 EVT VT = Op.getValueType();
7779 SDLoc DL(Op);
7780 int64_t Cnt;
7781
7782 if (!Op.getOperand(1).getValueType().isVector())
7783 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007784 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007785
7786 switch (Op.getOpcode()) {
7787 default:
7788 llvm_unreachable("unexpected shift opcode");
7789
7790 case ISD::SHL:
7791 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007792 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7793 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007794 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007795 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7796 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007797 Op.getOperand(0), Op.getOperand(1));
7798 case ISD::SRA:
7799 case ISD::SRL:
7800 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007801 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007802 unsigned Opc =
7803 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007804 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7805 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007806 }
7807
7808 // Right shift register. Note, there is not a shift right register
7809 // instruction, but the shift left register instruction takes a signed
7810 // value, where negative numbers specify a right shift.
7811 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7812 : Intrinsic::aarch64_neon_ushl;
7813 // negate the shift amount
7814 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7815 SDValue NegShiftLeft =
7816 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007817 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7818 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007819 return NegShiftLeft;
7820 }
7821
7822 return SDValue();
7823}
7824
7825static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7826 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007827 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007828 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007829 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7830 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007831
7832 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7833 APInt CnstBits(VT.getSizeInBits(), 0);
7834 APInt UndefBits(VT.getSizeInBits(), 0);
7835 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7836 bool IsZero = IsCnst && (CnstBits == 0);
7837
7838 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7839 switch (CC) {
7840 default:
7841 return SDValue();
7842 case AArch64CC::NE: {
7843 SDValue Fcmeq;
7844 if (IsZero)
7845 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7846 else
7847 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7848 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7849 }
7850 case AArch64CC::EQ:
7851 if (IsZero)
7852 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7853 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7854 case AArch64CC::GE:
7855 if (IsZero)
7856 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7857 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7858 case AArch64CC::GT:
7859 if (IsZero)
7860 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7861 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7862 case AArch64CC::LS:
7863 if (IsZero)
7864 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7865 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7866 case AArch64CC::LT:
7867 if (!NoNans)
7868 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007869 // If we ignore NaNs then we can use to the MI implementation.
7870 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007871 case AArch64CC::MI:
7872 if (IsZero)
7873 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7874 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7875 }
7876 }
7877
7878 switch (CC) {
7879 default:
7880 return SDValue();
7881 case AArch64CC::NE: {
7882 SDValue Cmeq;
7883 if (IsZero)
7884 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7885 else
7886 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7887 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7888 }
7889 case AArch64CC::EQ:
7890 if (IsZero)
7891 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7892 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7893 case AArch64CC::GE:
7894 if (IsZero)
7895 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7896 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7897 case AArch64CC::GT:
7898 if (IsZero)
7899 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7900 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7901 case AArch64CC::LE:
7902 if (IsZero)
7903 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7904 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7905 case AArch64CC::LS:
7906 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7907 case AArch64CC::LO:
7908 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7909 case AArch64CC::LT:
7910 if (IsZero)
7911 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7912 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7913 case AArch64CC::HI:
7914 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7915 case AArch64CC::HS:
7916 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7917 }
7918}
7919
7920SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7921 SelectionDAG &DAG) const {
7922 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7923 SDValue LHS = Op.getOperand(0);
7924 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007925 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007926 SDLoc dl(Op);
7927
7928 if (LHS.getValueType().getVectorElementType().isInteger()) {
7929 assert(LHS.getValueType() == RHS.getValueType());
7930 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007931 SDValue Cmp =
7932 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7933 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007934 }
7935
Carey Williamsda15b5b2018-01-22 14:16:11 +00007936 const bool FullFP16 =
7937 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7938
7939 // Make v4f16 (only) fcmp operations utilise vector instructions
7940 // v8f16 support will be a litle more complicated
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007941 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7942 if (LHS.getValueType().getVectorNumElements() == 4) {
Carey Williamsda15b5b2018-01-22 14:16:11 +00007943 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7944 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7945 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7946 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7947 CmpVT = MVT::v4i32;
7948 } else
7949 return SDValue();
7950 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007951
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007952 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7953 LHS.getValueType().getVectorElementType() != MVT::f128);
Tim Northover3b0846e2014-05-24 12:50:23 +00007954
7955 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7956 // clean. Some of them require two branches to implement.
7957 AArch64CC::CondCode CC1, CC2;
7958 bool ShouldInvert;
7959 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7960
7961 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7962 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007963 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007964 if (!Cmp.getNode())
7965 return SDValue();
7966
7967 if (CC2 != AArch64CC::AL) {
7968 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007969 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007970 if (!Cmp2.getNode())
7971 return SDValue();
7972
Tim Northover45aa89c2015-02-08 00:50:47 +00007973 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007974 }
7975
Tim Northover45aa89c2015-02-08 00:50:47 +00007976 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7977
Tim Northover3b0846e2014-05-24 12:50:23 +00007978 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007979 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007980
7981 return Cmp;
7982}
7983
Amara Emersonc9916d72017-05-16 21:29:22 +00007984static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7985 SelectionDAG &DAG) {
7986 SDValue VecOp = ScalarOp.getOperand(0);
7987 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7988 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7989 DAG.getConstant(0, DL, MVT::i64));
7990}
7991
7992SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7993 SelectionDAG &DAG) const {
7994 SDLoc dl(Op);
7995 switch (Op.getOpcode()) {
7996 case ISD::VECREDUCE_ADD:
7997 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7998 case ISD::VECREDUCE_SMAX:
7999 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8000 case ISD::VECREDUCE_SMIN:
8001 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8002 case ISD::VECREDUCE_UMAX:
8003 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8004 case ISD::VECREDUCE_UMIN:
8005 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8006 case ISD::VECREDUCE_FMAX: {
8007 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8008 return DAG.getNode(
8009 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8010 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8011 Op.getOperand(0));
8012 }
8013 case ISD::VECREDUCE_FMIN: {
8014 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8015 return DAG.getNode(
8016 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8017 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8018 Op.getOperand(0));
8019 }
8020 default:
8021 llvm_unreachable("Unhandled reduction");
8022 }
8023}
8024
Oliver Stannard42699172018-02-12 14:22:03 +00008025SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8026 SelectionDAG &DAG) const {
8027 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8028 if (!Subtarget.hasLSE())
8029 return SDValue();
8030
8031 // LSE has an atomic load-add instruction, but not a load-sub.
8032 SDLoc dl(Op);
8033 MVT VT = Op.getSimpleValueType();
8034 SDValue RHS = Op.getOperand(2);
8035 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8036 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8037 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8038 Op.getOperand(0), Op.getOperand(1), RHS,
8039 AN->getMemOperand());
8040}
8041
Oliver Stannard02f08c92018-02-12 17:03:11 +00008042SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8043 SelectionDAG &DAG) const {
8044 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8045 if (!Subtarget.hasLSE())
8046 return SDValue();
8047
8048 // LSE has an atomic load-clear instruction, but not a load-and.
8049 SDLoc dl(Op);
8050 MVT VT = Op.getSimpleValueType();
8051 SDValue RHS = Op.getOperand(2);
8052 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8053 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8054 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8055 Op.getOperand(0), Op.getOperand(1), RHS,
8056 AN->getMemOperand());
8057}
8058
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008059SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8060 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8061 SDLoc dl(Op);
8062 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8063 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8064
Tri Vo6c47c622018-09-22 22:17:50 +00008065 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8066 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8067 if (Subtarget->hasCustomCallingConv())
8068 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008069
8070 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8071 DAG.getConstant(4, dl, MVT::i64));
8072 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8073 Chain =
8074 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8075 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8076 DAG.getRegisterMask(Mask), Chain.getValue(1));
8077 // To match the actual intent better, we should read the output from X15 here
8078 // again (instead of potentially spilling it to the stack), but rereading Size
8079 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8080 // here.
8081
8082 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8083 DAG.getConstant(4, dl, MVT::i64));
8084 return Chain;
8085}
8086
8087SDValue
8088AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8089 SelectionDAG &DAG) const {
8090 assert(Subtarget->isTargetWindows() &&
8091 "Only Windows alloca probing supported");
8092 SDLoc dl(Op);
8093 // Get the inputs.
8094 SDNode *Node = Op.getNode();
8095 SDValue Chain = Op.getOperand(0);
8096 SDValue Size = Op.getOperand(1);
8097 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8098 EVT VT = Node->getValueType(0);
8099
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00008100 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8101 "no-stack-arg-probe")) {
8102 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8103 Chain = SP.getValue(1);
8104 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8105 if (Align)
8106 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8107 DAG.getConstant(-(uint64_t)Align, dl, VT));
8108 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8109 SDValue Ops[2] = {SP, Chain};
8110 return DAG.getMergeValues(Ops, dl);
8111 }
8112
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008113 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8114
8115 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8116
8117 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8118 Chain = SP.getValue(1);
8119 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00008120 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008121 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8122 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00008123 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008124
8125 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8126 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8127
8128 SDValue Ops[2] = {SP, Chain};
8129 return DAG.getMergeValues(Ops, dl);
8130}
8131
Tim Northover3b0846e2014-05-24 12:50:23 +00008132/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8133/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8134/// specified in the intrinsic calls.
8135bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8136 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00008137 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00008138 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008139 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00008140 switch (Intrinsic) {
8141 case Intrinsic::aarch64_neon_ld2:
8142 case Intrinsic::aarch64_neon_ld3:
8143 case Intrinsic::aarch64_neon_ld4:
8144 case Intrinsic::aarch64_neon_ld1x2:
8145 case Intrinsic::aarch64_neon_ld1x3:
8146 case Intrinsic::aarch64_neon_ld1x4:
8147 case Intrinsic::aarch64_neon_ld2lane:
8148 case Intrinsic::aarch64_neon_ld3lane:
8149 case Intrinsic::aarch64_neon_ld4lane:
8150 case Intrinsic::aarch64_neon_ld2r:
8151 case Intrinsic::aarch64_neon_ld3r:
8152 case Intrinsic::aarch64_neon_ld4r: {
8153 Info.opc = ISD::INTRINSIC_W_CHAIN;
8154 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008155 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008156 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8157 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8158 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008159 Info.align.reset();
Matt Arsenault11171332017-12-14 21:39:51 +00008160 // volatile loads with NEON intrinsics not supported
8161 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008162 return true;
8163 }
8164 case Intrinsic::aarch64_neon_st2:
8165 case Intrinsic::aarch64_neon_st3:
8166 case Intrinsic::aarch64_neon_st4:
8167 case Intrinsic::aarch64_neon_st1x2:
8168 case Intrinsic::aarch64_neon_st1x3:
8169 case Intrinsic::aarch64_neon_st1x4:
8170 case Intrinsic::aarch64_neon_st2lane:
8171 case Intrinsic::aarch64_neon_st3lane:
8172 case Intrinsic::aarch64_neon_st4lane: {
8173 Info.opc = ISD::INTRINSIC_VOID;
8174 // Conservatively set memVT to the entire set of vectors stored.
8175 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008176 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008177 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8178 if (!ArgTy->isVectorTy())
8179 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008180 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008181 }
8182 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8183 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8184 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008185 Info.align.reset();
Matt Arsenault11171332017-12-14 21:39:51 +00008186 // volatile stores with NEON intrinsics not supported
8187 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008188 return true;
8189 }
8190 case Intrinsic::aarch64_ldaxr:
8191 case Intrinsic::aarch64_ldxr: {
8192 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8193 Info.opc = ISD::INTRINSIC_W_CHAIN;
8194 Info.memVT = MVT::getVT(PtrTy->getElementType());
8195 Info.ptrVal = I.getArgOperand(0);
8196 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008197 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
Matt Arsenault11171332017-12-14 21:39:51 +00008198 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008199 return true;
8200 }
8201 case Intrinsic::aarch64_stlxr:
8202 case Intrinsic::aarch64_stxr: {
8203 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8204 Info.opc = ISD::INTRINSIC_W_CHAIN;
8205 Info.memVT = MVT::getVT(PtrTy->getElementType());
8206 Info.ptrVal = I.getArgOperand(1);
8207 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008208 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
Matt Arsenault11171332017-12-14 21:39:51 +00008209 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008210 return true;
8211 }
8212 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008213 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008214 Info.opc = ISD::INTRINSIC_W_CHAIN;
8215 Info.memVT = MVT::i128;
8216 Info.ptrVal = I.getArgOperand(0);
8217 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008218 Info.align = Align(16);
Matt Arsenault11171332017-12-14 21:39:51 +00008219 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008220 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008221 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008222 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008223 Info.opc = ISD::INTRINSIC_W_CHAIN;
8224 Info.memVT = MVT::i128;
8225 Info.ptrVal = I.getArgOperand(2);
8226 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008227 Info.align = Align(16);
Matt Arsenault11171332017-12-14 21:39:51 +00008228 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008229 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008230 default:
8231 break;
8232 }
8233
8234 return false;
8235}
8236
John Brawne3b44f92018-03-23 14:47:07 +00008237bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8238 ISD::LoadExtType ExtTy,
8239 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008240 // TODO: This may be worth removing. Check regression tests for diffs.
8241 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8242 return false;
8243
John Brawne3b44f92018-03-23 14:47:07 +00008244 // If we're reducing the load width in order to avoid having to use an extra
8245 // instruction to do extension then it's probably a good idea.
8246 if (ExtTy != ISD::NON_EXTLOAD)
8247 return true;
8248 // Don't reduce load width if it would prevent us from combining a shift into
8249 // the offset.
8250 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8251 assert(Mem);
8252 const SDValue &Base = Mem->getBasePtr();
8253 if (Base.getOpcode() == ISD::ADD &&
8254 Base.getOperand(1).getOpcode() == ISD::SHL &&
8255 Base.getOperand(1).hasOneUse() &&
8256 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8257 // The shift can be combined if it matches the size of the value being
8258 // loaded (and so reducing the width would make it not match).
8259 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8260 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8261 if (ShiftAmount == Log2_32(LoadBytes))
8262 return false;
8263 }
8264 // We have no reason to disallow reducing the load width, so allow it.
8265 return true;
8266}
8267
Tim Northover3b0846e2014-05-24 12:50:23 +00008268// Truncations from 64-bit GPR to 32-bit GPR is free.
8269bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8270 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8271 return false;
8272 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8273 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008274 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008275}
8276bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008277 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008278 return false;
8279 unsigned NumBits1 = VT1.getSizeInBits();
8280 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008281 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008282}
8283
Chad Rosier54390052015-02-23 19:15:16 +00008284/// Check if it is profitable to hoist instruction in then/else to if.
8285/// Not profitable if I and it's user can form a FMA instruction
8286/// because we prefer FMSUB/FMADD.
8287bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8288 if (I->getOpcode() != Instruction::FMul)
8289 return true;
8290
Davide Italiano3e9986f2017-04-18 00:29:54 +00008291 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008292 return true;
8293
8294 Instruction *User = I->user_back();
8295
8296 if (User &&
8297 !(User->getOpcode() == Instruction::FSub ||
8298 User->getOpcode() == Instruction::FAdd))
8299 return true;
8300
8301 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008302 const DataLayout &DL = I->getModule()->getDataLayout();
8303 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008304
Eric Christopher114fa1c2016-02-29 22:50:49 +00008305 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8306 isOperationLegalOrCustom(ISD::FMA, VT) &&
8307 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8308 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008309}
8310
Tim Northover3b0846e2014-05-24 12:50:23 +00008311// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8312// 64-bit GPR.
8313bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8314 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8315 return false;
8316 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8317 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008318 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008319}
8320bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008321 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008322 return false;
8323 unsigned NumBits1 = VT1.getSizeInBits();
8324 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008325 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008326}
8327
8328bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8329 EVT VT1 = Val.getValueType();
8330 if (isZExtFree(VT1, VT2)) {
8331 return true;
8332 }
8333
8334 if (Val.getOpcode() != ISD::LOAD)
8335 return false;
8336
8337 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008338 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8339 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8340 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008341}
8342
Quentin Colombet6843ac42015-03-31 20:52:32 +00008343bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8344 if (isa<FPExtInst>(Ext))
8345 return false;
8346
Haicheng Wu50692a22017-08-01 21:26:45 +00008347 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008348 if (Ext->getType()->isVectorTy())
8349 return false;
8350
8351 for (const Use &U : Ext->uses()) {
8352 // The extension is free if we can fold it with a left shift in an
8353 // addressing mode or an arithmetic operation: add, sub, and cmp.
8354
8355 // Is there a shift?
8356 const Instruction *Instr = cast<Instruction>(U.getUser());
8357
8358 // Is this a constant shift?
8359 switch (Instr->getOpcode()) {
8360 case Instruction::Shl:
8361 if (!isa<ConstantInt>(Instr->getOperand(1)))
8362 return false;
8363 break;
8364 case Instruction::GetElementPtr: {
8365 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008366 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008367 std::advance(GTI, U.getOperandNo()-1);
8368 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008369 // This extension will end up with a shift because of the scaling factor.
8370 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8371 // Get the shift amount based on the scaling factor:
8372 // log2(sizeof(IdxTy)) - log2(8).
8373 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008374 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008375 // Is the constant foldable in the shift of the addressing mode?
8376 // I.e., shift amount is between 1 and 4 inclusive.
8377 if (ShiftAmt == 0 || ShiftAmt > 4)
8378 return false;
8379 break;
8380 }
8381 case Instruction::Trunc:
8382 // Check if this is a noop.
8383 // trunc(sext ty1 to ty2) to ty1.
8384 if (Instr->getType() == Ext->getOperand(0)->getType())
8385 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008386 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008387 default:
8388 return false;
8389 }
8390
8391 // At this point we can use the bfm family, so this extension is free
8392 // for that use.
8393 }
8394 return true;
8395}
8396
Florian Hahn3b251962019-02-05 10:27:40 +00008397/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8398/// or upper half of the vector elements.
8399static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8400 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8401 auto *FullVT = cast<VectorType>(FullV->getType());
8402 auto *HalfVT = cast<VectorType>(HalfV->getType());
8403 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8404 };
8405
8406 auto extractHalf = [](Value *FullV, Value *HalfV) {
8407 auto *FullVT = cast<VectorType>(FullV->getType());
8408 auto *HalfVT = cast<VectorType>(HalfV->getType());
8409 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8410 };
8411
8412 Constant *M1, *M2;
8413 Value *S1Op1, *S2Op1;
8414 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8415 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8416 return false;
8417
8418 // Check that the operands are half as wide as the result and we extract
8419 // half of the elements of the input vectors.
8420 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8421 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8422 return false;
8423
8424 // Check the mask extracts either the lower or upper half of vector
8425 // elements.
8426 int M1Start = -1;
8427 int M2Start = -1;
8428 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8429 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8430 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8431 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8432 return false;
8433
8434 return true;
8435}
8436
8437/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8438/// of the vector elements.
8439static bool areExtractExts(Value *Ext1, Value *Ext2) {
8440 auto areExtDoubled = [](Instruction *Ext) {
8441 return Ext->getType()->getScalarSizeInBits() ==
8442 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8443 };
8444
8445 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8446 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8447 !areExtDoubled(cast<Instruction>(Ext1)) ||
8448 !areExtDoubled(cast<Instruction>(Ext2)))
8449 return false;
8450
8451 return true;
8452}
8453
8454/// Check if sinking \p I's operands to I's basic block is profitable, because
8455/// the operands can be folded into a target instruction, e.g.
8456/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8457bool AArch64TargetLowering::shouldSinkOperands(
8458 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8459 if (!I->getType()->isVectorTy())
8460 return false;
8461
8462 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8463 switch (II->getIntrinsicID()) {
8464 case Intrinsic::aarch64_neon_umull:
8465 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8466 return false;
8467 Ops.push_back(&II->getOperandUse(0));
8468 Ops.push_back(&II->getOperandUse(1));
8469 return true;
8470 default:
8471 return false;
8472 }
8473 }
8474
8475 switch (I->getOpcode()) {
8476 case Instruction::Sub:
8477 case Instruction::Add: {
8478 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8479 return false;
8480
8481 // If the exts' operands extract either the lower or upper elements, we
8482 // can sink them too.
8483 auto Ext1 = cast<Instruction>(I->getOperand(0));
8484 auto Ext2 = cast<Instruction>(I->getOperand(1));
8485 if (areExtractShuffleVectors(Ext1, Ext2)) {
8486 Ops.push_back(&Ext1->getOperandUse(0));
8487 Ops.push_back(&Ext2->getOperandUse(0));
8488 }
8489
8490 Ops.push_back(&I->getOperandUse(0));
8491 Ops.push_back(&I->getOperandUse(1));
8492
8493 return true;
8494 }
8495 default:
8496 return false;
8497 }
8498 return false;
8499}
8500
Tim Northover3b0846e2014-05-24 12:50:23 +00008501bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8502 unsigned &RequiredAligment) const {
8503 if (!LoadedType.isSimple() ||
8504 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8505 return false;
8506 // Cyclone supports unaligned accesses.
8507 RequiredAligment = 0;
8508 unsigned NumBits = LoadedType.getSizeInBits();
8509 return NumBits == 32 || NumBits == 64;
8510}
8511
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008512/// A helper function for determining the number of interleaved accesses we
8513/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008514unsigned
8515AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8516 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008517 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8518}
8519
Geoff Berryb1e87142017-07-14 21:44:12 +00008520MachineMemOperand::Flags
8521AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8522 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8523 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8524 return MOStridedAccess;
8525 return MachineMemOperand::MONone;
8526}
8527
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008528bool AArch64TargetLowering::isLegalInterleavedAccessType(
8529 VectorType *VecTy, const DataLayout &DL) const {
8530
8531 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8532 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8533
8534 // Ensure the number of vector elements is greater than 1.
8535 if (VecTy->getNumElements() < 2)
8536 return false;
8537
8538 // Ensure the element type is legal.
8539 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8540 return false;
8541
8542 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8543 // 128 will be split into multiple interleaved accesses.
8544 return VecSize == 64 || VecSize % 128 == 0;
8545}
8546
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008547/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008548///
8549/// E.g. Lower an interleaved load (Factor = 2):
8550/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8551/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8552/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8553///
8554/// Into:
8555/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8556/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8557/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8558bool AArch64TargetLowering::lowerInterleavedLoad(
8559 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8560 ArrayRef<unsigned> Indices, unsigned Factor) const {
8561 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8562 "Invalid interleave factor");
8563 assert(!Shuffles.empty() && "Empty shufflevector input");
8564 assert(Shuffles.size() == Indices.size() &&
8565 "Unmatched number of shufflevectors and indices");
8566
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008567 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008568
8569 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008570
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008571 // Skip if we do not have NEON and skip illegal vector types. We can
8572 // "legalize" wide vector types into multiple interleaved accesses as long as
8573 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008574 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008575 return false;
8576
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008577 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8578
Hao Liu7ec8ee32015-06-26 02:32:07 +00008579 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8580 // load integer vectors first and then convert to pointer vectors.
8581 Type *EltTy = VecTy->getVectorElementType();
8582 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008583 VecTy =
8584 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008585
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008586 IRBuilder<> Builder(LI);
8587
8588 // The base address of the load.
8589 Value *BaseAddr = LI->getPointerOperand();
8590
8591 if (NumLoads > 1) {
8592 // If we're going to generate more than one load, reset the sub-vector type
8593 // to something legal.
8594 VecTy = VectorType::get(VecTy->getVectorElementType(),
8595 VecTy->getVectorNumElements() / NumLoads);
8596
8597 // We will compute the pointer operand of each load from the original base
8598 // address using GEPs. Cast the base address to a pointer to the scalar
8599 // element type.
8600 BaseAddr = Builder.CreateBitCast(
8601 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8602 LI->getPointerAddressSpace()));
8603 }
8604
Hao Liu7ec8ee32015-06-26 02:32:07 +00008605 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8606 Type *Tys[2] = {VecTy, PtrTy};
8607 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8608 Intrinsic::aarch64_neon_ld3,
8609 Intrinsic::aarch64_neon_ld4};
8610 Function *LdNFunc =
8611 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8612
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008613 // Holds sub-vectors extracted from the load intrinsic return values. The
8614 // sub-vectors are associated with the shufflevector instructions they will
8615 // replace.
8616 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008617
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008618 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008619
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008620 // If we're generating more than one load, compute the base address of
8621 // subsequent loads as an offset from the previous.
8622 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008623 BaseAddr =
8624 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8625 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008626
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008627 CallInst *LdN = Builder.CreateCall(
8628 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008629
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008630 // Extract and store the sub-vectors returned by the load intrinsic.
8631 for (unsigned i = 0; i < Shuffles.size(); i++) {
8632 ShuffleVectorInst *SVI = Shuffles[i];
8633 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008634
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008635 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8636
8637 // Convert the integer vector to pointer vector if the element is pointer.
8638 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008639 SubVec = Builder.CreateIntToPtr(
8640 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8641 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008642 SubVecs[SVI].push_back(SubVec);
8643 }
8644 }
8645
8646 // Replace uses of the shufflevector instructions with the sub-vectors
8647 // returned by the load intrinsic. If a shufflevector instruction is
8648 // associated with more than one sub-vector, those sub-vectors will be
8649 // concatenated into a single wide vector.
8650 for (ShuffleVectorInst *SVI : Shuffles) {
8651 auto &SubVec = SubVecs[SVI];
8652 auto *WideVec =
8653 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8654 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008655 }
8656
8657 return true;
8658}
8659
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008660/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008661///
8662/// E.g. Lower an interleaved store (Factor = 3):
8663/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008664/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008665/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8666///
8667/// Into:
8668/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8669/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8670/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8671/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8672///
8673/// Note that the new shufflevectors will be removed and we'll only generate one
8674/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008675///
8676/// Example for a more general valid mask (Factor 3). Lower:
8677/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8678/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8679/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8680///
8681/// Into:
8682/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8683/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8684/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8685/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008686bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8687 ShuffleVectorInst *SVI,
8688 unsigned Factor) const {
8689 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8690 "Invalid interleave factor");
8691
8692 VectorType *VecTy = SVI->getType();
8693 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8694 "Invalid interleaved store");
8695
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008696 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008697 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008698 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008699
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008700 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008701
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008702 // Skip if we do not have NEON and skip illegal vector types. We can
8703 // "legalize" wide vector types into multiple interleaved accesses as long as
8704 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008705 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008706 return false;
8707
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008708 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8709
Hao Liu7ec8ee32015-06-26 02:32:07 +00008710 Value *Op0 = SVI->getOperand(0);
8711 Value *Op1 = SVI->getOperand(1);
8712 IRBuilder<> Builder(SI);
8713
8714 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8715 // vectors to integer vectors.
8716 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008717 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008718 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008719
8720 // Convert to the corresponding integer vector.
8721 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8722 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8723 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8724
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008725 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008726 }
8727
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008728 // The base address of the store.
8729 Value *BaseAddr = SI->getPointerOperand();
8730
8731 if (NumStores > 1) {
8732 // If we're going to generate more than one store, reset the lane length
8733 // and sub-vector type to something legal.
8734 LaneLen /= NumStores;
8735 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8736
8737 // We will compute the pointer operand of each store from the original base
8738 // address using GEPs. Cast the base address to a pointer to the scalar
8739 // element type.
8740 BaseAddr = Builder.CreateBitCast(
8741 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8742 SI->getPointerAddressSpace()));
8743 }
8744
8745 auto Mask = SVI->getShuffleMask();
8746
Hao Liu7ec8ee32015-06-26 02:32:07 +00008747 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8748 Type *Tys[2] = {SubVecTy, PtrTy};
8749 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8750 Intrinsic::aarch64_neon_st3,
8751 Intrinsic::aarch64_neon_st4};
8752 Function *StNFunc =
8753 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8754
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008755 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008756
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008757 SmallVector<Value *, 5> Ops;
8758
8759 // Split the shufflevector operands into sub vectors for the new stN call.
8760 for (unsigned i = 0; i < Factor; i++) {
8761 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8762 if (Mask[IdxI] >= 0) {
8763 Ops.push_back(Builder.CreateShuffleVector(
8764 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8765 } else {
8766 unsigned StartMask = 0;
8767 for (unsigned j = 1; j < LaneLen; j++) {
8768 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8769 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8770 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8771 break;
8772 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008773 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008774 // Note: Filling undef gaps with random elements is ok, since
8775 // those elements were being written anyway (with undefs).
8776 // In the case of all undefs we're defaulting to using elems from 0
8777 // Note: StartMask cannot be negative, it's checked in
8778 // isReInterleaveMask
8779 Ops.push_back(Builder.CreateShuffleVector(
8780 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008781 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008782 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008783
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008784 // If we generating more than one store, we compute the base address of
8785 // subsequent stores as an offset from the previous.
8786 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008787 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8788 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008789
8790 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8791 Builder.CreateCall(StNFunc, Ops);
8792 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008793 return true;
8794}
8795
Tim Northover3b0846e2014-05-24 12:50:23 +00008796static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8797 unsigned AlignCheck) {
8798 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8799 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8800}
8801
Sjoerd Meijer180f1ae2019-04-30 08:38:12 +00008802EVT AArch64TargetLowering::getOptimalMemOpType(
8803 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8804 bool ZeroMemset, bool MemcpyStrSrc,
8805 const AttributeList &FuncAttributes) const {
8806 bool CanImplicitFloat =
8807 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
JF Bastien29200612018-09-06 16:03:32 +00008808 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8809 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8810 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8811 // taken one instruction to materialize the v2i64 zero and one store (with
8812 // restrictive addressing mode). Just do i64 stores.
8813 bool IsSmallMemset = IsMemset && Size < 32;
8814 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8815 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8816 return true;
8817 bool Fast;
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00008818 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8819 &Fast) &&
8820 Fast;
JF Bastien29200612018-09-06 16:03:32 +00008821 };
8822
8823 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8824 AlignmentIsAcceptable(MVT::v2i64, 16))
8825 return MVT::v2i64;
8826 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008827 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008828 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008829 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008830 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008831 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008832 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008833}
8834
Amara Emerson13af1ed2019-07-24 22:17:31 +00008835LLT AArch64TargetLowering::getOptimalMemOpLLT(
8836 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8837 bool ZeroMemset, bool MemcpyStrSrc,
8838 const AttributeList &FuncAttributes) const {
8839 bool CanImplicitFloat =
8840 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8841 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8842 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8843 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8844 // taken one instruction to materialize the v2i64 zero and one store (with
8845 // restrictive addressing mode). Just do i64 stores.
8846 bool IsSmallMemset = IsMemset && Size < 32;
8847 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8848 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8849 return true;
8850 bool Fast;
8851 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8852 &Fast) &&
8853 Fast;
8854 };
8855
8856 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8857 AlignmentIsAcceptable(MVT::v2i64, 16))
8858 return LLT::vector(2, 64);
8859 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8860 return LLT::scalar(128);
8861 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8862 return LLT::scalar(64);
8863 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8864 return LLT::scalar(32);
8865 return LLT();
8866}
8867
Tim Northover3b0846e2014-05-24 12:50:23 +00008868// 12-bit optionally shifted immediates are legal for adds.
8869bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008870 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008871 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8872 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008873 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008874 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008875 // Same encoding for add/sub, just flip the sign.
8876 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008877 bool IsLegal = ((Immed >> 12) == 0 ||
8878 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008879 LLVM_DEBUG(dbgs() << "Is " << Immed
8880 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008881 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008882}
8883
8884// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8885// immediates is the same as for an add or a sub.
8886bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008887 return isLegalAddImmediate(Immed);
8888}
8889
8890/// isLegalAddressingMode - Return true if the addressing mode represented
8891/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008892bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8893 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008894 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008895 // AArch64 has five basic addressing modes:
8896 // reg
8897 // reg + 9-bit signed offset
8898 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8899 // reg1 + reg2
8900 // reg + SIZE_IN_BYTES * reg
8901
8902 // No global is ever allowed as a base.
8903 if (AM.BaseGV)
8904 return false;
8905
8906 // No reg+reg+imm addressing.
8907 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8908 return false;
8909
8910 // check reg + imm case:
8911 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8912 uint64_t NumBytes = 0;
8913 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008914 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008915 NumBytes = NumBits / 8;
8916 if (!isPowerOf2_64(NumBits))
8917 NumBytes = 0;
8918 }
8919
8920 if (!AM.Scale) {
8921 int64_t Offset = AM.BaseOffs;
8922
8923 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008924 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008925 return true;
8926
8927 // 12-bit unsigned offset
8928 unsigned shift = Log2_64(NumBytes);
8929 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8930 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8931 (Offset >> shift) << shift == Offset)
8932 return true;
8933 return false;
8934 }
8935
8936 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8937
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008938 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008939}
8940
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008941bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8942 // Consider splitting large offset of struct or array.
8943 return true;
8944}
8945
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008946int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8947 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008948 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008949 // Scaling factors are not free at all.
8950 // Operands | Rt Latency
8951 // -------------------------------------------
8952 // Rt, [Xn, Xm] | 4
8953 // -------------------------------------------
8954 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8955 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008956 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008957 // Scale represents reg2 * scale, thus account for 1 if
8958 // it is not equal to 0 or 1.
8959 return AM.Scale != 0 && AM.Scale != 1;
8960 return -1;
8961}
8962
8963bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8964 VT = VT.getScalarType();
8965
8966 if (!VT.isSimple())
8967 return false;
8968
8969 switch (VT.getSimpleVT().SimpleTy) {
8970 case MVT::f32:
8971 case MVT::f64:
8972 return true;
8973 default:
8974 break;
8975 }
8976
8977 return false;
8978}
8979
8980const MCPhysReg *
8981AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8982 // LR is a callee-save register, but we must treat it as clobbered by any call
8983 // site. Hence we include LR in the scratch registers, which are in turn added
8984 // as implicit-defs for stackmaps and patchpoints.
8985 static const MCPhysReg ScratchRegs[] = {
8986 AArch64::X16, AArch64::X17, AArch64::LR, 0
8987 };
8988 return ScratchRegs;
8989}
8990
8991bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008992AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8993 CombineLevel Level) const {
8994 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008995 EVT VT = N->getValueType(0);
8996 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8997 // it with shift to let it be lowered to UBFX.
8998 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8999 isa<ConstantSDNode>(N->getOperand(1))) {
9000 uint64_t TruncMask = N->getConstantOperandVal(1);
9001 if (isMask_64(TruncMask) &&
9002 N->getOperand(0).getOpcode() == ISD::SRL &&
9003 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9004 return false;
9005 }
9006 return true;
9007}
9008
9009bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9010 Type *Ty) const {
9011 assert(Ty->isIntegerTy());
9012
9013 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9014 if (BitSize == 0)
9015 return false;
9016
9017 int64_t Val = Imm.getSExtValue();
9018 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9019 return true;
9020
9021 if ((int64_t)Val < 0)
9022 Val = ~Val;
9023 if (BitSize == 32)
9024 Val &= (1LL << 32) - 1;
9025
9026 unsigned LZ = countLeadingZeros((uint64_t)Val);
9027 unsigned Shift = (63 - LZ) / 16;
9028 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00009029 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00009030}
9031
Sebastian Pop41073e82018-03-06 16:54:55 +00009032bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9033 unsigned Index) const {
9034 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9035 return false;
9036
9037 return (Index == 0 || Index == ResVT.getVectorNumElements());
9038}
9039
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00009040/// Turn vector tests of the signbit in the form of:
9041/// xor (sra X, elt_size(X)-1), -1
9042/// into:
9043/// cmge X, X, #0
9044static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9045 const AArch64Subtarget *Subtarget) {
9046 EVT VT = N->getValueType(0);
9047 if (!Subtarget->hasNEON() || !VT.isVector())
9048 return SDValue();
9049
9050 // There must be a shift right algebraic before the xor, and the xor must be a
9051 // 'not' operation.
9052 SDValue Shift = N->getOperand(0);
9053 SDValue Ones = N->getOperand(1);
9054 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9055 !ISD::isBuildVectorAllOnes(Ones.getNode()))
9056 return SDValue();
9057
9058 // The shift should be smearing the sign bit across each vector element.
9059 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9060 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9061 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9062 return SDValue();
9063
9064 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9065}
9066
Tim Northover3b0846e2014-05-24 12:50:23 +00009067// Generate SUBS and CSEL for integer abs.
9068static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9069 EVT VT = N->getValueType(0);
9070
9071 SDValue N0 = N->getOperand(0);
9072 SDValue N1 = N->getOperand(1);
9073 SDLoc DL(N);
9074
9075 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9076 // and change it to SUB and CSEL.
9077 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9078 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9079 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9080 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9081 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009082 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00009083 N0.getOperand(0));
9084 // Generate SUBS & CSEL.
9085 SDValue Cmp =
9086 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009087 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009088 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009089 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00009090 SDValue(Cmp.getNode(), 1));
9091 }
9092 return SDValue();
9093}
9094
Tim Northover3b0846e2014-05-24 12:50:23 +00009095static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9096 TargetLowering::DAGCombinerInfo &DCI,
9097 const AArch64Subtarget *Subtarget) {
9098 if (DCI.isBeforeLegalizeOps())
9099 return SDValue();
9100
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00009101 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9102 return Cmp;
9103
Tim Northover3b0846e2014-05-24 12:50:23 +00009104 return performIntegerAbsCombine(N, DAG);
9105}
9106
Chad Rosier17020f92014-07-23 14:57:52 +00009107SDValue
9108AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9109 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00009110 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00009111 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00009112 if (isIntDivCheap(N->getValueType(0), Attr))
9113 return SDValue(N,0); // Lower SDIV as SDIV
9114
Chad Rosier17020f92014-07-23 14:57:52 +00009115 // fold (sdiv X, pow2)
9116 EVT VT = N->getValueType(0);
9117 if ((VT != MVT::i32 && VT != MVT::i64) ||
9118 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9119 return SDValue();
9120
9121 SDLoc DL(N);
9122 SDValue N0 = N->getOperand(0);
9123 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009124 SDValue Zero = DAG.getConstant(0, DL, VT);
9125 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00009126
9127 // Add (N0 < 0) ? Pow2 - 1 : 0;
9128 SDValue CCVal;
9129 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9130 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9131 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9132
Craig Toppera568a272018-07-30 21:04:34 +00009133 Created.push_back(Cmp.getNode());
9134 Created.push_back(Add.getNode());
9135 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00009136
9137 // Divide by pow2.
9138 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009139 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00009140
9141 // If we're dividing by a positive value, we're done. Otherwise, we must
9142 // negate the result.
9143 if (Divisor.isNonNegative())
9144 return SRA;
9145
Craig Toppera568a272018-07-30 21:04:34 +00009146 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009147 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00009148}
9149
Tim Northover3b0846e2014-05-24 12:50:23 +00009150static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9151 TargetLowering::DAGCombinerInfo &DCI,
9152 const AArch64Subtarget *Subtarget) {
9153 if (DCI.isBeforeLegalizeOps())
9154 return SDValue();
9155
Chad Rosier31ee8132016-11-11 17:07:37 +00009156 // The below optimizations require a constant RHS.
9157 if (!isa<ConstantSDNode>(N->getOperand(1)))
9158 return SDValue();
9159
9160 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9161 const APInt &ConstValue = C->getAPIntValue();
9162
Tim Northover3b0846e2014-05-24 12:50:23 +00009163 // Multiplication of a power of two plus/minus one can be done more
9164 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9165 // future CPUs have a cheaper MADD instruction, this may need to be
9166 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9167 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009168 // More aggressively, some multiplications N0 * C can be lowered to
9169 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9170 // e.g. 6=3*2=(2+1)*2.
9171 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9172 // which equals to (1+2)*16-(1+2).
9173 SDValue N0 = N->getOperand(0);
9174 // TrailingZeroes is used to test if the mul can be lowered to
9175 // shift+add+shift.
9176 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9177 if (TrailingZeroes) {
9178 // Conservatively do not lower to shift+add+shift if the mul might be
9179 // folded into smul or umul.
9180 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9181 isZeroExtended(N0.getNode(), DAG)))
9182 return SDValue();
9183 // Conservatively do not lower to shift+add+shift if the mul might be
9184 // folded into madd or msub.
9185 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9186 N->use_begin()->getOpcode() == ISD::SUB))
9187 return SDValue();
9188 }
9189 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9190 // and shift+add+shift.
9191 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9192
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009193 unsigned ShiftAmt, AddSubOpc;
9194 // Is the shifted value the LHS operand of the add/sub?
9195 bool ShiftValUseIsN0 = true;
9196 // Do we need to negate the result?
9197 bool NegateResult = false;
9198
Chad Rosier31ee8132016-11-11 17:07:37 +00009199 if (ConstValue.isNonNegative()) {
9200 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00009201 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00009202 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9203 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009204 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00009205 if (SCVMinus1.isPowerOf2()) {
9206 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009207 AddSubOpc = ISD::ADD;
9208 } else if (CVPlus1.isPowerOf2()) {
9209 ShiftAmt = CVPlus1.logBase2();
9210 AddSubOpc = ISD::SUB;
9211 } else
9212 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00009213 } else {
9214 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00009215 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009216 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009217 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009218 if (CVNegPlus1.isPowerOf2()) {
9219 ShiftAmt = CVNegPlus1.logBase2();
9220 AddSubOpc = ISD::SUB;
9221 ShiftValUseIsN0 = false;
9222 } else if (CVNegMinus1.isPowerOf2()) {
9223 ShiftAmt = CVNegMinus1.logBase2();
9224 AddSubOpc = ISD::ADD;
9225 NegateResult = true;
9226 } else
9227 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009228 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009229
9230 SDLoc DL(N);
9231 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009232 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009233 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9234
9235 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9236 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9237 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009238 assert(!(NegateResult && TrailingZeroes) &&
9239 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009240 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009241 if (NegateResult)
9242 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9243 // Shift the result.
9244 if (TrailingZeroes)
9245 return DAG.getNode(ISD::SHL, DL, VT, Res,
9246 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9247 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00009248}
9249
Jim Grosbachf7502c42014-07-18 00:40:52 +00009250static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9251 SelectionDAG &DAG) {
9252 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9253 // optimize away operation when it's from a constant.
9254 //
9255 // The general transformation is:
9256 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9257 // AND(VECTOR_CMP(x,y), constant2)
9258 // constant2 = UNARYOP(constant)
9259
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009260 // Early exit if this isn't a vector operation, the operand of the
9261 // unary operation isn't a bitwise AND, or if the sizes of the operations
9262 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009263 EVT VT = N->getValueType(0);
9264 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009265 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9266 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009267 return SDValue();
9268
Jim Grosbach724e4382014-07-23 20:41:43 +00009269 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009270 // make the transformation for non-constant splats as well, but it's unclear
9271 // that would be a benefit as it would not eliminate any operations, just
9272 // perform one more step in scalar code before moving to the vector unit.
9273 if (BuildVectorSDNode *BV =
9274 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009275 // Bail out if the vector isn't a constant.
9276 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009277 return SDValue();
9278
9279 // Everything checks out. Build up the new and improved node.
9280 SDLoc DL(N);
9281 EVT IntVT = BV->getValueType(0);
9282 // Create a new constant of the appropriate type for the transformed
9283 // DAG.
9284 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9285 // The AND node needs bitcasts to/from an integer vector type around it.
9286 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9287 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9288 N->getOperand(0)->getOperand(0), MaskConst);
9289 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9290 return Res;
9291 }
9292
9293 return SDValue();
9294}
9295
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009296static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9297 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009298 // First try to optimize away the conversion when it's conditionally from
9299 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009300 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009301 return Res;
9302
Tim Northover3b0846e2014-05-24 12:50:23 +00009303 EVT VT = N->getValueType(0);
9304 if (VT != MVT::f32 && VT != MVT::f64)
9305 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009306
Tim Northover3b0846e2014-05-24 12:50:23 +00009307 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009308 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009309 return SDValue();
9310
9311 // If the result of an integer load is only used by an integer-to-float
9312 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009313 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009314 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009315 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009316 // Do not change the width of a volatile load.
9317 !cast<LoadSDNode>(N0)->isVolatile()) {
9318 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9319 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009320 LN0->getPointerInfo(), LN0->getAlignment(),
9321 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009322
9323 // Make sure successors of the original load stay after it by updating them
9324 // to use the new Chain.
9325 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9326
9327 unsigned Opcode =
9328 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9329 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9330 }
9331
9332 return SDValue();
9333}
9334
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009335/// Fold a floating-point multiply by power of two into floating-point to
9336/// fixed-point conversion.
9337static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009338 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009339 const AArch64Subtarget *Subtarget) {
9340 if (!Subtarget->hasNEON())
9341 return SDValue();
9342
Sam Parkera0bd6f82019-06-03 08:49:17 +00009343 if (!N->getValueType(0).isSimple())
9344 return SDValue();
9345
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009346 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009347 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9348 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009349 return SDValue();
9350
9351 SDValue ConstVec = Op->getOperand(1);
9352 if (!isa<BuildVectorSDNode>(ConstVec))
9353 return SDValue();
9354
9355 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9356 uint32_t FloatBits = FloatTy.getSizeInBits();
9357 if (FloatBits != 32 && FloatBits != 64)
9358 return SDValue();
9359
9360 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9361 uint32_t IntBits = IntTy.getSizeInBits();
9362 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9363 return SDValue();
9364
9365 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9366 if (IntBits > FloatBits)
9367 return SDValue();
9368
9369 BitVector UndefElements;
9370 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9371 int32_t Bits = IntBits == 64 ? 64 : 32;
9372 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9373 if (C == -1 || C == 0 || C > Bits)
9374 return SDValue();
9375
9376 MVT ResTy;
9377 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9378 switch (NumLanes) {
9379 default:
9380 return SDValue();
9381 case 2:
9382 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9383 break;
9384 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009385 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009386 break;
9387 }
9388
Silviu Barangafa00ba32016-08-08 13:13:57 +00009389 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9390 return SDValue();
9391
9392 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9393 "Illegal vector type after legalization");
9394
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009395 SDLoc DL(N);
9396 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9397 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9398 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9399 SDValue FixConv =
9400 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9401 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9402 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9403 // We can handle smaller integers by generating an extra trunc.
9404 if (IntBits < FloatBits)
9405 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9406
9407 return FixConv;
9408}
9409
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009410/// Fold a floating-point divide by power of two into fixed-point to
9411/// floating-point conversion.
9412static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009413 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009414 const AArch64Subtarget *Subtarget) {
9415 if (!Subtarget->hasNEON())
9416 return SDValue();
9417
9418 SDValue Op = N->getOperand(0);
9419 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009420 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9421 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009422 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9423 return SDValue();
9424
9425 SDValue ConstVec = N->getOperand(1);
9426 if (!isa<BuildVectorSDNode>(ConstVec))
9427 return SDValue();
9428
9429 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9430 int32_t IntBits = IntTy.getSizeInBits();
9431 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9432 return SDValue();
9433
9434 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9435 int32_t FloatBits = FloatTy.getSizeInBits();
9436 if (FloatBits != 32 && FloatBits != 64)
9437 return SDValue();
9438
9439 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9440 if (IntBits > FloatBits)
9441 return SDValue();
9442
9443 BitVector UndefElements;
9444 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9445 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9446 if (C == -1 || C == 0 || C > FloatBits)
9447 return SDValue();
9448
9449 MVT ResTy;
9450 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9451 switch (NumLanes) {
9452 default:
9453 return SDValue();
9454 case 2:
9455 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9456 break;
9457 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009458 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009459 break;
9460 }
9461
Tim Northover85cf5642016-08-26 18:52:31 +00009462 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9463 return SDValue();
9464
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009465 SDLoc DL(N);
9466 SDValue ConvInput = Op.getOperand(0);
9467 bool IsSigned = Opc == ISD::SINT_TO_FP;
9468 if (IntBits < FloatBits)
9469 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9470 ResTy, ConvInput);
9471
9472 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9473 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9474 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9475 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9476 DAG.getConstant(C, DL, MVT::i32));
9477}
9478
Tim Northover3b0846e2014-05-24 12:50:23 +00009479/// An EXTR instruction is made up of two shifts, ORed together. This helper
9480/// searches for and classifies those shifts.
9481static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9482 bool &FromHi) {
9483 if (N.getOpcode() == ISD::SHL)
9484 FromHi = false;
9485 else if (N.getOpcode() == ISD::SRL)
9486 FromHi = true;
9487 else
9488 return false;
9489
9490 if (!isa<ConstantSDNode>(N.getOperand(1)))
9491 return false;
9492
9493 ShiftAmount = N->getConstantOperandVal(1);
9494 Src = N->getOperand(0);
9495 return true;
9496}
9497
9498/// EXTR instruction extracts a contiguous chunk of bits from two existing
9499/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009500/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9501/// with an EXTR. Can't quite be done in TableGen because the two immediates
9502/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009503static SDValue tryCombineToEXTR(SDNode *N,
9504 TargetLowering::DAGCombinerInfo &DCI) {
9505 SelectionDAG &DAG = DCI.DAG;
9506 SDLoc DL(N);
9507 EVT VT = N->getValueType(0);
9508
9509 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9510
9511 if (VT != MVT::i32 && VT != MVT::i64)
9512 return SDValue();
9513
9514 SDValue LHS;
9515 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009516 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009517 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9518 return SDValue();
9519
9520 SDValue RHS;
9521 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009522 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009523 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9524 return SDValue();
9525
9526 // If they're both trying to come from the high part of the register, they're
9527 // not really an EXTR.
9528 if (LHSFromHi == RHSFromHi)
9529 return SDValue();
9530
9531 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9532 return SDValue();
9533
9534 if (LHSFromHi) {
9535 std::swap(LHS, RHS);
9536 std::swap(ShiftLHS, ShiftRHS);
9537 }
9538
9539 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009540 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009541}
9542
9543static SDValue tryCombineToBSL(SDNode *N,
9544 TargetLowering::DAGCombinerInfo &DCI) {
9545 EVT VT = N->getValueType(0);
9546 SelectionDAG &DAG = DCI.DAG;
9547 SDLoc DL(N);
9548
9549 if (!VT.isVector())
9550 return SDValue();
9551
9552 SDValue N0 = N->getOperand(0);
9553 if (N0.getOpcode() != ISD::AND)
9554 return SDValue();
9555
9556 SDValue N1 = N->getOperand(1);
9557 if (N1.getOpcode() != ISD::AND)
9558 return SDValue();
9559
9560 // We only have to look for constant vectors here since the general, variable
9561 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009562 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009563 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9564 for (int i = 1; i >= 0; --i)
9565 for (int j = 1; j >= 0; --j) {
9566 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9567 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9568 if (!BVN0 || !BVN1)
9569 continue;
9570
9571 bool FoundMatch = true;
9572 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9573 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9574 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9575 if (!CN0 || !CN1 ||
9576 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9577 FoundMatch = false;
9578 break;
9579 }
9580 }
9581
9582 if (FoundMatch)
9583 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9584 N0->getOperand(1 - i), N1->getOperand(1 - j));
9585 }
9586
9587 return SDValue();
9588}
9589
9590static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9591 const AArch64Subtarget *Subtarget) {
9592 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009593 SelectionDAG &DAG = DCI.DAG;
9594 EVT VT = N->getValueType(0);
9595
9596 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9597 return SDValue();
9598
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009599 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009600 return Res;
9601
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009602 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009603 return Res;
9604
9605 return SDValue();
9606}
9607
Nikita Popov1a261442019-03-15 21:04:34 +00009608static SDValue performANDCombine(SDNode *N,
9609 TargetLowering::DAGCombinerInfo &DCI) {
9610 SelectionDAG &DAG = DCI.DAG;
9611 SDValue LHS = N->getOperand(0);
9612 EVT VT = N->getValueType(0);
9613 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9614 return SDValue();
9615
9616 BuildVectorSDNode *BVN =
9617 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9618 if (!BVN)
9619 return SDValue();
9620
9621 // AND does not accept an immediate, so check if we can use a BIC immediate
9622 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9623 // pattern in isel, because some immediates may be lowered to the preferred
9624 // (and x, (movi imm)) form, even though an mvni representation also exists.
9625 APInt DefBits(VT.getSizeInBits(), 0);
9626 APInt UndefBits(VT.getSizeInBits(), 0);
9627 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9628 SDValue NewOp;
9629
9630 DefBits = ~DefBits;
9631 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9632 DefBits, &LHS)) ||
9633 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9634 DefBits, &LHS)))
9635 return NewOp;
9636
9637 UndefBits = ~UndefBits;
9638 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9639 UndefBits, &LHS)) ||
9640 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9641 UndefBits, &LHS)))
9642 return NewOp;
9643 }
9644
9645 return SDValue();
9646}
9647
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009648static SDValue performSRLCombine(SDNode *N,
9649 TargetLowering::DAGCombinerInfo &DCI) {
9650 SelectionDAG &DAG = DCI.DAG;
9651 EVT VT = N->getValueType(0);
9652 if (VT != MVT::i32 && VT != MVT::i64)
9653 return SDValue();
9654
9655 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9656 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9657 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9658 SDValue N0 = N->getOperand(0);
9659 if (N0.getOpcode() == ISD::BSWAP) {
9660 SDLoc DL(N);
9661 SDValue N1 = N->getOperand(1);
9662 SDValue N00 = N0.getOperand(0);
9663 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9664 uint64_t ShiftAmt = C->getZExtValue();
9665 if (VT == MVT::i32 && ShiftAmt == 16 &&
9666 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9667 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9668 if (VT == MVT::i64 && ShiftAmt == 32 &&
9669 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9670 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9671 }
9672 }
9673 return SDValue();
9674}
9675
Tim Northover3b0846e2014-05-24 12:50:23 +00009676static SDValue performBitcastCombine(SDNode *N,
9677 TargetLowering::DAGCombinerInfo &DCI,
9678 SelectionDAG &DAG) {
9679 // Wait 'til after everything is legalized to try this. That way we have
9680 // legal vector types and such.
9681 if (DCI.isBeforeLegalizeOps())
9682 return SDValue();
9683
9684 // Remove extraneous bitcasts around an extract_subvector.
9685 // For example,
9686 // (v4i16 (bitconvert
9687 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9688 // becomes
9689 // (extract_subvector ((v8i16 ...), (i64 4)))
9690
9691 // Only interested in 64-bit vectors as the ultimate result.
9692 EVT VT = N->getValueType(0);
9693 if (!VT.isVector())
9694 return SDValue();
9695 if (VT.getSimpleVT().getSizeInBits() != 64)
9696 return SDValue();
9697 // Is the operand an extract_subvector starting at the beginning or halfway
9698 // point of the vector? A low half may also come through as an
9699 // EXTRACT_SUBREG, so look for that, too.
9700 SDValue Op0 = N->getOperand(0);
9701 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9702 !(Op0->isMachineOpcode() &&
9703 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9704 return SDValue();
9705 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9706 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9707 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9708 return SDValue();
9709 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9710 if (idx != AArch64::dsub)
9711 return SDValue();
9712 // The dsub reference is equivalent to a lane zero subvector reference.
9713 idx = 0;
9714 }
9715 // Look through the bitcast of the input to the extract.
9716 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9717 return SDValue();
9718 SDValue Source = Op0->getOperand(0)->getOperand(0);
9719 // If the source type has twice the number of elements as our destination
9720 // type, we know this is an extract of the high or low half of the vector.
9721 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009722 if (!SVT.isVector() ||
9723 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009724 return SDValue();
9725
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009726 LLVM_DEBUG(
9727 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009728
9729 // Create the simplified form to just extract the low or high half of the
9730 // vector directly rather than bothering with the bitcasts.
9731 SDLoc dl(N);
9732 unsigned NumElements = VT.getVectorNumElements();
9733 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009734 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009735 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9736 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009737 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009738 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9739 Source, SubReg),
9740 0);
9741 }
9742}
9743
9744static SDValue performConcatVectorsCombine(SDNode *N,
9745 TargetLowering::DAGCombinerInfo &DCI,
9746 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009747 SDLoc dl(N);
9748 EVT VT = N->getValueType(0);
9749 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9750
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009751 // Optimize concat_vectors of truncated vectors, where the intermediate
9752 // type is illegal, to avoid said illegality, e.g.,
9753 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9754 // (v2i16 (truncate (v2i64)))))
9755 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009756 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9757 // (v4i32 (bitcast (v2i64))),
9758 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009759 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9760 // on both input and result type, so we might generate worse code.
9761 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9762 if (N->getNumOperands() == 2 &&
9763 N0->getOpcode() == ISD::TRUNCATE &&
9764 N1->getOpcode() == ISD::TRUNCATE) {
9765 SDValue N00 = N0->getOperand(0);
9766 SDValue N10 = N1->getOperand(0);
9767 EVT N00VT = N00.getValueType();
9768
9769 if (N00VT == N10.getValueType() &&
9770 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9771 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009772 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9773 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9774 for (size_t i = 0; i < Mask.size(); ++i)
9775 Mask[i] = i * 2;
9776 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9777 DAG.getVectorShuffle(
9778 MidVT, dl,
9779 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9780 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009781 }
9782 }
9783
Tim Northover3b0846e2014-05-24 12:50:23 +00009784 // Wait 'til after everything is legalized to try this. That way we have
9785 // legal vector types and such.
9786 if (DCI.isBeforeLegalizeOps())
9787 return SDValue();
9788
Tim Northover3b0846e2014-05-24 12:50:23 +00009789 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9790 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9791 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009792 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009793 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009794 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009795 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009796 }
9797
9798 // Canonicalise concat_vectors so that the right-hand vector has as few
9799 // bit-casts as possible before its real operation. The primary matching
9800 // destination for these operations will be the narrowing "2" instructions,
9801 // which depend on the operation being performed on this right-hand vector.
9802 // For example,
9803 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9804 // becomes
9805 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9806
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009807 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009808 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009809 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009810 MVT RHSTy = RHS.getValueType().getSimpleVT();
9811 // If the RHS is not a vector, this is not the pattern we're looking for.
9812 if (!RHSTy.isVector())
9813 return SDValue();
9814
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009815 LLVM_DEBUG(
9816 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009817
9818 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9819 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009820 return DAG.getNode(ISD::BITCAST, dl, VT,
9821 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9822 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9823 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009824}
9825
9826static SDValue tryCombineFixedPointConvert(SDNode *N,
9827 TargetLowering::DAGCombinerInfo &DCI,
9828 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009829 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009830 // legal vector types and such.
9831 if (DCI.isBeforeLegalizeOps())
9832 return SDValue();
9833 // Transform a scalar conversion of a value from a lane extract into a
9834 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9835 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9836 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9837 //
9838 // The second form interacts better with instruction selection and the
9839 // register allocator to avoid cross-class register copies that aren't
9840 // coalescable due to a lane reference.
9841
9842 // Check the operand and see if it originates from a lane extract.
9843 SDValue Op1 = N->getOperand(1);
9844 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9845 // Yep, no additional predication needed. Perform the transform.
9846 SDValue IID = N->getOperand(0);
9847 SDValue Shift = N->getOperand(2);
9848 SDValue Vec = Op1.getOperand(0);
9849 SDValue Lane = Op1.getOperand(1);
9850 EVT ResTy = N->getValueType(0);
9851 EVT VecResTy;
9852 SDLoc DL(N);
9853
9854 // The vector width should be 128 bits by the time we get here, even
9855 // if it started as 64 bits (the extract_vector handling will have
9856 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009857 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009858 "unexpected vector size on extract_vector_elt!");
9859 if (Vec.getValueType() == MVT::v4i32)
9860 VecResTy = MVT::v4f32;
9861 else if (Vec.getValueType() == MVT::v2i64)
9862 VecResTy = MVT::v2f64;
9863 else
Craig Topper2a30d782014-06-18 05:05:13 +00009864 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009865
9866 SDValue Convert =
9867 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9868 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9869 }
9870 return SDValue();
9871}
9872
9873// AArch64 high-vector "long" operations are formed by performing the non-high
9874// version on an extract_subvector of each operand which gets the high half:
9875//
9876// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9877//
9878// However, there are cases which don't have an extract_high explicitly, but
9879// have another operation that can be made compatible with one for free. For
9880// example:
9881//
9882// (dupv64 scalar) --> (extract_high (dup128 scalar))
9883//
9884// This routine does the actual conversion of such DUPs, once outer routines
9885// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009886// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9887// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009888static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009889 switch (N.getOpcode()) {
9890 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009891 case AArch64ISD::DUPLANE8:
9892 case AArch64ISD::DUPLANE16:
9893 case AArch64ISD::DUPLANE32:
9894 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009895 case AArch64ISD::MOVI:
9896 case AArch64ISD::MOVIshift:
9897 case AArch64ISD::MOVIedit:
9898 case AArch64ISD::MOVImsl:
9899 case AArch64ISD::MVNIshift:
9900 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009901 break;
9902 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009903 // FMOV could be supported, but isn't very useful, as it would only occur
9904 // if you passed a bitcast' floating point immediate to an eligible long
9905 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009906 return SDValue();
9907 }
9908
9909 MVT NarrowTy = N.getSimpleValueType();
9910 if (!NarrowTy.is64BitVector())
9911 return SDValue();
9912
9913 MVT ElementTy = NarrowTy.getVectorElementType();
9914 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009915 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009916
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009917 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009918 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9919 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009920 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009921}
9922
Eli Friedman29c06092019-02-08 00:23:35 +00009923static bool isEssentiallyExtractHighSubvector(SDValue N) {
9924 if (N.getOpcode() == ISD::BITCAST)
9925 N = N.getOperand(0);
9926 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9927 return false;
9928 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9929 N.getOperand(0).getValueType().getVectorNumElements() / 2;
Tim Northover3b0846e2014-05-24 12:50:23 +00009930}
9931
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009932/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009933struct GenericSetCCInfo {
9934 const SDValue *Opnd0;
9935 const SDValue *Opnd1;
9936 ISD::CondCode CC;
9937};
9938
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009939/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009940struct AArch64SetCCInfo {
9941 const SDValue *Cmp;
9942 AArch64CC::CondCode CC;
9943};
9944
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009945/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009946union SetCCInfo {
9947 GenericSetCCInfo Generic;
9948 AArch64SetCCInfo AArch64;
9949};
9950
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009951/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009952/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9953/// GenericSetCCInfo.
9954struct SetCCInfoAndKind {
9955 SetCCInfo Info;
9956 bool IsAArch64;
9957};
9958
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009959/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009960/// an
9961/// AArch64 lowered one.
9962/// \p SetCCInfo is filled accordingly.
9963/// \post SetCCInfo is meanginfull only when this function returns true.
9964/// \return True when Op is a kind of SET_CC operation.
9965static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9966 // If this is a setcc, this is straight forward.
9967 if (Op.getOpcode() == ISD::SETCC) {
9968 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9969 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9970 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9971 SetCCInfo.IsAArch64 = false;
9972 return true;
9973 }
9974 // Otherwise, check if this is a matching csel instruction.
9975 // In other words:
9976 // - csel 1, 0, cc
9977 // - csel 0, 1, !cc
9978 if (Op.getOpcode() != AArch64ISD::CSEL)
9979 return false;
9980 // Set the information about the operands.
9981 // TODO: we want the operands of the Cmp not the csel
9982 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9983 SetCCInfo.IsAArch64 = true;
9984 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9985 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9986
9987 // Check that the operands matches the constraints:
9988 // (1) Both operands must be constants.
9989 // (2) One must be 1 and the other must be 0.
9990 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9991 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9992
9993 // Check (1).
9994 if (!TValue || !FValue)
9995 return false;
9996
9997 // Check (2).
9998 if (!TValue->isOne()) {
9999 // Update the comparison when we are interested in !cc.
10000 std::swap(TValue, FValue);
10001 SetCCInfo.Info.AArch64.CC =
10002 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10003 }
10004 return TValue->isOne() && FValue->isNullValue();
10005}
10006
10007// Returns true if Op is setcc or zext of setcc.
10008static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10009 if (isSetCC(Op, Info))
10010 return true;
10011 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10012 isSetCC(Op->getOperand(0), Info));
10013}
10014
10015// The folding we want to perform is:
10016// (add x, [zext] (setcc cc ...) )
10017// -->
10018// (csel x, (add x, 1), !cc ...)
10019//
10020// The latter will get matched to a CSINC instruction.
10021static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10022 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10023 SDValue LHS = Op->getOperand(0);
10024 SDValue RHS = Op->getOperand(1);
10025 SetCCInfoAndKind InfoAndKind;
10026
10027 // If neither operand is a SET_CC, give up.
10028 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10029 std::swap(LHS, RHS);
10030 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10031 return SDValue();
10032 }
10033
10034 // FIXME: This could be generatized to work for FP comparisons.
10035 EVT CmpVT = InfoAndKind.IsAArch64
10036 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10037 : InfoAndKind.Info.Generic.Opnd0->getValueType();
10038 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10039 return SDValue();
10040
10041 SDValue CCVal;
10042 SDValue Cmp;
10043 SDLoc dl(Op);
10044 if (InfoAndKind.IsAArch64) {
10045 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010046 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10047 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +000010048 Cmp = *InfoAndKind.Info.AArch64.Cmp;
10049 } else
10050 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
10051 *InfoAndKind.Info.Generic.Opnd1,
10052 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
10053 CCVal, DAG, dl);
10054
10055 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010056 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +000010057 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10058}
10059
10060// The basic add/sub long vector instructions have variants with "2" on the end
10061// which act on the high-half of their inputs. They are normally matched by
10062// patterns like:
10063//
10064// (add (zeroext (extract_high LHS)),
10065// (zeroext (extract_high RHS)))
10066// -> uaddl2 vD, vN, vM
10067//
10068// However, if one of the extracts is something like a duplicate, this
10069// instruction can still be used profitably. This function puts the DAG into a
10070// more appropriate form for those patterns to trigger.
10071static SDValue performAddSubLongCombine(SDNode *N,
10072 TargetLowering::DAGCombinerInfo &DCI,
10073 SelectionDAG &DAG) {
10074 if (DCI.isBeforeLegalizeOps())
10075 return SDValue();
10076
10077 MVT VT = N->getSimpleValueType(0);
10078 if (!VT.is128BitVector()) {
10079 if (N->getOpcode() == ISD::ADD)
10080 return performSetccAddFolding(N, DAG);
10081 return SDValue();
10082 }
10083
10084 // Make sure both branches are extended in the same way.
10085 SDValue LHS = N->getOperand(0);
10086 SDValue RHS = N->getOperand(1);
10087 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10088 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10089 LHS.getOpcode() != RHS.getOpcode())
10090 return SDValue();
10091
10092 unsigned ExtType = LHS.getOpcode();
10093
10094 // It's not worth doing if at least one of the inputs isn't already an
10095 // extract, but we don't know which it'll be so we have to try both.
Eli Friedman29c06092019-02-08 00:23:35 +000010096 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010097 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10098 if (!RHS.getNode())
10099 return SDValue();
10100
10101 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
Eli Friedman29c06092019-02-08 00:23:35 +000010102 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010103 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10104 if (!LHS.getNode())
10105 return SDValue();
10106
10107 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10108 }
10109
10110 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10111}
10112
10113// Massage DAGs which we can use the high-half "long" operations on into
10114// something isel will recognize better. E.g.
10115//
10116// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10117// (aarch64_neon_umull (extract_high (v2i64 vec)))
10118// (extract_high (v2i64 (dup128 scalar)))))
10119//
Hal Finkelcd8664c2015-12-11 23:11:52 +000010120static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +000010121 TargetLowering::DAGCombinerInfo &DCI,
10122 SelectionDAG &DAG) {
10123 if (DCI.isBeforeLegalizeOps())
10124 return SDValue();
10125
Hal Finkelcd8664c2015-12-11 23:11:52 +000010126 SDValue LHS = N->getOperand(1);
10127 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +000010128 assert(LHS.getValueType().is64BitVector() &&
10129 RHS.getValueType().is64BitVector() &&
10130 "unexpected shape for long operation");
10131
10132 // Either node could be a DUP, but it's not worth doing both of them (you'd
10133 // just as well use the non-high version) so look for a corresponding extract
10134 // operation on the other "wing".
Eli Friedman29c06092019-02-08 00:23:35 +000010135 if (isEssentiallyExtractHighSubvector(LHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010136 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10137 if (!RHS.getNode())
10138 return SDValue();
Eli Friedman29c06092019-02-08 00:23:35 +000010139 } else if (isEssentiallyExtractHighSubvector(RHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010140 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10141 if (!LHS.getNode())
10142 return SDValue();
10143 }
10144
Hal Finkelcd8664c2015-12-11 23:11:52 +000010145 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10146 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +000010147}
10148
10149static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10150 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10151 unsigned ElemBits = ElemTy.getSizeInBits();
10152
10153 int64_t ShiftAmount;
10154 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10155 APInt SplatValue, SplatUndef;
10156 unsigned SplatBitSize;
10157 bool HasAnyUndefs;
10158 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10159 HasAnyUndefs, ElemBits) ||
10160 SplatBitSize != ElemBits)
10161 return SDValue();
10162
10163 ShiftAmount = SplatValue.getSExtValue();
10164 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10165 ShiftAmount = CVN->getSExtValue();
10166 } else
10167 return SDValue();
10168
10169 unsigned Opcode;
10170 bool IsRightShift;
10171 switch (IID) {
10172 default:
10173 llvm_unreachable("Unknown shift intrinsic");
10174 case Intrinsic::aarch64_neon_sqshl:
10175 Opcode = AArch64ISD::SQSHL_I;
10176 IsRightShift = false;
10177 break;
10178 case Intrinsic::aarch64_neon_uqshl:
10179 Opcode = AArch64ISD::UQSHL_I;
10180 IsRightShift = false;
10181 break;
10182 case Intrinsic::aarch64_neon_srshl:
10183 Opcode = AArch64ISD::SRSHR_I;
10184 IsRightShift = true;
10185 break;
10186 case Intrinsic::aarch64_neon_urshl:
10187 Opcode = AArch64ISD::URSHR_I;
10188 IsRightShift = true;
10189 break;
10190 case Intrinsic::aarch64_neon_sqshlu:
10191 Opcode = AArch64ISD::SQSHLU_I;
10192 IsRightShift = false;
10193 break;
10194 }
10195
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010196 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10197 SDLoc dl(N);
10198 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10199 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10200 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10201 SDLoc dl(N);
10202 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10203 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10204 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010205
10206 return SDValue();
10207}
10208
10209// The CRC32[BH] instructions ignore the high bits of their data operand. Since
10210// the intrinsics must be legal and take an i32, this means there's almost
10211// certainly going to be a zext in the DAG which we can eliminate.
10212static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10213 SDValue AndN = N->getOperand(2);
10214 if (AndN.getOpcode() != ISD::AND)
10215 return SDValue();
10216
10217 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10218 if (!CMask || CMask->getZExtValue() != Mask)
10219 return SDValue();
10220
10221 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10222 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10223}
10224
Ahmed Bougachafab58922015-03-10 20:45:38 +000010225static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10226 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010227 SDLoc dl(N);
10228 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10229 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +000010230 N->getOperand(1).getSimpleValueType(),
10231 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010232 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +000010233}
10234
Tim Northover3b0846e2014-05-24 12:50:23 +000010235static SDValue performIntrinsicCombine(SDNode *N,
10236 TargetLowering::DAGCombinerInfo &DCI,
10237 const AArch64Subtarget *Subtarget) {
10238 SelectionDAG &DAG = DCI.DAG;
10239 unsigned IID = getIntrinsicID(N);
10240 switch (IID) {
10241 default:
10242 break;
10243 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10244 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10245 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +000010246 case Intrinsic::aarch64_neon_saddv:
10247 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10248 case Intrinsic::aarch64_neon_uaddv:
10249 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10250 case Intrinsic::aarch64_neon_sminv:
10251 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10252 case Intrinsic::aarch64_neon_uminv:
10253 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10254 case Intrinsic::aarch64_neon_smaxv:
10255 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10256 case Intrinsic::aarch64_neon_umaxv:
10257 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010258 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +000010259 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010260 N->getOperand(1), N->getOperand(2));
10261 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +000010262 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010263 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +000010264 case Intrinsic::aarch64_neon_fmaxnm:
10265 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10266 N->getOperand(1), N->getOperand(2));
10267 case Intrinsic::aarch64_neon_fminnm:
10268 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10269 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010270 case Intrinsic::aarch64_neon_smull:
10271 case Intrinsic::aarch64_neon_umull:
10272 case Intrinsic::aarch64_neon_pmull:
10273 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +000010274 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010275 case Intrinsic::aarch64_neon_sqshl:
10276 case Intrinsic::aarch64_neon_uqshl:
10277 case Intrinsic::aarch64_neon_sqshlu:
10278 case Intrinsic::aarch64_neon_srshl:
10279 case Intrinsic::aarch64_neon_urshl:
10280 return tryCombineShiftImm(IID, N, DAG);
10281 case Intrinsic::aarch64_crc32b:
10282 case Intrinsic::aarch64_crc32cb:
10283 return tryCombineCRC32(0xff, N, DAG);
10284 case Intrinsic::aarch64_crc32h:
10285 case Intrinsic::aarch64_crc32ch:
10286 return tryCombineCRC32(0xffff, N, DAG);
10287 }
10288 return SDValue();
10289}
10290
10291static SDValue performExtendCombine(SDNode *N,
10292 TargetLowering::DAGCombinerInfo &DCI,
10293 SelectionDAG &DAG) {
10294 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10295 // we can convert that DUP into another extract_high (of a bigger DUP), which
10296 // helps the backend to decide that an sabdl2 would be useful, saving a real
10297 // extract_high operation.
10298 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +000010299 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010300 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010301 unsigned IID = getIntrinsicID(ABDNode);
10302 if (IID == Intrinsic::aarch64_neon_sabd ||
10303 IID == Intrinsic::aarch64_neon_uabd) {
10304 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10305 if (!NewABD.getNode())
10306 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010307
Hal Finkelcd8664c2015-12-11 23:11:52 +000010308 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10309 NewABD);
10310 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010311 }
10312
10313 // This is effectively a custom type legalization for AArch64.
10314 //
10315 // Type legalization will split an extend of a small, legal, type to a larger
10316 // illegal type by first splitting the destination type, often creating
10317 // illegal source types, which then get legalized in isel-confusing ways,
10318 // leading to really terrible codegen. E.g.,
10319 // %result = v8i32 sext v8i8 %value
10320 // becomes
10321 // %losrc = extract_subreg %value, ...
10322 // %hisrc = extract_subreg %value, ...
10323 // %lo = v4i32 sext v4i8 %losrc
10324 // %hi = v4i32 sext v4i8 %hisrc
10325 // Things go rapidly downhill from there.
10326 //
10327 // For AArch64, the [sz]ext vector instructions can only go up one element
10328 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10329 // take two instructions.
10330 //
10331 // This implies that the most efficient way to do the extend from v8i8
10332 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10333 // the normal splitting to happen for the v8i16->v8i32.
10334
10335 // This is pre-legalization to catch some cases where the default
10336 // type legalization will create ill-tempered code.
10337 if (!DCI.isBeforeLegalizeOps())
10338 return SDValue();
10339
10340 // We're only interested in cleaning things up for non-legal vector types
10341 // here. If both the source and destination are legal, things will just
10342 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010344 EVT ResVT = N->getValueType(0);
10345 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10346 return SDValue();
10347 // If the vector type isn't a simple VT, it's beyond the scope of what
10348 // we're worried about here. Let legalization do its thing and hope for
10349 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010350 SDValue Src = N->getOperand(0);
10351 EVT SrcVT = Src->getValueType(0);
10352 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010353 return SDValue();
10354
Tim Northover3b0846e2014-05-24 12:50:23 +000010355 // If the source VT is a 64-bit vector, we can play games and get the
10356 // better results we want.
10357 if (SrcVT.getSizeInBits() != 64)
10358 return SDValue();
10359
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010360 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010361 unsigned ElementCount = SrcVT.getVectorNumElements();
10362 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10363 SDLoc DL(N);
10364 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10365
10366 // Now split the rest of the operation into two halves, each with a 64
10367 // bit source.
10368 EVT LoVT, HiVT;
10369 SDValue Lo, Hi;
10370 unsigned NumElements = ResVT.getVectorNumElements();
10371 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10372 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10373 ResVT.getVectorElementType(), NumElements / 2);
10374
10375 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10376 LoVT.getVectorNumElements());
10377 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010378 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010379 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010380 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010381 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10382 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10383
10384 // Now combine the parts back together so we still have a single result
10385 // like the combiner expects.
10386 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10387}
10388
Geoff Berry8301c642016-11-16 19:35:19 +000010389static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10390 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010391 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010392 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010393 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010394
10395 // Create scalar stores. This is at least as good as the code sequence for a
10396 // split unaligned store which is a dup.s, ext.b, and two stores.
10397 // Most of the time the three stores should be replaced by store pair
10398 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010399 SDLoc DL(&St);
10400 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010401 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010402
John Brawn3a9c8422017-02-06 18:07:20 +000010403 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010404 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010405 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010406 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010407
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010408 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010409 if (BasePtr->getOpcode() == ISD::ADD &&
10410 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10411 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10412 BasePtr = BasePtr->getOperand(0);
10413 }
10414
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010415 unsigned Offset = EltOffset;
10416 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010417 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010418 SDValue OffsetPtr =
10419 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10420 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010421 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010422 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010423 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010424 Offset += EltOffset;
10425 }
10426 return NewST1;
10427}
10428
Geoff Berry526c5052016-11-14 19:39:04 +000010429/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10430/// load store optimizer pass will merge them to store pair stores. This should
10431/// be better than a movi to create the vector zero followed by a vector store
10432/// if the zero constant is not re-used, since one instructions and one register
10433/// live range will be removed.
10434///
10435/// For example, the final generated code should be:
10436///
10437/// stp xzr, xzr, [x0]
10438///
10439/// instead of:
10440///
10441/// movi v0.2d, #0
10442/// str q0, [x0]
10443///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010444static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10445 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010446 EVT VT = StVal.getValueType();
10447
Geoff Berry8301c642016-11-16 19:35:19 +000010448 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10449 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010450 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010451 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10452 VT.getVectorElementType().getSizeInBits() == 64) ||
10453 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10454 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010455 return SDValue();
10456
10457 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10458 return SDValue();
10459
10460 // If the zero constant has more than one use then the vector store could be
10461 // better since the constant mov will be amortized and stp q instructions
10462 // should be able to be formed.
10463 if (!StVal.hasOneUse())
10464 return SDValue();
10465
Tim Northover964eea72019-01-08 13:30:27 +000010466 // If the store is truncating then it's going down to i16 or smaller, which
10467 // means it can be implemented in a single store anyway.
10468 if (St.isTruncatingStore())
10469 return SDValue();
10470
Geoff Berry526c5052016-11-14 19:39:04 +000010471 // If the immediate offset of the address operand is too large for the stp
10472 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010473 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10474 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010475 if (Offset < -512 || Offset > 504)
10476 return SDValue();
10477 }
10478
10479 for (int I = 0; I < NumVecElts; ++I) {
10480 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010481 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010482 return SDValue();
10483 }
Geoff Berry8301c642016-11-16 19:35:19 +000010484
Geoff Berrybb23df92017-09-21 21:10:06 +000010485 // Use a CopyFromReg WZR/XZR here to prevent
10486 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10487 SDLoc DL(&St);
10488 unsigned ZeroReg;
10489 EVT ZeroVT;
10490 if (VT.getVectorElementType().getSizeInBits() == 32) {
10491 ZeroReg = AArch64::WZR;
10492 ZeroVT = MVT::i32;
10493 } else {
10494 ZeroReg = AArch64::XZR;
10495 ZeroVT = MVT::i64;
10496 }
10497 SDValue SplatVal =
10498 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010499 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010500}
10501
Tim Northover3b0846e2014-05-24 12:50:23 +000010502/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10503/// value. The load store optimizer pass will merge them to store pair stores.
10504/// This has better performance than a splat of the scalar followed by a split
10505/// vector store. Even if the stores are not merged it is four stores vs a dup,
10506/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010507static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10508 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010509 EVT VT = StVal.getValueType();
10510
10511 // Don't replace floating point stores, they possibly won't be transformed to
10512 // stp because of the store pair suppress pass.
10513 if (VT.isFloatingPoint())
10514 return SDValue();
10515
Tim Northover3b0846e2014-05-24 12:50:23 +000010516 // We can express a splat as store pair(s) for 2 or 4 elements.
10517 unsigned NumVecElts = VT.getVectorNumElements();
10518 if (NumVecElts != 4 && NumVecElts != 2)
10519 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010520
Tim Northover964eea72019-01-08 13:30:27 +000010521 // If the store is truncating then it's going down to i16 or smaller, which
10522 // means it can be implemented in a single store anyway.
10523 if (St.isTruncatingStore())
10524 return SDValue();
10525
Tim Northover3b0846e2014-05-24 12:50:23 +000010526 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010527 // Make sure that each of the relevant vector element locations are inserted
10528 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10529 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10530 SDValue SplatVal;
10531 for (unsigned I = 0; I < NumVecElts; ++I) {
10532 // Check for insert vector elements.
10533 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010534 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010535
10536 // Check that same value is inserted at each vector element.
10537 if (I == 0)
10538 SplatVal = StVal.getOperand(1);
10539 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010540 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010541
10542 // Check insert element index.
10543 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10544 if (!CIndex)
10545 return SDValue();
10546 uint64_t IndexVal = CIndex->getZExtValue();
10547 if (IndexVal >= NumVecElts)
10548 return SDValue();
10549 IndexNotInserted.reset(IndexVal);
10550
10551 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010552 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010553 // Check that all vector element locations were inserted to.
10554 if (IndexNotInserted.any())
10555 return SDValue();
10556
Geoff Berry8301c642016-11-16 19:35:19 +000010557 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010558}
10559
Geoff Berry8301c642016-11-16 19:35:19 +000010560static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10561 SelectionDAG &DAG,
10562 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010563
10564 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010565 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010566 return SDValue();
10567
Geoff Berry526c5052016-11-14 19:39:04 +000010568 SDValue StVal = S->getValue();
10569 EVT VT = StVal.getValueType();
10570 if (!VT.isVector())
10571 return SDValue();
10572
10573 // If we get a splat of zeros, convert this vector store to a store of
10574 // scalars. They will be merged into store pairs of xzr thereby removing one
10575 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010576 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010577 return ReplacedZeroSplat;
10578
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010579 // FIXME: The logic for deciding if an unaligned store should be split should
10580 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10581 // a call to that function here.
10582
Matthias Braun651cff42016-06-02 18:03:53 +000010583 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010584 return SDValue();
10585
Sanjay Patel924879a2015-08-04 15:49:57 +000010586 // Don't split at -Oz.
Evandro Menezes85bd3972019-04-04 22:40:06 +000010587 if (DAG.getMachineFunction().getFunction().hasMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010588 return SDValue();
10589
Tim Northover3b0846e2014-05-24 12:50:23 +000010590 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10591 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010592 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010593 return SDValue();
10594
10595 // Split unaligned 16B stores. They are terrible for performance.
10596 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10597 // extensions can use this to mark that it does not want splitting to happen
10598 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10599 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10600 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10601 S->getAlignment() <= 2)
10602 return SDValue();
10603
10604 // If we get a splat of a scalar convert this vector store to a store of
10605 // scalars. They will be merged into store pairs thereby removing two
10606 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010607 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010608 return ReplacedSplat;
10609
10610 SDLoc DL(S);
10611 unsigned NumElts = VT.getVectorNumElements() / 2;
10612 // Split VT into two.
10613 EVT HalfVT =
10614 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10615 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010616 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010617 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010618 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010619 SDValue BasePtr = S->getBasePtr();
10620 SDValue NewST1 =
10621 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010622 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010623 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010624 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010625 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010626 S->getPointerInfo(), S->getAlignment(),
10627 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010628}
10629
10630/// Target-specific DAG combine function for post-increment LD1 (lane) and
10631/// post-increment LD1R.
10632static SDValue performPostLD1Combine(SDNode *N,
10633 TargetLowering::DAGCombinerInfo &DCI,
10634 bool IsLaneOp) {
10635 if (DCI.isBeforeLegalizeOps())
10636 return SDValue();
10637
10638 SelectionDAG &DAG = DCI.DAG;
10639 EVT VT = N->getValueType(0);
10640
10641 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10642 SDNode *LD = N->getOperand(LoadIdx).getNode();
10643 // If it is not LOAD, can not do such combine.
10644 if (LD->getOpcode() != ISD::LOAD)
10645 return SDValue();
10646
Geoff Berry60460262018-05-11 16:25:06 +000010647 // The vector lane must be a constant in the LD1LANE opcode.
10648 SDValue Lane;
10649 if (IsLaneOp) {
10650 Lane = N->getOperand(2);
10651 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10652 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10653 return SDValue();
10654 }
10655
Tim Northover3b0846e2014-05-24 12:50:23 +000010656 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10657 EVT MemVT = LoadSDN->getMemoryVT();
10658 // Check if memory operand is the same type as the vector element.
10659 if (MemVT != VT.getVectorElementType())
10660 return SDValue();
10661
10662 // Check if there are other uses. If so, do not combine as it will introduce
10663 // an extra load.
10664 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10665 ++UI) {
10666 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10667 continue;
10668 if (*UI != N)
10669 return SDValue();
10670 }
10671
10672 SDValue Addr = LD->getOperand(1);
10673 SDValue Vector = N->getOperand(0);
10674 // Search for a use of the address operand that is an increment.
10675 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10676 Addr.getNode()->use_end(); UI != UE; ++UI) {
10677 SDNode *User = *UI;
10678 if (User->getOpcode() != ISD::ADD
10679 || UI.getUse().getResNo() != Addr.getResNo())
10680 continue;
10681
Tim Northover3b0846e2014-05-24 12:50:23 +000010682 // If the increment is a constant, it must match the memory ref size.
10683 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10684 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10685 uint32_t IncVal = CInc->getZExtValue();
10686 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10687 if (IncVal != NumBytes)
10688 continue;
10689 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10690 }
10691
Nirav Davee40e2bb2018-09-25 15:30:22 +000010692 // To avoid cycle construction make sure that neither the load nor the add
10693 // are predecessors to each other or the Vector.
10694 SmallPtrSet<const SDNode *, 32> Visited;
10695 SmallVector<const SDNode *, 16> Worklist;
10696 Visited.insert(N);
10697 Worklist.push_back(User);
10698 Worklist.push_back(LD);
10699 Worklist.push_back(Vector.getNode());
10700 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10701 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010702 continue;
10703
Tim Northover3b0846e2014-05-24 12:50:23 +000010704 SmallVector<SDValue, 8> Ops;
10705 Ops.push_back(LD->getOperand(0)); // Chain
10706 if (IsLaneOp) {
10707 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010708 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010709 }
10710 Ops.push_back(Addr);
10711 Ops.push_back(Inc);
10712
10713 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010714 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010715 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10716 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10717 MemVT,
10718 LoadSDN->getMemOperand());
10719
10720 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010721 SDValue NewResults[] = {
10722 SDValue(LD, 0), // The result of load
10723 SDValue(UpdN.getNode(), 2) // Chain
10724 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010725 DCI.CombineTo(LD, NewResults);
10726 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10727 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10728
10729 break;
10730 }
10731 return SDValue();
10732}
10733
Joel Jones7466ccf2017-07-10 22:11:50 +000010734/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010735/// address translation.
10736static bool performTBISimplification(SDValue Addr,
10737 TargetLowering::DAGCombinerInfo &DCI,
10738 SelectionDAG &DAG) {
10739 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010740 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010741 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10742 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010743 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010744 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010745 DCI.CommitTargetLoweringOpt(TLO);
10746 return true;
10747 }
10748 return false;
10749}
10750
10751static SDValue performSTORECombine(SDNode *N,
10752 TargetLowering::DAGCombinerInfo &DCI,
10753 SelectionDAG &DAG,
10754 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010755 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010756 return Split;
10757
10758 if (Subtarget->supportsAddressTopByteIgnored() &&
10759 performTBISimplification(N->getOperand(2), DCI, DAG))
10760 return SDValue(N, 0);
10761
10762 return SDValue();
10763}
10764
Chad Rosier6c36eff2015-09-03 18:13:57 +000010765
Tim Northover3b0846e2014-05-24 12:50:23 +000010766/// Target-specific DAG combine function for NEON load/store intrinsics
10767/// to merge base address updates.
10768static SDValue performNEONPostLDSTCombine(SDNode *N,
10769 TargetLowering::DAGCombinerInfo &DCI,
10770 SelectionDAG &DAG) {
10771 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10772 return SDValue();
10773
10774 unsigned AddrOpIdx = N->getNumOperands() - 1;
10775 SDValue Addr = N->getOperand(AddrOpIdx);
10776
10777 // Search for a use of the address operand that is an increment.
10778 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10779 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10780 SDNode *User = *UI;
10781 if (User->getOpcode() != ISD::ADD ||
10782 UI.getUse().getResNo() != Addr.getResNo())
10783 continue;
10784
10785 // Check that the add is independent of the load/store. Otherwise, folding
10786 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010787 SmallPtrSet<const SDNode *, 32> Visited;
10788 SmallVector<const SDNode *, 16> Worklist;
10789 Visited.insert(Addr.getNode());
10790 Worklist.push_back(N);
10791 Worklist.push_back(User);
10792 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10793 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010794 continue;
10795
10796 // Find the new opcode for the updating load/store.
10797 bool IsStore = false;
10798 bool IsLaneOp = false;
10799 bool IsDupOp = false;
10800 unsigned NewOpc = 0;
10801 unsigned NumVecs = 0;
10802 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10803 switch (IntNo) {
10804 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10805 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10806 NumVecs = 2; break;
10807 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10808 NumVecs = 3; break;
10809 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10810 NumVecs = 4; break;
10811 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10812 NumVecs = 2; IsStore = true; break;
10813 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10814 NumVecs = 3; IsStore = true; break;
10815 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10816 NumVecs = 4; IsStore = true; break;
10817 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10818 NumVecs = 2; break;
10819 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10820 NumVecs = 3; break;
10821 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10822 NumVecs = 4; break;
10823 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10824 NumVecs = 2; IsStore = true; break;
10825 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10826 NumVecs = 3; IsStore = true; break;
10827 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10828 NumVecs = 4; IsStore = true; break;
10829 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10830 NumVecs = 2; IsDupOp = true; break;
10831 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10832 NumVecs = 3; IsDupOp = true; break;
10833 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10834 NumVecs = 4; IsDupOp = true; break;
10835 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10836 NumVecs = 2; IsLaneOp = true; break;
10837 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10838 NumVecs = 3; IsLaneOp = true; break;
10839 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10840 NumVecs = 4; IsLaneOp = true; break;
10841 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10842 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10843 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10844 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10845 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10846 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10847 }
10848
10849 EVT VecTy;
10850 if (IsStore)
10851 VecTy = N->getOperand(2).getValueType();
10852 else
10853 VecTy = N->getValueType(0);
10854
10855 // If the increment is a constant, it must match the memory ref size.
10856 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10857 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10858 uint32_t IncVal = CInc->getZExtValue();
10859 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10860 if (IsLaneOp || IsDupOp)
10861 NumBytes /= VecTy.getVectorNumElements();
10862 if (IncVal != NumBytes)
10863 continue;
10864 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10865 }
10866 SmallVector<SDValue, 8> Ops;
10867 Ops.push_back(N->getOperand(0)); // Incoming chain
10868 // Load lane and store have vector list as input.
10869 if (IsLaneOp || IsStore)
10870 for (unsigned i = 2; i < AddrOpIdx; ++i)
10871 Ops.push_back(N->getOperand(i));
10872 Ops.push_back(Addr); // Base register
10873 Ops.push_back(Inc);
10874
10875 // Return Types.
10876 EVT Tys[6];
10877 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10878 unsigned n;
10879 for (n = 0; n < NumResultVecs; ++n)
10880 Tys[n] = VecTy;
10881 Tys[n++] = MVT::i64; // Type of write back register
10882 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010883 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010884
10885 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10886 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10887 MemInt->getMemoryVT(),
10888 MemInt->getMemOperand());
10889
10890 // Update the uses.
10891 std::vector<SDValue> NewResults;
10892 for (unsigned i = 0; i < NumResultVecs; ++i) {
10893 NewResults.push_back(SDValue(UpdN.getNode(), i));
10894 }
10895 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10896 DCI.CombineTo(N, NewResults);
10897 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10898
10899 break;
10900 }
10901 return SDValue();
10902}
10903
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010904// Checks to see if the value is the prescribed width and returns information
10905// about its extension mode.
10906static
10907bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10908 ExtType = ISD::NON_EXTLOAD;
10909 switch(V.getNode()->getOpcode()) {
10910 default:
10911 return false;
10912 case ISD::LOAD: {
10913 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10914 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10915 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10916 ExtType = LoadNode->getExtensionType();
10917 return true;
10918 }
10919 return false;
10920 }
10921 case ISD::AssertSext: {
10922 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10923 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10924 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10925 ExtType = ISD::SEXTLOAD;
10926 return true;
10927 }
10928 return false;
10929 }
10930 case ISD::AssertZext: {
10931 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10932 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10933 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10934 ExtType = ISD::ZEXTLOAD;
10935 return true;
10936 }
10937 return false;
10938 }
10939 case ISD::Constant:
10940 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010941 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10942 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010943 }
10944 }
10945
10946 return true;
10947}
10948
10949// This function does a whole lot of voodoo to determine if the tests are
10950// equivalent without and with a mask. Essentially what happens is that given a
10951// DAG resembling:
10952//
10953// +-------------+ +-------------+ +-------------+ +-------------+
10954// | Input | | AddConstant | | CompConstant| | CC |
10955// +-------------+ +-------------+ +-------------+ +-------------+
10956// | | | |
10957// V V | +----------+
10958// +-------------+ +----+ | |
10959// | ADD | |0xff| | |
10960// +-------------+ +----+ | |
10961// | | | |
10962// V V | |
10963// +-------------+ | |
10964// | AND | | |
10965// +-------------+ | |
10966// | | |
10967// +-----+ | |
10968// | | |
10969// V V V
10970// +-------------+
10971// | CMP |
10972// +-------------+
10973//
10974// The AND node may be safely removed for some combinations of inputs. In
10975// particular we need to take into account the extension type of the Input,
10976// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10977// width of the input (this can work for any width inputs, the above graph is
10978// specific to 8 bits.
10979//
10980// The specific equations were worked out by generating output tables for each
10981// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10982// problem was simplified by working with 4 bit inputs, which means we only
10983// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10984// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10985// patterns present in both extensions (0,7). For every distinct set of
10986// AddConstant and CompConstants bit patterns we can consider the masked and
10987// unmasked versions to be equivalent if the result of this function is true for
10988// all 16 distinct bit patterns of for the current extension type of Input (w0).
10989//
10990// sub w8, w0, w1
10991// and w10, w8, #0x0f
10992// cmp w8, w2
10993// cset w9, AArch64CC
10994// cmp w10, w2
10995// cset w11, AArch64CC
10996// cmp w9, w11
10997// cset w0, eq
10998// ret
10999//
11000// Since the above function shows when the outputs are equivalent it defines
11001// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11002// would be expensive to run during compiles. The equations below were written
11003// in a test harness that confirmed they gave equivalent outputs to the above
11004// for all inputs function, so they can be used determine if the removal is
11005// legal instead.
11006//
11007// isEquivalentMaskless() is the code for testing if the AND can be removed
11008// factored out of the DAG recognition as the DAG can take several forms.
11009
David Majnemere61e4bf2016-06-21 05:10:24 +000011010static bool isEquivalentMaskless(unsigned CC, unsigned width,
11011 ISD::LoadExtType ExtType, int AddConstant,
11012 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011013 // By being careful about our equations and only writing the in term
11014 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11015 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000011016 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011017
11018 // For the purposes of these comparisons sign extending the type is
11019 // equivalent to zero extending the add and displacing it by half the integer
11020 // width. Provided we are careful and make sure our equations are valid over
11021 // the whole range we can just adjust the input and avoid writing equations
11022 // for sign extended inputs.
11023 if (ExtType == ISD::SEXTLOAD)
11024 AddConstant -= (1 << (width-1));
11025
11026 switch(CC) {
11027 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011028 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011029 if ((AddConstant == 0) ||
11030 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11031 (AddConstant >= 0 && CompConstant < 0) ||
11032 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11033 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011034 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011035 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011036 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011037 if ((AddConstant == 0) ||
11038 (AddConstant >= 0 && CompConstant <= 0) ||
11039 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11040 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011041 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011042 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011043 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011044 if ((AddConstant >= 0 && CompConstant < 0) ||
11045 (AddConstant <= 0 && CompConstant >= -1 &&
11046 CompConstant < AddConstant + MaxUInt))
11047 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011048 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011049 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011050 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011051 if ((AddConstant == 0) ||
11052 (AddConstant > 0 && CompConstant <= 0) ||
11053 (AddConstant < 0 && CompConstant <= AddConstant))
11054 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011055 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011056 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011057 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011058 if ((AddConstant >= 0 && CompConstant <= 0) ||
11059 (AddConstant <= 0 && CompConstant >= 0 &&
11060 CompConstant <= AddConstant + MaxUInt))
11061 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011062 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011063 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011064 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011065 if ((AddConstant > 0 && CompConstant < 0) ||
11066 (AddConstant < 0 && CompConstant >= 0 &&
11067 CompConstant < AddConstant + MaxUInt) ||
11068 (AddConstant >= 0 && CompConstant >= 0 &&
11069 CompConstant >= AddConstant) ||
11070 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011071 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011072 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011073 case AArch64CC::VS:
11074 case AArch64CC::VC:
11075 case AArch64CC::AL:
11076 case AArch64CC::NV:
11077 return true;
11078 case AArch64CC::Invalid:
11079 break;
11080 }
11081
11082 return false;
11083}
11084
11085static
11086SDValue performCONDCombine(SDNode *N,
11087 TargetLowering::DAGCombinerInfo &DCI,
11088 SelectionDAG &DAG, unsigned CCIndex,
11089 unsigned CmpIndex) {
11090 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11091 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11092 unsigned CondOpcode = SubsNode->getOpcode();
11093
11094 if (CondOpcode != AArch64ISD::SUBS)
11095 return SDValue();
11096
11097 // There is a SUBS feeding this condition. Is it fed by a mask we can
11098 // use?
11099
11100 SDNode *AndNode = SubsNode->getOperand(0).getNode();
11101 unsigned MaskBits = 0;
11102
11103 if (AndNode->getOpcode() != ISD::AND)
11104 return SDValue();
11105
11106 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11107 uint32_t CNV = CN->getZExtValue();
11108 if (CNV == 255)
11109 MaskBits = 8;
11110 else if (CNV == 65535)
11111 MaskBits = 16;
11112 }
11113
11114 if (!MaskBits)
11115 return SDValue();
11116
11117 SDValue AddValue = AndNode->getOperand(0);
11118
11119 if (AddValue.getOpcode() != ISD::ADD)
11120 return SDValue();
11121
11122 // The basic dag structure is correct, grab the inputs and validate them.
11123
11124 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11125 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11126 SDValue SubsInputValue = SubsNode->getOperand(1);
11127
11128 // The mask is present and the provenance of all the values is a smaller type,
11129 // lets see if the mask is superfluous.
11130
11131 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11132 !isa<ConstantSDNode>(SubsInputValue.getNode()))
11133 return SDValue();
11134
11135 ISD::LoadExtType ExtType;
11136
11137 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11138 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11139 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11140 return SDValue();
11141
11142 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11143 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11144 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11145 return SDValue();
11146
11147 // The AND is not necessary, remove it.
11148
11149 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11150 SubsNode->getValueType(1));
11151 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11152
11153 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11154 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11155
11156 return SDValue(N, 0);
11157}
11158
Tim Northover3b0846e2014-05-24 12:50:23 +000011159// Optimize compare with zero and branch.
11160static SDValue performBRCONDCombine(SDNode *N,
11161 TargetLowering::DAGCombinerInfo &DCI,
11162 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000011163 MachineFunction &MF = DAG.getMachineFunction();
11164 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11165 // will not be produced, as they are conditional branch instructions that do
11166 // not set flags.
11167 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11168 return SDValue();
11169
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000011170 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011171 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000011172 SDValue Chain = N->getOperand(0);
11173 SDValue Dest = N->getOperand(1);
11174 SDValue CCVal = N->getOperand(2);
11175 SDValue Cmp = N->getOperand(3);
11176
11177 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11178 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11179 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11180 return SDValue();
11181
11182 unsigned CmpOpc = Cmp.getOpcode();
11183 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11184 return SDValue();
11185
11186 // Only attempt folding if there is only one use of the flag and no use of the
11187 // value.
11188 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11189 return SDValue();
11190
11191 SDValue LHS = Cmp.getOperand(0);
11192 SDValue RHS = Cmp.getOperand(1);
11193
11194 assert(LHS.getValueType() == RHS.getValueType() &&
11195 "Expected the value type to be the same for both operands!");
11196 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11197 return SDValue();
11198
Artyom Skrobov314ee042015-11-25 19:41:11 +000011199 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011200 std::swap(LHS, RHS);
11201
Artyom Skrobov314ee042015-11-25 19:41:11 +000011202 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011203 return SDValue();
11204
11205 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11206 LHS.getOpcode() == ISD::SRL)
11207 return SDValue();
11208
11209 // Fold the compare into the branch instruction.
11210 SDValue BR;
11211 if (CC == AArch64CC::EQ)
11212 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11213 else
11214 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11215
11216 // Do not add new nodes to DAG combiner worklist.
11217 DCI.CombineTo(N, BR, false);
11218
11219 return SDValue();
11220}
11221
Geoff Berry9e934b02016-01-04 18:55:47 +000011222// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11223// as well as whether the test should be inverted. This code is required to
11224// catch these cases (as opposed to standard dag combines) because
11225// AArch64ISD::TBZ is matched during legalization.
11226static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11227 SelectionDAG &DAG) {
11228
11229 if (!Op->hasOneUse())
11230 return Op;
11231
11232 // We don't handle undef/constant-fold cases below, as they should have
11233 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11234 // etc.)
11235
11236 // (tbz (trunc x), b) -> (tbz x, b)
11237 // This case is just here to enable more of the below cases to be caught.
11238 if (Op->getOpcode() == ISD::TRUNCATE &&
11239 Bit < Op->getValueType(0).getSizeInBits()) {
11240 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11241 }
11242
Craig Topper35fe0792019-04-10 17:27:29 +000011243 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11244 if (Op->getOpcode() == ISD::ANY_EXTEND &&
11245 Bit < Op->getOperand(0).getValueSizeInBits()) {
11246 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11247 }
11248
Geoff Berry9e934b02016-01-04 18:55:47 +000011249 if (Op->getNumOperands() != 2)
11250 return Op;
11251
11252 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11253 if (!C)
11254 return Op;
11255
11256 switch (Op->getOpcode()) {
11257 default:
11258 return Op;
11259
11260 // (tbz (and x, m), b) -> (tbz x, b)
11261 case ISD::AND:
11262 if ((C->getZExtValue() >> Bit) & 1)
11263 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11264 return Op;
11265
11266 // (tbz (shl x, c), b) -> (tbz x, b-c)
11267 case ISD::SHL:
11268 if (C->getZExtValue() <= Bit &&
11269 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11270 Bit = Bit - C->getZExtValue();
11271 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11272 }
11273 return Op;
11274
11275 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11276 case ISD::SRA:
11277 Bit = Bit + C->getZExtValue();
11278 if (Bit >= Op->getValueType(0).getSizeInBits())
11279 Bit = Op->getValueType(0).getSizeInBits() - 1;
11280 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11281
11282 // (tbz (srl x, c), b) -> (tbz x, b+c)
11283 case ISD::SRL:
11284 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11285 Bit = Bit + C->getZExtValue();
11286 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11287 }
11288 return Op;
11289
11290 // (tbz (xor x, -1), b) -> (tbnz x, b)
11291 case ISD::XOR:
11292 if ((C->getZExtValue() >> Bit) & 1)
11293 Invert = !Invert;
11294 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11295 }
11296}
11297
11298// Optimize test single bit zero/non-zero and branch.
11299static SDValue performTBZCombine(SDNode *N,
11300 TargetLowering::DAGCombinerInfo &DCI,
11301 SelectionDAG &DAG) {
11302 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11303 bool Invert = false;
11304 SDValue TestSrc = N->getOperand(1);
11305 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11306
11307 if (TestSrc == NewTestSrc)
11308 return SDValue();
11309
11310 unsigned NewOpc = N->getOpcode();
11311 if (Invert) {
11312 if (NewOpc == AArch64ISD::TBZ)
11313 NewOpc = AArch64ISD::TBNZ;
11314 else {
11315 assert(NewOpc == AArch64ISD::TBNZ);
11316 NewOpc = AArch64ISD::TBZ;
11317 }
11318 }
11319
11320 SDLoc DL(N);
11321 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11322 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11323}
11324
Tim Northover3b0846e2014-05-24 12:50:23 +000011325// vselect (v1i1 setcc) ->
11326// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11327// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11328// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11329// such VSELECT.
11330static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11331 SDValue N0 = N->getOperand(0);
11332 EVT CCVT = N0.getValueType();
11333
11334 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11335 CCVT.getVectorElementType() != MVT::i1)
11336 return SDValue();
11337
11338 EVT ResVT = N->getValueType(0);
11339 EVT CmpVT = N0.getOperand(0).getValueType();
11340 // Only combine when the result type is of the same size as the compared
11341 // operands.
11342 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11343 return SDValue();
11344
11345 SDValue IfTrue = N->getOperand(1);
11346 SDValue IfFalse = N->getOperand(2);
11347 SDValue SetCC =
11348 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11349 N0.getOperand(0), N0.getOperand(1),
11350 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11351 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11352 IfTrue, IfFalse);
11353}
11354
11355/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11356/// the compare-mask instructions rather than going via NZCV, even if LHS and
11357/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11358/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011359static SDValue performSelectCombine(SDNode *N,
11360 TargetLowering::DAGCombinerInfo &DCI) {
11361 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011362 SDValue N0 = N->getOperand(0);
11363 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011364
Ahmed Bougachac004c602015-04-27 21:43:12 +000011365 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011366 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011367
Ahmed Bougachac004c602015-04-27 21:43:12 +000011368 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11369 // scalar SetCCResultType. We also don't expect vectors, because we assume
11370 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11371 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11372 "Scalar-SETCC feeding SELECT has unexpected result type!");
11373
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011374 // If NumMaskElts == 0, the comparison is larger than select result. The
11375 // largest real NEON comparison is 64-bits per lane, which means the result is
11376 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011377 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011378
11379 // Don't try to do this optimization when the setcc itself has i1 operands.
11380 // There are no legal vectors of i1, so this would be pointless.
11381 if (SrcVT == MVT::i1)
11382 return SDValue();
11383
Tim Northover3c0915e2014-08-29 15:34:58 +000011384 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011385 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011386 return SDValue();
11387
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011388 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011389 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11390
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011391 // Also bail out if the vector CCVT isn't the same size as ResVT.
11392 // This can happen if the SETCC operand size doesn't divide the ResVT size
11393 // (e.g., f64 vs v3f32).
11394 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11395 return SDValue();
11396
Ahmed Bougachac004c602015-04-27 21:43:12 +000011397 // Make sure we didn't create illegal types, if we're not supposed to.
11398 assert(DCI.isBeforeLegalize() ||
11399 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11400
Tim Northover3b0846e2014-05-24 12:50:23 +000011401 // First perform a vector comparison, where lane 0 is the one we're interested
11402 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011403 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011404 SDValue LHS =
11405 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11406 SDValue RHS =
11407 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11408 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11409
11410 // Now duplicate the comparison mask we want across all other lanes.
11411 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011412 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011413 Mask = DAG.getNode(ISD::BITCAST, DL,
11414 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011415
11416 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11417}
11418
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011419/// Get rid of unnecessary NVCASTs (that don't change the type).
11420static SDValue performNVCASTCombine(SDNode *N) {
11421 if (N->getValueType(0) == N->getOperand(0).getValueType())
11422 return N->getOperand(0);
11423
11424 return SDValue();
11425}
11426
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011427// If all users of the globaladdr are of the form (globaladdr + constant), find
11428// the smallest constant, fold it into the globaladdr's offset and rewrite the
11429// globaladdr as (globaladdr + constant) - constant.
11430static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11431 const AArch64Subtarget *Subtarget,
11432 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011433 auto *GN = cast<GlobalAddressSDNode>(N);
11434 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11435 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011436 return SDValue();
11437
11438 uint64_t MinOffset = -1ull;
11439 for (SDNode *N : GN->uses()) {
11440 if (N->getOpcode() != ISD::ADD)
11441 return SDValue();
11442 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11443 if (!C)
11444 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11445 if (!C)
11446 return SDValue();
11447 MinOffset = std::min(MinOffset, C->getZExtValue());
11448 }
11449 uint64_t Offset = MinOffset + GN->getOffset();
11450
11451 // Require that the new offset is larger than the existing one. Otherwise, we
11452 // can end up oscillating between two possible DAGs, for example,
11453 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11454 if (Offset <= uint64_t(GN->getOffset()))
11455 return SDValue();
11456
11457 // Check whether folding this offset is legal. It must not go out of bounds of
11458 // the referenced object to avoid violating the code model, and must be
11459 // smaller than 2^21 because this is the largest offset expressible in all
11460 // object formats.
11461 //
11462 // This check also prevents us from folding negative offsets, which will end
11463 // up being treated in the same way as large positive ones. They could also
11464 // cause code model violations, and aren't really common enough to matter.
11465 if (Offset >= (1 << 21))
11466 return SDValue();
11467
11468 const GlobalValue *GV = GN->getGlobal();
11469 Type *T = GV->getValueType();
11470 if (!T->isSized() ||
11471 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11472 return SDValue();
11473
11474 SDLoc DL(GN);
11475 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11476 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11477 DAG.getConstant(MinOffset, DL, MVT::i64));
11478}
11479
Tim Northover3b0846e2014-05-24 12:50:23 +000011480SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11481 DAGCombinerInfo &DCI) const {
11482 SelectionDAG &DAG = DCI.DAG;
11483 switch (N->getOpcode()) {
11484 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011485 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011486 break;
11487 case ISD::ADD:
11488 case ISD::SUB:
11489 return performAddSubLongCombine(N, DCI, DAG);
11490 case ISD::XOR:
11491 return performXorCombine(N, DAG, DCI, Subtarget);
11492 case ISD::MUL:
11493 return performMulCombine(N, DAG, DCI, Subtarget);
11494 case ISD::SINT_TO_FP:
11495 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011496 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011497 case ISD::FP_TO_SINT:
11498 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011499 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011500 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011501 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011502 case ISD::OR:
11503 return performORCombine(N, DCI, Subtarget);
Nikita Popov1a261442019-03-15 21:04:34 +000011504 case ISD::AND:
11505 return performANDCombine(N, DCI);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011506 case ISD::SRL:
11507 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011508 case ISD::INTRINSIC_WO_CHAIN:
11509 return performIntrinsicCombine(N, DCI, Subtarget);
11510 case ISD::ANY_EXTEND:
11511 case ISD::ZERO_EXTEND:
11512 case ISD::SIGN_EXTEND:
11513 return performExtendCombine(N, DCI, DAG);
11514 case ISD::BITCAST:
11515 return performBitcastCombine(N, DCI, DAG);
11516 case ISD::CONCAT_VECTORS:
11517 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011518 case ISD::SELECT:
11519 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011520 case ISD::VSELECT:
11521 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011522 case ISD::LOAD:
11523 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11524 return SDValue(N, 0);
11525 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011526 case ISD::STORE:
11527 return performSTORECombine(N, DCI, DAG, Subtarget);
11528 case AArch64ISD::BRCOND:
11529 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011530 case AArch64ISD::TBNZ:
11531 case AArch64ISD::TBZ:
11532 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011533 case AArch64ISD::CSEL:
11534 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011535 case AArch64ISD::DUP:
11536 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011537 case AArch64ISD::NVCAST:
11538 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011539 case ISD::INSERT_VECTOR_ELT:
11540 return performPostLD1Combine(N, DCI, true);
11541 case ISD::INTRINSIC_VOID:
11542 case ISD::INTRINSIC_W_CHAIN:
11543 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11544 case Intrinsic::aarch64_neon_ld2:
11545 case Intrinsic::aarch64_neon_ld3:
11546 case Intrinsic::aarch64_neon_ld4:
11547 case Intrinsic::aarch64_neon_ld1x2:
11548 case Intrinsic::aarch64_neon_ld1x3:
11549 case Intrinsic::aarch64_neon_ld1x4:
11550 case Intrinsic::aarch64_neon_ld2lane:
11551 case Intrinsic::aarch64_neon_ld3lane:
11552 case Intrinsic::aarch64_neon_ld4lane:
11553 case Intrinsic::aarch64_neon_ld2r:
11554 case Intrinsic::aarch64_neon_ld3r:
11555 case Intrinsic::aarch64_neon_ld4r:
11556 case Intrinsic::aarch64_neon_st2:
11557 case Intrinsic::aarch64_neon_st3:
11558 case Intrinsic::aarch64_neon_st4:
11559 case Intrinsic::aarch64_neon_st1x2:
11560 case Intrinsic::aarch64_neon_st1x3:
11561 case Intrinsic::aarch64_neon_st1x4:
11562 case Intrinsic::aarch64_neon_st2lane:
11563 case Intrinsic::aarch64_neon_st3lane:
11564 case Intrinsic::aarch64_neon_st4lane:
11565 return performNEONPostLDSTCombine(N, DCI, DAG);
11566 default:
11567 break;
11568 }
Reid Klecknereb568942018-11-01 18:02:27 +000011569 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011570 case ISD::GlobalAddress:
11571 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011572 }
11573 return SDValue();
11574}
11575
11576// Check if the return value is used as only a return value, as otherwise
11577// we can't perform a tail-call. In particular, we need to check for
11578// target ISD nodes that are returns and any other "odd" constructs
11579// that the generic analysis code won't necessarily catch.
11580bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11581 SDValue &Chain) const {
11582 if (N->getNumValues() != 1)
11583 return false;
11584 if (!N->hasNUsesOfValue(1, 0))
11585 return false;
11586
11587 SDValue TCChain = Chain;
11588 SDNode *Copy = *N->use_begin();
11589 if (Copy->getOpcode() == ISD::CopyToReg) {
11590 // If the copy has a glue operand, we conservatively assume it isn't safe to
11591 // perform a tail call.
11592 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11593 MVT::Glue)
11594 return false;
11595 TCChain = Copy->getOperand(0);
11596 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11597 return false;
11598
11599 bool HasRet = false;
11600 for (SDNode *Node : Copy->uses()) {
11601 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11602 return false;
11603 HasRet = true;
11604 }
11605
11606 if (!HasRet)
11607 return false;
11608
11609 Chain = TCChain;
11610 return true;
11611}
11612
11613// Return whether the an instruction can potentially be optimized to a tail
11614// call. This will cause the optimizers to attempt to move, or duplicate,
11615// return instructions to help enable tail call optimizations for this
11616// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011617bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011618 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011619}
11620
11621bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11622 SDValue &Offset,
11623 ISD::MemIndexedMode &AM,
11624 bool &IsInc,
11625 SelectionDAG &DAG) const {
11626 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11627 return false;
11628
11629 Base = Op->getOperand(0);
11630 // All of the indexed addressing mode instructions take a signed
11631 // 9 bit immediate offset.
11632 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011633 int64_t RHSC = RHS->getSExtValue();
11634 if (Op->getOpcode() == ISD::SUB)
11635 RHSC = -(uint64_t)RHSC;
11636 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011637 return false;
11638 IsInc = (Op->getOpcode() == ISD::ADD);
11639 Offset = Op->getOperand(1);
11640 return true;
11641 }
11642 return false;
11643}
11644
11645bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11646 SDValue &Offset,
11647 ISD::MemIndexedMode &AM,
11648 SelectionDAG &DAG) const {
11649 EVT VT;
11650 SDValue Ptr;
11651 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11652 VT = LD->getMemoryVT();
11653 Ptr = LD->getBasePtr();
11654 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11655 VT = ST->getMemoryVT();
11656 Ptr = ST->getBasePtr();
11657 } else
11658 return false;
11659
11660 bool IsInc;
11661 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11662 return false;
11663 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11664 return true;
11665}
11666
11667bool AArch64TargetLowering::getPostIndexedAddressParts(
11668 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11669 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11670 EVT VT;
11671 SDValue Ptr;
11672 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11673 VT = LD->getMemoryVT();
11674 Ptr = LD->getBasePtr();
11675 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11676 VT = ST->getMemoryVT();
11677 Ptr = ST->getBasePtr();
11678 } else
11679 return false;
11680
11681 bool IsInc;
11682 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11683 return false;
11684 // Post-indexing updates the base, so it's not a valid transform
11685 // if that's not the same as the load's pointer.
11686 if (Ptr != Base)
11687 return false;
11688 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11689 return true;
11690}
11691
Tim Northoverf8bfe212014-07-18 13:07:05 +000011692static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11693 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011694 SDLoc DL(N);
11695 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011696
11697 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11698 return;
11699
Tim Northoverf8bfe212014-07-18 13:07:05 +000011700 Op = SDValue(
11701 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11702 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011703 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011704 0);
11705 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11706 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11707}
11708
Charlie Turner434d4592015-10-16 15:38:25 +000011709static void ReplaceReductionResults(SDNode *N,
11710 SmallVectorImpl<SDValue> &Results,
11711 SelectionDAG &DAG, unsigned InterOp,
11712 unsigned AcrossOp) {
11713 EVT LoVT, HiVT;
11714 SDValue Lo, Hi;
11715 SDLoc dl(N);
11716 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11717 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11718 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11719 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11720 Results.push_back(SplitVal);
11721}
11722
Tim Northover2f32e7f2016-08-04 19:32:28 +000011723static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11724 SDLoc DL(N);
11725 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11726 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11727 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11728 DAG.getConstant(64, DL, MVT::i64)));
11729 return std::make_pair(Lo, Hi);
11730}
11731
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011732// Create an even/odd pair of X registers holding integer value V.
11733static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11734 SDLoc dl(V.getNode());
11735 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11736 SDValue VHi = DAG.getAnyExtOrTrunc(
11737 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11738 dl, MVT::i64);
11739 if (DAG.getDataLayout().isBigEndian())
11740 std::swap (VLo, VHi);
11741 SDValue RegClass =
11742 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11743 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11744 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11745 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11746 return SDValue(
11747 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11748}
11749
Tim Northovercdf15292016-04-14 17:03:29 +000011750static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011751 SmallVectorImpl<SDValue> &Results,
11752 SelectionDAG &DAG,
11753 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011754 assert(N->getValueType(0) == MVT::i128 &&
11755 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011756
11757 if (Subtarget->hasLSE()) {
11758 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11759 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11760 SDValue Ops[] = {
11761 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11762 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11763 N->getOperand(1), // Ptr
11764 N->getOperand(0), // Chain in
11765 };
11766
Chandler Carruth66654b72018-08-14 23:30:32 +000011767 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011768
11769 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011770 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011771 case AtomicOrdering::Monotonic:
11772 Opcode = AArch64::CASPX;
11773 break;
11774 case AtomicOrdering::Acquire:
11775 Opcode = AArch64::CASPAX;
11776 break;
11777 case AtomicOrdering::Release:
11778 Opcode = AArch64::CASPLX;
11779 break;
11780 case AtomicOrdering::AcquireRelease:
11781 case AtomicOrdering::SequentiallyConsistent:
11782 Opcode = AArch64::CASPALX;
11783 break;
11784 default:
11785 llvm_unreachable("Unexpected ordering!");
11786 }
11787
11788 MachineSDNode *CmpSwap = DAG.getMachineNode(
11789 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011790 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011791
11792 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11793 if (DAG.getDataLayout().isBigEndian())
11794 std::swap(SubReg1, SubReg2);
11795 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11796 SDValue(CmpSwap, 0)));
11797 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11798 SDValue(CmpSwap, 0)));
11799 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11800 return;
11801 }
11802
Tim Northover2f32e7f2016-08-04 19:32:28 +000011803 auto Desired = splitInt128(N->getOperand(2), DAG);
11804 auto New = splitInt128(N->getOperand(3), DAG);
11805 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11806 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011807 SDNode *CmpSwap = DAG.getMachineNode(
11808 AArch64::CMP_SWAP_128, SDLoc(N),
11809 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11810
Chandler Carruth66654b72018-08-14 23:30:32 +000011811 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11812 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011813
11814 Results.push_back(SDValue(CmpSwap, 0));
11815 Results.push_back(SDValue(CmpSwap, 1));
11816 Results.push_back(SDValue(CmpSwap, 3));
11817}
11818
Tim Northover3b0846e2014-05-24 12:50:23 +000011819void AArch64TargetLowering::ReplaceNodeResults(
11820 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11821 switch (N->getOpcode()) {
11822 default:
11823 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011824 case ISD::BITCAST:
11825 ReplaceBITCASTResults(N, Results, DAG);
11826 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011827 case ISD::VECREDUCE_ADD:
11828 case ISD::VECREDUCE_SMAX:
11829 case ISD::VECREDUCE_SMIN:
11830 case ISD::VECREDUCE_UMAX:
11831 case ISD::VECREDUCE_UMIN:
11832 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11833 return;
11834
Charlie Turner434d4592015-10-16 15:38:25 +000011835 case AArch64ISD::SADDV:
11836 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11837 return;
11838 case AArch64ISD::UADDV:
11839 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11840 return;
11841 case AArch64ISD::SMINV:
11842 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11843 return;
11844 case AArch64ISD::UMINV:
11845 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11846 return;
11847 case AArch64ISD::SMAXV:
11848 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11849 return;
11850 case AArch64ISD::UMAXV:
11851 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11852 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011853 case ISD::FP_TO_UINT:
11854 case ISD::FP_TO_SINT:
11855 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11856 // Let normal code take care of it by not adding anything to Results.
11857 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011858 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011859 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011860 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011861 }
11862}
11863
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011864bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011865 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11866 return TargetLowering::useLoadStackGuardNode();
11867 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011868}
11869
Sanjay Patel1dd15592015-07-28 23:05:48 +000011870unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011871 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11872 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011873 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011874}
11875
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011876TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011877AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011878 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11879 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011880 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11881 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011882 return TypeWidenVector;
11883
11884 return TargetLoweringBase::getPreferredVectorAction(VT);
11885}
11886
Robin Morisseted3d48f2014-09-03 21:29:59 +000011887// Loads and stores less than 128-bits are already atomic; ones above that
11888// are doomed anyway, so defer to the default libcall and blame the OS when
11889// things go wrong.
11890bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11891 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11892 return Size == 128;
11893}
11894
11895// Loads and stores less than 128-bits are already atomic; ones above that
11896// are doomed anyway, so defer to the default libcall and blame the OS when
11897// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011898TargetLowering::AtomicExpansionKind
11899AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011900 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011901 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011902}
11903
11904// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011905TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011906AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000011907 if (AI->isFloatingPointOperation())
11908 return AtomicExpansionKind::CmpXChg;
11909
Robin Morisseted3d48f2014-09-03 21:29:59 +000011910 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011911 if (Size > 128) return AtomicExpansionKind::None;
11912 // Nand not supported in LSE.
11913 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011914 // Leave 128 bits to LLSC.
11915 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011916}
11917
Alex Bradbury79518b02018-09-19 14:51:42 +000011918TargetLowering::AtomicExpansionKind
11919AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011920 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011921 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011922 if (Subtarget->hasLSE())
11923 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011924 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11925 // implement cmpxchg without spilling. If the address being exchanged is also
11926 // on the stack and close enough to the spill slot, this can lead to a
11927 // situation where the monitor always gets cleared and the atomic operation
11928 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011929 if (getTargetMachine().getOptLevel() == 0)
11930 return AtomicExpansionKind::None;
11931 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011932}
11933
Tim Northover3b0846e2014-05-24 12:50:23 +000011934Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11935 AtomicOrdering Ord) const {
11936 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11937 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011938 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011939
11940 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11941 // intrinsic must return {i64, i64} and we have to recombine them into a
11942 // single i128 here.
11943 if (ValTy->getPrimitiveSizeInBits() == 128) {
11944 Intrinsic::ID Int =
11945 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011946 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011947
11948 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11949 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11950
11951 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11952 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11953 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11954 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11955 return Builder.CreateOr(
11956 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11957 }
11958
11959 Type *Tys[] = { Addr->getType() };
11960 Intrinsic::ID Int =
11961 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011962 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011963
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011964 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11965
11966 const DataLayout &DL = M->getDataLayout();
11967 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11968 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11969
11970 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000011971}
11972
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011973void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11974 IRBuilder<> &Builder) const {
11975 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011976 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011977}
11978
Tim Northover3b0846e2014-05-24 12:50:23 +000011979Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11980 Value *Val, Value *Addr,
11981 AtomicOrdering Ord) const {
11982 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011983 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011984
11985 // Since the intrinsics must have legal type, the i128 intrinsics take two
11986 // parameters: "i64, i64". We must marshal Val into the appropriate form
11987 // before the call.
11988 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11989 Intrinsic::ID Int =
11990 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11991 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11992 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11993
11994 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11995 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11996 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011997 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011998 }
11999
12000 Intrinsic::ID Int =
12001 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
12002 Type *Tys[] = { Addr->getType() };
12003 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
12004
Matt Arsenault0cb08e42019-01-17 10:49:01 +000012005 const DataLayout &DL = M->getDataLayout();
12006 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
12007 Val = Builder.CreateBitCast(Val, IntValTy);
12008
David Blaikieff6409d2015-05-18 22:13:54 +000012009 return Builder.CreateCall(Stxr,
12010 {Builder.CreateZExtOrBitCast(
12011 Val, Stxr->getFunctionType()->getParamType(0)),
12012 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000012013}
Tim Northover3c55cca2014-11-27 21:02:42 +000012014
12015bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
12016 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12017 return Ty->isArrayTy();
12018}
Matthias Braunaf7d7702015-07-16 20:02:37 +000012019
12020bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
12021 EVT) const {
12022 return false;
12023}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012024
Petr Hoseka7d59162017-02-24 03:10:10 +000012025static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000012026 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
12027 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000012028 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000012029 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000012030 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
12031 Offset),
12032 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000012033}
12034
Petr Hoseka7d59162017-02-24 03:10:10 +000012035Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
12036 // Android provides a fixed TLS slot for the stack cookie. See the definition
12037 // of TLS_SLOT_STACK_GUARD in
12038 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12039 if (Subtarget->isTargetAndroid())
12040 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012041
Petr Hoseka7d59162017-02-24 03:10:10 +000012042 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000012043 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000012044 if (Subtarget->isTargetFuchsia())
12045 return UseTlsOffset(IRB, -0x10);
12046
12047 return TargetLowering::getIRStackGuard(IRB);
12048}
12049
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012050void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
12051 // MSVC CRT provides functionalities for stack protection.
12052 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
12053 // MSVC CRT has a global variable holding security cookie.
12054 M.getOrInsertGlobal("__security_cookie",
12055 Type::getInt8PtrTy(M.getContext()));
12056
12057 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000012058 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
12059 "__security_check_cookie", Type::getVoidTy(M.getContext()),
12060 Type::getInt8PtrTy(M.getContext()));
12061 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
12062 F->setCallingConv(CallingConv::Win64);
12063 F->addAttribute(1, Attribute::AttrKind::InReg);
12064 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012065 return;
12066 }
12067 TargetLowering::insertSSPDeclarations(M);
12068}
12069
12070Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12071 // MSVC CRT has a global variable holding security cookie.
12072 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12073 return M.getGlobalVariable("__security_cookie");
12074 return TargetLowering::getSDagStackGuard(M);
12075}
12076
James Y Knight7976eb52019-02-01 20:43:25 +000012077Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012078 // MSVC CRT has a function to validate security cookie.
12079 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12080 return M.getFunction("__security_check_cookie");
12081 return TargetLowering::getSSPStackGuardCheck(M);
12082}
12083
Petr Hoseka7d59162017-02-24 03:10:10 +000012084Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012085 // Android provides a fixed TLS slot for the SafeStack pointer. See the
12086 // definition of TLS_SLOT_SAFESTACK in
12087 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000012088 if (Subtarget->isTargetAndroid())
12089 return UseTlsOffset(IRB, 0x48);
12090
12091 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000012092 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000012093 if (Subtarget->isTargetFuchsia())
12094 return UseTlsOffset(IRB, -0x8);
12095
12096 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012097}
Manman Rencbe4f942015-12-16 21:04:19 +000012098
Geoff Berry5d534b62017-02-21 18:53:14 +000012099bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12100 const Instruction &AndI) const {
12101 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12102 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
12103 // may be beneficial to sink in other cases, but we would have to check that
12104 // the cmp would not get folded into the br to form a cbz for these to be
12105 // beneficial.
12106 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12107 if (!Mask)
12108 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000012109 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000012110}
12111
Roman Lebedev017e2722019-07-24 22:57:22 +000012112bool AArch64TargetLowering::
12113 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12114 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
12115 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
12116 SelectionDAG &DAG) const {
12117 // Does baseline recommend not to perform the fold by default?
12118 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12119 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
12120 return false;
12121 // Else, if this is a vector shift, prefer 'shl'.
12122 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
12123}
12124
Manman Rencbe4f942015-12-16 21:04:19 +000012125void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12126 // Update IsSplitCSR in AArch64unctionInfo.
12127 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12128 AFI->setIsSplitCSR(true);
12129}
12130
12131void AArch64TargetLowering::insertCopiesSplitCSR(
12132 MachineBasicBlock *Entry,
12133 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12134 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12135 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12136 if (!IStart)
12137 return;
12138
12139 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12140 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000012141 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000012142 for (const MCPhysReg *I = IStart; *I; ++I) {
12143 const TargetRegisterClass *RC = nullptr;
12144 if (AArch64::GPR64RegClass.contains(*I))
12145 RC = &AArch64::GPR64RegClass;
12146 else if (AArch64::FPR64RegClass.contains(*I))
12147 RC = &AArch64::FPR64RegClass;
12148 else
12149 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12150
12151 unsigned NewVR = MRI->createVirtualRegister(RC);
12152 // Create copy from CSR to a virtual register.
12153 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12154 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12155 // nounwind. If we want to generalize this later, we may need to emit
12156 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000012157 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000012158 Attribute::NoUnwind) &&
12159 "Function should be nounwind in insertCopiesSplitCSR!");
12160 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000012161 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000012162 .addReg(*I);
12163
Manman Ren4632e8e2016-01-15 20:13:28 +000012164 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000012165 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000012166 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12167 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000012168 .addReg(NewVR);
12169 }
12170}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012171
Reid Klecknerb5180542017-03-21 16:57:19 +000012172bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012173 // Integer division on AArch64 is expensive. However, when aggressively
12174 // optimizing for code size, we prefer to use a div instruction, as it is
12175 // usually smaller than the alternative sequence.
12176 // The exception to this is vector division. Since AArch64 doesn't have vector
12177 // integer division, leaving the division as-is is a loss even in terms of
12178 // size, because it will have to be scalarized, while the alternative code
12179 // sequence can be performed in vector form.
12180 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000012181 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012182 return OptSize && !VT.isVector();
12183}
Tim Northoverf19d4672017-02-08 17:57:20 +000012184
Roman Lebedevc4b83a62019-07-03 09:41:35 +000012185bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12186 // We want inc-of-add for scalars and sub-of-not for vectors.
12187 return VT.isScalarInteger();
12188}
12189
Joel Jones07150922018-01-25 21:55:39 +000012190bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12191 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12192}
12193
Tim Northoverf19d4672017-02-08 17:57:20 +000012194unsigned
12195AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000012196 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000012197 return getPointerTy(DL).getSizeInBits();
12198
12199 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12200}
Matthias Braun5c290dc2018-01-19 03:16:36 +000012201
12202void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12203 MF.getFrameInfo().computeMaxCallFrameSize(MF);
12204 TargetLoweringBase::finalizeLowering(MF);
12205}
Eli Friedmanad1151c2018-11-09 23:33:30 +000012206
12207// Unlike X86, we let frame lowering assign offsets to all catch objects.
12208bool AArch64TargetLowering::needsFixedCatchObjects() const {
12209 return false;
12210}