blob: 5048371282b8a882ab8e76648104ae977919564e [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"
Tim Northoverf1c28922019-09-12 10:22:23 +000026#include "llvm/ADT/SmallSet.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000027#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000028#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000029#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/StringSwitch.h"
31#include "llvm/ADT/Triple.h"
32#include "llvm/ADT/Twine.h"
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +000033#include "llvm/Analysis/VectorUtils.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000034#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000035#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000036#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000037#include "llvm/CodeGen/MachineFunction.h"
38#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000039#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000040#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000041#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000042#include "llvm/CodeGen/RuntimeLibcalls.h"
43#include "llvm/CodeGen/SelectionDAG.h"
44#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000045#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000046#include "llvm/CodeGen/TargetInstrInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000047#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000048#include "llvm/IR/Attributes.h"
49#include "llvm/IR/Constants.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/DebugLoc.h"
52#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000053#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000054#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000055#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000056#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000057#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Instructions.h"
Florian Hahn3b251962019-02-05 10:27:40 +000059#include "llvm/IR/IntrinsicInst.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000060#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000061#include "llvm/IR/Module.h"
62#include "llvm/IR/OperandTraits.h"
Florian Hahn3b251962019-02-05 10:27:40 +000063#include "llvm/IR/PatternMatch.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000064#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000065#include "llvm/IR/Use.h"
66#include "llvm/IR/Value.h"
67#include "llvm/MC/MCRegisterInfo.h"
68#include "llvm/Support/Casting.h"
69#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000070#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000071#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000072#include "llvm/Support/Debug.h"
73#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000074#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000075#include "llvm/Support/MachineValueType.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000076#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000077#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000078#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000079#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000080#include <algorithm>
81#include <bitset>
82#include <cassert>
83#include <cctype>
84#include <cstdint>
85#include <cstdlib>
86#include <iterator>
87#include <limits>
88#include <tuple>
89#include <utility>
90#include <vector>
91
Tim Northover3b0846e2014-05-24 12:50:23 +000092using namespace llvm;
Florian Hahn3b251962019-02-05 10:27:40 +000093using namespace llvm::PatternMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +000094
95#define DEBUG_TYPE "aarch64-lower"
96
97STATISTIC(NumTailCalls, "Number of tail calls");
98STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000099STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +0000100
Tim Northover3b0846e2014-05-24 12:50:23 +0000101static cl::opt<bool>
102EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +0000103 cl::desc("Allow AArch64 SLI/SRI formation"),
104 cl::init(false));
105
106// FIXME: The necessary dtprel relocations don't seem to be supported
107// well in the GNU bfd and gold linkers at the moment. Therefore, by
108// default, for now, fall back to GeneralDynamic code generation.
109cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
110 "aarch64-elf-ldtls-generation", cl::Hidden,
111 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
112 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000113
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000114static cl::opt<bool>
115EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
116 cl::desc("Enable AArch64 logical imm instruction "
117 "optimization"),
118 cl::init(true));
119
Matthias Braunaf7d7702015-07-16 20:02:37 +0000120/// Value type used for condition codes.
121static const MVT MVT_CC = MVT::i32;
122
Eric Christopher905f12d2015-01-29 00:19:42 +0000123AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
124 const AArch64Subtarget &STI)
125 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
127 // we have to make something up. Arbitrarily, choose ZeroOrOne.
128 setBooleanContents(ZeroOrOneBooleanContent);
129 // When comparing vectors the result sets the different elements in the
130 // vector to all-one or all-zero.
131 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
132
133 // Set up the register classes.
134 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
135 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
136
137 if (Subtarget->hasFPARMv8()) {
138 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
139 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
140 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
141 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
142 }
143
144 if (Subtarget->hasNEON()) {
145 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
146 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
147 // Someone set us up the NEON.
148 addDRTypeForNEON(MVT::v2f32);
149 addDRTypeForNEON(MVT::v8i8);
150 addDRTypeForNEON(MVT::v4i16);
151 addDRTypeForNEON(MVT::v2i32);
152 addDRTypeForNEON(MVT::v1i64);
153 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000154 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000155
156 addQRTypeForNEON(MVT::v4f32);
157 addQRTypeForNEON(MVT::v2f64);
158 addQRTypeForNEON(MVT::v16i8);
159 addQRTypeForNEON(MVT::v8i16);
160 addQRTypeForNEON(MVT::v4i32);
161 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000162 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000163 }
164
Cullen Rhodes2a481762019-08-05 13:44:10 +0000165 if (Subtarget->hasSVE()) {
166 // Add legal sve predicate types
167 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
168 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
169 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
170 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
171
172 // Add legal sve data types
173 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
174 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
175 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
176 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
177
178 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
179 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
180 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
181 addRegisterClass(MVT::nxv1f32, &AArch64::ZPRRegClass);
182 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
183 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
184 addRegisterClass(MVT::nxv1f64, &AArch64::ZPRRegClass);
185 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
186 }
187
Tim Northover3b0846e2014-05-24 12:50:23 +0000188 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000189 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000190
191 // Provide all sorts of operation actions
192 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
193 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
194 setOperationAction(ISD::SETCC, MVT::i32, Custom);
195 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000196 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000197 setOperationAction(ISD::SETCC, MVT::f32, Custom);
198 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000199 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
200 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000201 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
202 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
203 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000204 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000205 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
206 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
207 setOperationAction(ISD::SELECT, MVT::i32, Custom);
208 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000209 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000210 setOperationAction(ISD::SELECT, MVT::f32, Custom);
211 setOperationAction(ISD::SELECT, MVT::f64, Custom);
212 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
213 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000214 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000215 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
216 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
Tim Northover1c353412018-10-24 20:19:09 +0000217 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000218 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
219
220 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
221 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
222 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
223
224 setOperationAction(ISD::FREM, MVT::f32, Expand);
225 setOperationAction(ISD::FREM, MVT::f64, Expand);
226 setOperationAction(ISD::FREM, MVT::f80, Expand);
227
Amara Emersone27d5012018-04-10 19:01:58 +0000228 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
229
Tim Northover3b0846e2014-05-24 12:50:23 +0000230 // Custom lowering hooks are needed for XOR
231 // to fold it into CSINC/CSINV.
232 setOperationAction(ISD::XOR, MVT::i32, Custom);
233 setOperationAction(ISD::XOR, MVT::i64, Custom);
234
235 // Virtually no operation on f128 is legal, but LLVM can't expand them when
236 // there's a valid register class, so we need custom operations in most cases.
237 setOperationAction(ISD::FABS, MVT::f128, Expand);
238 setOperationAction(ISD::FADD, MVT::f128, Custom);
239 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
240 setOperationAction(ISD::FCOS, MVT::f128, Expand);
241 setOperationAction(ISD::FDIV, MVT::f128, Custom);
242 setOperationAction(ISD::FMA, MVT::f128, Expand);
243 setOperationAction(ISD::FMUL, MVT::f128, Custom);
244 setOperationAction(ISD::FNEG, MVT::f128, Expand);
245 setOperationAction(ISD::FPOW, MVT::f128, Expand);
246 setOperationAction(ISD::FREM, MVT::f128, Expand);
247 setOperationAction(ISD::FRINT, MVT::f128, Expand);
248 setOperationAction(ISD::FSIN, MVT::f128, Expand);
249 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
250 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
251 setOperationAction(ISD::FSUB, MVT::f128, Custom);
252 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
253 setOperationAction(ISD::SETCC, MVT::f128, Custom);
254 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
255 setOperationAction(ISD::SELECT, MVT::f128, Custom);
256 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
257 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
258
259 // Lowering for many of the conversions is actually specified by the non-f128
260 // type. The LowerXXX function will be trivial when f128 isn't involved.
261 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
262 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
263 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
264 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
265 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
266 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
267 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
268 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
269 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
270 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
271 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
272 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
273 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
274 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
275
276 // Variable arguments.
277 setOperationAction(ISD::VASTART, MVT::Other, Custom);
278 setOperationAction(ISD::VAARG, MVT::Other, Custom);
279 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
280 setOperationAction(ISD::VAEND, MVT::Other, Expand);
281
282 // Variable-sized objects.
283 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
284 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000285
286 if (Subtarget->isTargetWindows())
287 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
288 else
289 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000290
Tim Northover3b0846e2014-05-24 12:50:23 +0000291 // Constant pool entries
292 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
293
294 // BlockAddress
295 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
296
297 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
298 setOperationAction(ISD::ADDC, MVT::i32, Custom);
299 setOperationAction(ISD::ADDE, MVT::i32, Custom);
300 setOperationAction(ISD::SUBC, MVT::i32, Custom);
301 setOperationAction(ISD::SUBE, MVT::i32, Custom);
302 setOperationAction(ISD::ADDC, MVT::i64, Custom);
303 setOperationAction(ISD::ADDE, MVT::i64, Custom);
304 setOperationAction(ISD::SUBC, MVT::i64, Custom);
305 setOperationAction(ISD::SUBE, MVT::i64, Custom);
306
307 // AArch64 lacks both left-rotate and popcount instructions.
308 setOperationAction(ISD::ROTL, MVT::i32, Expand);
309 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Graham Hunter1a9195d2019-09-17 10:19:23 +0000310 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
Charlie Turner458e79b2015-10-27 10:25:20 +0000311 setOperationAction(ISD::ROTL, VT, Expand);
312 setOperationAction(ISD::ROTR, VT, Expand);
313 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000314
315 // AArch64 doesn't have {U|S}MUL_LOHI.
316 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
317 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
318
Tim Northover3b0846e2014-05-24 12:50:23 +0000319 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
320 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
321
322 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
323 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Graham Hunter1a9195d2019-09-17 10:19:23 +0000324 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
Chad Rosierf3491492015-12-04 21:38:44 +0000325 setOperationAction(ISD::SDIVREM, VT, Expand);
326 setOperationAction(ISD::UDIVREM, VT, Expand);
327 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000328 setOperationAction(ISD::SREM, MVT::i32, Expand);
329 setOperationAction(ISD::SREM, MVT::i64, Expand);
330 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
331 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
332 setOperationAction(ISD::UREM, MVT::i32, Expand);
333 setOperationAction(ISD::UREM, MVT::i64, Expand);
334
335 // Custom lower Add/Sub/Mul with overflow.
336 setOperationAction(ISD::SADDO, MVT::i32, Custom);
337 setOperationAction(ISD::SADDO, MVT::i64, Custom);
338 setOperationAction(ISD::UADDO, MVT::i32, Custom);
339 setOperationAction(ISD::UADDO, MVT::i64, Custom);
340 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
341 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
342 setOperationAction(ISD::USUBO, MVT::i32, Custom);
343 setOperationAction(ISD::USUBO, MVT::i64, Custom);
344 setOperationAction(ISD::SMULO, MVT::i32, Custom);
345 setOperationAction(ISD::SMULO, MVT::i64, Custom);
346 setOperationAction(ISD::UMULO, MVT::i32, Custom);
347 setOperationAction(ISD::UMULO, MVT::i64, Custom);
348
349 setOperationAction(ISD::FSIN, MVT::f32, Expand);
350 setOperationAction(ISD::FSIN, MVT::f64, Expand);
351 setOperationAction(ISD::FCOS, MVT::f32, Expand);
352 setOperationAction(ISD::FCOS, MVT::f64, Expand);
353 setOperationAction(ISD::FPOW, MVT::f32, Expand);
354 setOperationAction(ISD::FPOW, MVT::f64, Expand);
355 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
356 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000357 if (Subtarget->hasFullFP16())
358 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
359 else
360 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000361
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000362 setOperationAction(ISD::FREM, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000363 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
364 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000365 setOperationAction(ISD::FPOW, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000366 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
367 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000368 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000369 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
370 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000371 setOperationAction(ISD::FCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000372 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
373 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000374 setOperationAction(ISD::FSIN, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000375 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
376 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000377 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000378 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
379 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000380 setOperationAction(ISD::FEXP, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000381 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
382 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000383 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000384 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
385 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000386 setOperationAction(ISD::FLOG, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000387 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
388 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000389 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000390 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
391 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000392 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000393 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
394 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000395
396 if (!Subtarget->hasFullFP16()) {
397 setOperationAction(ISD::SELECT, MVT::f16, Promote);
398 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
399 setOperationAction(ISD::SETCC, MVT::f16, Promote);
400 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
401 setOperationAction(ISD::FADD, MVT::f16, Promote);
402 setOperationAction(ISD::FSUB, MVT::f16, Promote);
403 setOperationAction(ISD::FMUL, MVT::f16, Promote);
404 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000405 setOperationAction(ISD::FMA, MVT::f16, Promote);
406 setOperationAction(ISD::FNEG, MVT::f16, Promote);
407 setOperationAction(ISD::FABS, MVT::f16, Promote);
408 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
409 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000410 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
411 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
412 setOperationAction(ISD::FRINT, MVT::f16, Promote);
413 setOperationAction(ISD::FROUND, MVT::f16, Promote);
414 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
415 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
416 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Thomas Lively30f1d692018-10-24 22:49:55 +0000417 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
418 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000419
420 // promote v4f16 to v4f32 when that is known to be safe.
421 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
422 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
423 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
424 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
425 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
426 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
427 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
428 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
429 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
430 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
431 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
432 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
433
434 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
435 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
436 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
437 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
438 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
439 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
440 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
441 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
442 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
443 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
444 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
445 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
446 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
447 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
448 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000449
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000450 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
451 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
452 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
453 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
454 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
455 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
456 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
457 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
458 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
459 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
460 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
461 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
462 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
463 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
464 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
465 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
466 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
467 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
468 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
469 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
470 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000471
Tim Northover3b0846e2014-05-24 12:50:23 +0000472 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000473 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000474 setOperationAction(ISD::FFLOOR, Ty, Legal);
475 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
476 setOperationAction(ISD::FCEIL, Ty, Legal);
477 setOperationAction(ISD::FRINT, Ty, Legal);
478 setOperationAction(ISD::FTRUNC, Ty, Legal);
479 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000480 setOperationAction(ISD::FMINNUM, Ty, Legal);
481 setOperationAction(ISD::FMAXNUM, Ty, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000482 setOperationAction(ISD::FMINIMUM, Ty, Legal);
483 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
Adhemerval Zanella2d28db62019-05-16 13:30:18 +0000484 setOperationAction(ISD::LROUND, Ty, Legal);
485 setOperationAction(ISD::LLROUND, Ty, Legal);
Adhemerval Zanella34d8daa2019-05-28 21:04:29 +0000486 setOperationAction(ISD::LRINT, Ty, Legal);
487 setOperationAction(ISD::LLRINT, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000488 }
489
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000490 if (Subtarget->hasFullFP16()) {
491 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
492 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
493 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
494 setOperationAction(ISD::FRINT, MVT::f16, Legal);
495 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
496 setOperationAction(ISD::FROUND, MVT::f16, Legal);
497 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
498 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000499 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
500 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000501 }
502
Tim Northover3b0846e2014-05-24 12:50:23 +0000503 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
504
Tim Northover70666e72018-06-20 12:09:01 +0000505 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
506
Tim Northovercdf15292016-04-14 17:03:29 +0000507 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000508 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000510 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000512
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000513 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
514 // This requires the Performance Monitors extension.
515 if (Subtarget->hasPerfMon())
516 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
517
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000518 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
519 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
520 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000521 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
522 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
523 } else {
524 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
525 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
526 }
527
Juergen Ributzka23266502014-12-10 19:43:32 +0000528 // Make floating-point constants legal for the large code model, so they don't
529 // become loads from the constant pool.
530 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
531 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
532 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
533 }
534
Tim Northover3b0846e2014-05-24 12:50:23 +0000535 // AArch64 does not have floating-point extending loads, i1 sign-extending
536 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000537 for (MVT VT : MVT::fp_valuetypes()) {
538 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
539 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
540 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
541 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
542 }
543 for (MVT VT : MVT::integer_valuetypes())
544 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
545
Tim Northover3b0846e2014-05-24 12:50:23 +0000546 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
547 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
548 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
549 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
550 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
551 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
552 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000553
554 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
555 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
556
Tim Northover3b0846e2014-05-24 12:50:23 +0000557 // Indexed loads and stores are supported.
558 for (unsigned im = (unsigned)ISD::PRE_INC;
559 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
560 setIndexedLoadAction(im, MVT::i8, Legal);
561 setIndexedLoadAction(im, MVT::i16, Legal);
562 setIndexedLoadAction(im, MVT::i32, Legal);
563 setIndexedLoadAction(im, MVT::i64, Legal);
564 setIndexedLoadAction(im, MVT::f64, Legal);
565 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000566 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000567 setIndexedStoreAction(im, MVT::i8, Legal);
568 setIndexedStoreAction(im, MVT::i16, Legal);
569 setIndexedStoreAction(im, MVT::i32, Legal);
570 setIndexedStoreAction(im, MVT::i64, Legal);
571 setIndexedStoreAction(im, MVT::f64, Legal);
572 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000573 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000574 }
575
576 // Trap.
577 setOperationAction(ISD::TRAP, MVT::Other, Legal);
Tom Tan7ecb5142019-06-21 23:38:05 +0000578 if (Subtarget->isTargetWindows())
579 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000580
581 // We combine OR nodes for bitfield operations.
582 setTargetDAGCombine(ISD::OR);
Nikita Popov1a261442019-03-15 21:04:34 +0000583 // Try to create BICs for vector ANDs.
584 setTargetDAGCombine(ISD::AND);
Tim Northover3b0846e2014-05-24 12:50:23 +0000585
586 // Vector add and sub nodes may conceal a high-half opportunity.
587 // Also, try to fold ADD into CSINC/CSINV..
588 setTargetDAGCombine(ISD::ADD);
589 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000590 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000591 setTargetDAGCombine(ISD::XOR);
592 setTargetDAGCombine(ISD::SINT_TO_FP);
593 setTargetDAGCombine(ISD::UINT_TO_FP);
594
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000595 setTargetDAGCombine(ISD::FP_TO_SINT);
596 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000597 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000598
Tim Northover3b0846e2014-05-24 12:50:23 +0000599 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
600
601 setTargetDAGCombine(ISD::ANY_EXTEND);
602 setTargetDAGCombine(ISD::ZERO_EXTEND);
603 setTargetDAGCombine(ISD::SIGN_EXTEND);
604 setTargetDAGCombine(ISD::BITCAST);
605 setTargetDAGCombine(ISD::CONCAT_VECTORS);
606 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000607 if (Subtarget->supportsAddressTopByteIgnored())
608 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000609
610 setTargetDAGCombine(ISD::MUL);
611
612 setTargetDAGCombine(ISD::SELECT);
613 setTargetDAGCombine(ISD::VSELECT);
614
615 setTargetDAGCombine(ISD::INTRINSIC_VOID);
616 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
617 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
618
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000619 setTargetDAGCombine(ISD::GlobalAddress);
620
Evandro Menezesf8425342018-05-29 15:58:50 +0000621 // In case of strict alignment, avoid an excessive number of byte wide stores.
622 MaxStoresPerMemsetOptSize = 8;
623 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
624 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000625
Evandro Menezesf8425342018-05-29 15:58:50 +0000626 MaxGluedStoresPerMemcpy = 4;
627 MaxStoresPerMemcpyOptSize = 4;
628 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
629 ? MaxStoresPerMemcpyOptSize : 16;
630
631 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000632
Evandro Menezesa005c1a2019-08-05 18:09:14 +0000633 MaxLoadsPerMemcmpOptSize = 4;
634 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
635 ? MaxLoadsPerMemcmpOptSize : 8;
636
Tim Northover3b0846e2014-05-24 12:50:23 +0000637 setStackPointerRegisterToSaveRestore(AArch64::SP);
638
639 setSchedulingPreference(Sched::Hybrid);
640
Quentin Colombet6843ac42015-03-31 20:52:32 +0000641 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000642
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000643 // Set required alignment.
Guillaume Chatelet4fc3ad92019-09-06 12:48:34 +0000644 setMinFunctionAlignment(llvm::Align(4));
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000645 // Set preferred alignments.
Guillaume Chatelet9fcf0662019-09-06 14:51:15 +0000646 setPrefLoopAlignment(llvm::Align(1ULL << STI.getPrefLoopLogAlignment()));
Guillaume Chateletad1cea02019-09-06 15:03:49 +0000647 setPrefFunctionAlignment(
648 llvm::Align(1ULL << STI.getPrefFunctionLogAlignment()));
Tim Northover3b0846e2014-05-24 12:50:23 +0000649
Evandro Menezese45de8a2016-09-26 15:32:33 +0000650 // Only change the limit for entries in a jump table if specified by
Evandro Menezes0f797b82019-03-29 17:28:11 +0000651 // the sub target, but not at the command line.
Evandro Menezese45de8a2016-09-26 15:32:33 +0000652 unsigned MaxJT = STI.getMaximumJumpTableSize();
Evandro Menezes0f797b82019-03-29 17:28:11 +0000653 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
Evandro Menezese45de8a2016-09-26 15:32:33 +0000654 setMaximumJumpTableSize(MaxJT);
655
Tim Northover3b0846e2014-05-24 12:50:23 +0000656 setHasExtractBitsInsn(true);
657
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000658 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
659
Tim Northover3b0846e2014-05-24 12:50:23 +0000660 if (Subtarget->hasNEON()) {
661 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
662 // silliness like this:
663 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
664 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
665 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
666 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
667 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
668 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
669 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
670 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
671 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
672 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
673 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
674 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
675 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
676 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
677 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
678 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
679 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
680 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
681 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
682 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
683 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
684 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
685 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
686 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
687 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
688
689 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
690 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
691 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
692 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
693 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
694
695 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
696
697 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
698 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000699 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
700 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000701 // i8 vector elements also need promotion to i32 for v8i8
Craig Toppera4f99972018-01-01 19:21:35 +0000702 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
703 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000704 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
705 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
706 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
707 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
708 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000709 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
710 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
711 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
712 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000713
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000714 if (Subtarget->hasFullFP16()) {
715 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
716 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
717 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
718 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
719 } else {
720 // when AArch64 doesn't have fullfp16 support, promote the input
721 // to i32 first.
722 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
723 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
724 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
725 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
726 }
727
Craig Topperc5551bf2016-04-26 05:26:51 +0000728 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
729 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
730
Tim Northover3b0846e2014-05-24 12:50:23 +0000731 // AArch64 doesn't have MUL.2d:
732 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000733 // Custom handling for some quad-vector types to detect MULL.
734 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
735 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
736 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
737
Amara Emersonc9916d72017-05-16 21:29:22 +0000738 // Vector reductions
Nikita Popovaa7cfa72019-03-11 20:22:13 +0000739 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
740 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
Amara Emersonc9916d72017-05-16 21:29:22 +0000741 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
742 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
743 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
744 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
745 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
746 }
Nikita Popovaa7cfa72019-03-11 20:22:13 +0000747 for (MVT VT : { MVT::v4f16, MVT::v2f32,
748 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
Amara Emersonc9916d72017-05-16 21:29:22 +0000749 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
750 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
751 }
752
Tim Northover3b0846e2014-05-24 12:50:23 +0000753 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
754 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
755 // Likewise, narrowing and extending vector loads/stores aren't handled
756 // directly.
Graham Hunter1a9195d2019-09-17 10:19:23 +0000757 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000758 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000759
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000760 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
Craig Topper129d5292018-11-29 19:36:17 +0000761 setOperationAction(ISD::MULHS, VT, Legal);
762 setOperationAction(ISD::MULHU, VT, Legal);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000763 } else {
764 setOperationAction(ISD::MULHS, VT, Expand);
765 setOperationAction(ISD::MULHU, VT, Expand);
766 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000767 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000768 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000769
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000770 setOperationAction(ISD::BSWAP, VT, Expand);
Nikita Popova3be17e2019-02-12 18:55:53 +0000771 setOperationAction(ISD::CTTZ, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000772
Graham Hunter1a9195d2019-09-17 10:19:23 +0000773 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000774 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000775 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
776 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
777 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
778 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000779 }
780
781 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000782 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000783 setOperationAction(ISD::FFLOOR, Ty, Legal);
784 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
785 setOperationAction(ISD::FCEIL, Ty, Legal);
786 setOperationAction(ISD::FRINT, Ty, Legal);
787 setOperationAction(ISD::FTRUNC, Ty, Legal);
788 setOperationAction(ISD::FROUND, Ty, Legal);
789 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000790
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +0000791 if (Subtarget->hasFullFP16()) {
792 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
793 setOperationAction(ISD::FFLOOR, Ty, Legal);
794 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
795 setOperationAction(ISD::FCEIL, Ty, Legal);
796 setOperationAction(ISD::FRINT, Ty, Legal);
797 setOperationAction(ISD::FTRUNC, Ty, Legal);
798 setOperationAction(ISD::FROUND, Ty, Legal);
799 }
800 }
801
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000802 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000803 }
James Molloyf089ab72014-08-06 10:42:18 +0000804
Matthias Braun651cff42016-06-02 18:03:53 +0000805 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000806}
807
Craig Topper18e69f42016-04-15 06:20:21 +0000808void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000809 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000810
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000811 if (VT.isFloatingPoint()) {
812 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
813 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
814 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000815 }
816
817 // Mark vector float intrinsics as expand.
818 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000819 setOperationAction(ISD::FSIN, VT, Expand);
820 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000821 setOperationAction(ISD::FPOW, VT, Expand);
822 setOperationAction(ISD::FLOG, VT, Expand);
823 setOperationAction(ISD::FLOG2, VT, Expand);
824 setOperationAction(ISD::FLOG10, VT, Expand);
825 setOperationAction(ISD::FEXP, VT, Expand);
826 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000827
828 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000829 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000830 }
831
Craig Topper18e69f42016-04-15 06:20:21 +0000832 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
834 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
835 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
836 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
837 setOperationAction(ISD::SRA, VT, Custom);
838 setOperationAction(ISD::SRL, VT, Custom);
839 setOperationAction(ISD::SHL, VT, Custom);
Craig Topper18e69f42016-04-15 06:20:21 +0000840 setOperationAction(ISD::OR, VT, Custom);
841 setOperationAction(ISD::SETCC, VT, Custom);
842 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000843
Craig Topper18e69f42016-04-15 06:20:21 +0000844 setOperationAction(ISD::SELECT, VT, Expand);
845 setOperationAction(ISD::SELECT_CC, VT, Expand);
846 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000847 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000848 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000849
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000850 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000851 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000852 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000853
Craig Topper18e69f42016-04-15 06:20:21 +0000854 setOperationAction(ISD::UDIV, VT, Expand);
855 setOperationAction(ISD::SDIV, VT, Expand);
856 setOperationAction(ISD::UREM, VT, Expand);
857 setOperationAction(ISD::SREM, VT, Expand);
858 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000859
Craig Topper18e69f42016-04-15 06:20:21 +0000860 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
861 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000862
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000863 if (!VT.isFloatingPoint())
864 setOperationAction(ISD::ABS, VT, Legal);
865
Hal Finkelcd8664c2015-12-11 23:11:52 +0000866 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000867 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000868 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000869 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000870
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000871 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
872 if (VT.isFloatingPoint() &&
873 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000874 for (unsigned Opcode :
875 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000876 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000877
Tim Northover3b0846e2014-05-24 12:50:23 +0000878 if (Subtarget->isLittleEndian()) {
879 for (unsigned im = (unsigned)ISD::PRE_INC;
880 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000881 setIndexedLoadAction(im, VT, Legal);
882 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000883 }
884 }
885}
886
887void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
888 addRegisterClass(VT, &AArch64::FPR64RegClass);
889 addTypeForNEON(VT, MVT::v2i32);
890}
891
892void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
893 addRegisterClass(VT, &AArch64::FPR128RegClass);
894 addTypeForNEON(VT, MVT::v4i32);
895}
896
Mehdi Amini44ede332015-07-09 02:09:04 +0000897EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
898 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000899 if (!VT.isVector())
900 return MVT::i32;
901 return VT.changeVectorElementTypeToInteger();
902}
903
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000904static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
905 const APInt &Demanded,
906 TargetLowering::TargetLoweringOpt &TLO,
907 unsigned NewOpc) {
908 uint64_t OldImm = Imm, NewImm, Enc;
909 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
910
911 // Return if the immediate is already all zeros, all ones, a bimm32 or a
912 // bimm64.
913 if (Imm == 0 || Imm == Mask ||
914 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
915 return false;
916
917 unsigned EltSize = Size;
918 uint64_t DemandedBits = Demanded.getZExtValue();
919
920 // Clear bits that are not demanded.
921 Imm &= DemandedBits;
922
923 while (true) {
924 // The goal here is to set the non-demanded bits in a way that minimizes
925 // the number of switching between 0 and 1. In order to achieve this goal,
926 // we set the non-demanded bits to the value of the preceding demanded bits.
927 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
928 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
929 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
930 // The final result is 0b11000011.
931 uint64_t NonDemandedBits = ~DemandedBits;
932 uint64_t InvertedImm = ~Imm & DemandedBits;
933 uint64_t RotatedImm =
934 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
935 NonDemandedBits;
936 uint64_t Sum = RotatedImm + NonDemandedBits;
937 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
938 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
939 NewImm = (Imm | Ones) & Mask;
940
941 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
942 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
943 // we halve the element size and continue the search.
944 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
945 break;
946
947 // We cannot shrink the element size any further if it is 2-bits.
948 if (EltSize == 2)
949 return false;
950
951 EltSize /= 2;
952 Mask >>= EltSize;
953 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
954
955 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
956 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
957 return false;
958
959 // Merge the upper and lower halves of Imm and DemandedBits.
960 Imm |= Hi;
961 DemandedBits |= DemandedBitsHi;
962 }
963
964 ++NumOptimizedImms;
965
966 // Replicate the element across the register width.
967 while (EltSize < Size) {
968 NewImm |= NewImm << EltSize;
969 EltSize *= 2;
970 }
971
972 (void)OldImm;
973 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
974 "demanded bits should never be altered");
975 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
976
977 // Create the new constant immediate node.
978 EVT VT = Op.getValueType();
979 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000980 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000981
982 // If the new constant immediate is all-zeros or all-ones, let the target
983 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000984 if (NewImm == 0 || NewImm == OrigMask) {
985 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
986 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000987 // Otherwise, create a machine node so that target independent DAG combine
988 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000989 } else {
990 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
991 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
992 New = SDValue(
993 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
994 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000995
996 return TLO.CombineTo(Op, New);
997}
998
999bool AArch64TargetLowering::targetShrinkDemandedConstant(
1000 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1001 // Delay this optimization to as late as possible.
1002 if (!TLO.LegalOps)
1003 return false;
1004
1005 if (!EnableOptimizeLogicalImm)
1006 return false;
1007
1008 EVT VT = Op.getValueType();
1009 if (VT.isVector())
1010 return false;
1011
1012 unsigned Size = VT.getSizeInBits();
1013 assert((Size == 32 || Size == 64) &&
1014 "i32 or i64 is expected after legalization.");
1015
1016 // Exit early if we demand all bits.
1017 if (Demanded.countPopulation() == Size)
1018 return false;
1019
1020 unsigned NewOpc;
1021 switch (Op.getOpcode()) {
1022 default:
1023 return false;
1024 case ISD::AND:
1025 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1026 break;
1027 case ISD::OR:
1028 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1029 break;
1030 case ISD::XOR:
1031 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1032 break;
1033 }
1034 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1035 if (!C)
1036 return false;
1037 uint64_t Imm = C->getZExtValue();
1038 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1039}
1040
Tim Northover3b0846e2014-05-24 12:50:23 +00001041/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +00001042/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +00001043void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +00001044 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +00001045 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001046 switch (Op.getOpcode()) {
1047 default:
1048 break;
1049 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001050 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +00001051 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1052 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +00001053 Known.Zero &= Known2.Zero;
1054 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001055 break;
1056 }
Tim Northoverf1c28922019-09-12 10:22:23 +00001057 case AArch64ISD::LOADgot:
1058 case AArch64ISD::ADDlow: {
1059 if (!Subtarget->isTargetILP32())
1060 break;
1061 // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1062 Known.Zero = APInt::getHighBitsSet(64, 32);
1063 break;
1064 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001065 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001066 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001067 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1068 switch (IntID) {
1069 default: return;
1070 case Intrinsic::aarch64_ldaxr:
1071 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001072 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001073 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001074 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001075 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001076 return;
1077 }
1078 }
1079 break;
1080 }
1081 case ISD::INTRINSIC_WO_CHAIN:
1082 case ISD::INTRINSIC_VOID: {
1083 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1084 switch (IntNo) {
1085 default:
1086 break;
1087 case Intrinsic::aarch64_neon_umaxv:
1088 case Intrinsic::aarch64_neon_uminv: {
1089 // Figure out the datatype of the vector operand. The UMINV instruction
1090 // will zero extend the result, so we can mark as known zero all the
1091 // bits larger than the element datatype. 32-bit or larget doesn't need
1092 // this as those are legal types and will be handled by isel directly.
1093 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001094 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001095 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1096 assert(BitWidth >= 8 && "Unexpected width!");
1097 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001098 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001099 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1100 assert(BitWidth >= 16 && "Unexpected width!");
1101 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001102 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001103 }
1104 break;
1105 } break;
1106 }
1107 }
1108 }
1109}
1110
Mehdi Aminieaabc512015-07-09 15:12:23 +00001111MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1112 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001113 return MVT::i64;
1114}
1115
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00001116bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1117 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1118 bool *Fast) const {
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001119 if (Subtarget->requiresStrictAlign())
1120 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001121
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001122 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001123 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1124 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001125 // See comments in performSTORECombine() for more details about
1126 // these conditions.
1127
1128 // Code that uses clang vector extensions can mark that it
1129 // wants unaligned accesses to be treated as fast by
1130 // underspecifying alignment to be 1 or 2.
1131 Align <= 2 ||
1132
1133 // Disregard v2i64. Memcpy lowering produces those and splitting
1134 // them regresses performance on micro-benchmarks and olden/bh.
1135 VT == MVT::v2i64;
1136 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001137 return true;
1138}
1139
Amara Emerson13af1ed2019-07-24 22:17:31 +00001140// Same as above but handling LLTs instead.
1141bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1142 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1143 bool *Fast) const {
1144 if (Subtarget->requiresStrictAlign())
1145 return false;
1146
1147 if (Fast) {
1148 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1149 *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1150 Ty.getSizeInBytes() != 16 ||
1151 // See comments in performSTORECombine() for more details about
1152 // these conditions.
1153
1154 // Code that uses clang vector extensions can mark that it
1155 // wants unaligned accesses to be treated as fast by
1156 // underspecifying alignment to be 1 or 2.
1157 Align <= 2 ||
1158
1159 // Disregard v2i64. Memcpy lowering produces those and splitting
1160 // them regresses performance on micro-benchmarks and olden/bh.
1161 Ty == LLT::vector(2, 64);
1162 }
1163 return true;
1164}
1165
Tim Northover3b0846e2014-05-24 12:50:23 +00001166FastISel *
1167AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168 const TargetLibraryInfo *libInfo) const {
1169 return AArch64::createFastISel(funcInfo, libInfo);
1170}
1171
1172const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001173 switch ((AArch64ISD::NodeType)Opcode) {
1174 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001175 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1176 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001177 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001178 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1179 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1180 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1181 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1182 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1183 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1184 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1185 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1186 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1187 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001188 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001189 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1190 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1191 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1192 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1193 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1194 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1195 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001196 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1197 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1198 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001199 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001200 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1201 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1202 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1203 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1204 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1205 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1206 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1207 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1208 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1209 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1210 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1211 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1212 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1213 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1214 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1215 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1216 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1217 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1218 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1219 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1220 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1221 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1222 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1223 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1224 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1225 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1226 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1227 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1228 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1229 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1230 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1231 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1232 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1233 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1234 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1235 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1236 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1237 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1238 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1239 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1240 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1241 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1242 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1243 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1244 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1245 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1246 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1247 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001248 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1249 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1250 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1251 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1252 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1253 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001254 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1255 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1256 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1257 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1258 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1259 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1260 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001261 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001262 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1263 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001264 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001265 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1266 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1267 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1268 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1269 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1270 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1271 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1272 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1273 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1274 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1275 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1276 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1277 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1278 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1279 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1280 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1281 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1282 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1283 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1284 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1285 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1286 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1287 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1288 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1289 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1290 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1291 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1292 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1293 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001294 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1295 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001296 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001297 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1298 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1299 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Evgeniy Stepanovd752f5e2019-07-17 19:24:02 +00001300 case AArch64ISD::STG: return "AArch64ISD::STG";
1301 case AArch64ISD::STZG: return "AArch64ISD::STZG";
1302 case AArch64ISD::ST2G: return "AArch64ISD::ST2G";
1303 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G";
Tim Northover3b0846e2014-05-24 12:50:23 +00001304 }
Matthias Braund04893f2015-05-07 21:33:59 +00001305 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001306}
1307
1308MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001309AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001310 MachineBasicBlock *MBB) const {
1311 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1312 // phi node:
1313
1314 // OrigBB:
1315 // [... previous instrs leading to comparison ...]
1316 // b.ne TrueBB
1317 // b EndBB
1318 // TrueBB:
1319 // ; Fallthrough
1320 // EndBB:
1321 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1322
Tim Northover3b0846e2014-05-24 12:50:23 +00001323 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001324 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001325 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001326 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001327 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001328
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001329 Register DestReg = MI.getOperand(0).getReg();
1330 Register IfTrueReg = MI.getOperand(1).getReg();
1331 Register IfFalseReg = MI.getOperand(2).getReg();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001332 unsigned CondCode = MI.getOperand(3).getImm();
1333 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001334
1335 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1336 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1337 MF->insert(It, TrueBB);
1338 MF->insert(It, EndBB);
1339
1340 // Transfer rest of current basic-block to EndBB
1341 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1342 MBB->end());
1343 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1344
1345 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1346 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1347 MBB->addSuccessor(TrueBB);
1348 MBB->addSuccessor(EndBB);
1349
1350 // TrueBB falls through to the end.
1351 TrueBB->addSuccessor(EndBB);
1352
1353 if (!NZCVKilled) {
1354 TrueBB->addLiveIn(AArch64::NZCV);
1355 EndBB->addLiveIn(AArch64::NZCV);
1356 }
1357
1358 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1359 .addReg(IfTrueReg)
1360 .addMBB(TrueBB)
1361 .addReg(IfFalseReg)
1362 .addMBB(MBB);
1363
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001364 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001365 return EndBB;
1366}
1367
Eli Friedmanad1151c2018-11-09 23:33:30 +00001368MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1369 MachineInstr &MI, MachineBasicBlock *BB) const {
1370 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1371 BB->getParent()->getFunction().getPersonalityFn())) &&
1372 "SEH does not use catchret!");
1373 return BB;
1374}
1375
1376MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1377 MachineInstr &MI, MachineBasicBlock *BB) const {
1378 MI.eraseFromParent();
1379 return BB;
1380}
1381
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001382MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1383 MachineInstr &MI, MachineBasicBlock *BB) const {
1384 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001385 default:
1386#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001387 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001388#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001389 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001390
1391 case AArch64::F128CSEL:
1392 return EmitF128CSEL(MI, BB);
1393
1394 case TargetOpcode::STACKMAP:
1395 case TargetOpcode::PATCHPOINT:
1396 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001397
1398 case AArch64::CATCHRET:
1399 return EmitLoweredCatchRet(MI, BB);
1400 case AArch64::CATCHPAD:
1401 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001402 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001403}
1404
1405//===----------------------------------------------------------------------===//
1406// AArch64 Lowering private implementation.
1407//===----------------------------------------------------------------------===//
1408
1409//===----------------------------------------------------------------------===//
1410// Lowering Code
1411//===----------------------------------------------------------------------===//
1412
1413/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1414/// CC
1415static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1416 switch (CC) {
1417 default:
1418 llvm_unreachable("Unknown condition code!");
1419 case ISD::SETNE:
1420 return AArch64CC::NE;
1421 case ISD::SETEQ:
1422 return AArch64CC::EQ;
1423 case ISD::SETGT:
1424 return AArch64CC::GT;
1425 case ISD::SETGE:
1426 return AArch64CC::GE;
1427 case ISD::SETLT:
1428 return AArch64CC::LT;
1429 case ISD::SETLE:
1430 return AArch64CC::LE;
1431 case ISD::SETUGT:
1432 return AArch64CC::HI;
1433 case ISD::SETUGE:
1434 return AArch64CC::HS;
1435 case ISD::SETULT:
1436 return AArch64CC::LO;
1437 case ISD::SETULE:
1438 return AArch64CC::LS;
1439 }
1440}
1441
1442/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1443static void changeFPCCToAArch64CC(ISD::CondCode CC,
1444 AArch64CC::CondCode &CondCode,
1445 AArch64CC::CondCode &CondCode2) {
1446 CondCode2 = AArch64CC::AL;
1447 switch (CC) {
1448 default:
1449 llvm_unreachable("Unknown FP condition!");
1450 case ISD::SETEQ:
1451 case ISD::SETOEQ:
1452 CondCode = AArch64CC::EQ;
1453 break;
1454 case ISD::SETGT:
1455 case ISD::SETOGT:
1456 CondCode = AArch64CC::GT;
1457 break;
1458 case ISD::SETGE:
1459 case ISD::SETOGE:
1460 CondCode = AArch64CC::GE;
1461 break;
1462 case ISD::SETOLT:
1463 CondCode = AArch64CC::MI;
1464 break;
1465 case ISD::SETOLE:
1466 CondCode = AArch64CC::LS;
1467 break;
1468 case ISD::SETONE:
1469 CondCode = AArch64CC::MI;
1470 CondCode2 = AArch64CC::GT;
1471 break;
1472 case ISD::SETO:
1473 CondCode = AArch64CC::VC;
1474 break;
1475 case ISD::SETUO:
1476 CondCode = AArch64CC::VS;
1477 break;
1478 case ISD::SETUEQ:
1479 CondCode = AArch64CC::EQ;
1480 CondCode2 = AArch64CC::VS;
1481 break;
1482 case ISD::SETUGT:
1483 CondCode = AArch64CC::HI;
1484 break;
1485 case ISD::SETUGE:
1486 CondCode = AArch64CC::PL;
1487 break;
1488 case ISD::SETLT:
1489 case ISD::SETULT:
1490 CondCode = AArch64CC::LT;
1491 break;
1492 case ISD::SETLE:
1493 case ISD::SETULE:
1494 CondCode = AArch64CC::LE;
1495 break;
1496 case ISD::SETNE:
1497 case ISD::SETUNE:
1498 CondCode = AArch64CC::NE;
1499 break;
1500 }
1501}
1502
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001503/// Convert a DAG fp condition code to an AArch64 CC.
1504/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1505/// should be AND'ed instead of OR'ed.
1506static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1507 AArch64CC::CondCode &CondCode,
1508 AArch64CC::CondCode &CondCode2) {
1509 CondCode2 = AArch64CC::AL;
1510 switch (CC) {
1511 default:
1512 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1513 assert(CondCode2 == AArch64CC::AL);
1514 break;
1515 case ISD::SETONE:
1516 // (a one b)
1517 // == ((a olt b) || (a ogt b))
1518 // == ((a ord b) && (a une b))
1519 CondCode = AArch64CC::VC;
1520 CondCode2 = AArch64CC::NE;
1521 break;
1522 case ISD::SETUEQ:
1523 // (a ueq b)
1524 // == ((a uno b) || (a oeq b))
1525 // == ((a ule b) && (a uge b))
1526 CondCode = AArch64CC::PL;
1527 CondCode2 = AArch64CC::LE;
1528 break;
1529 }
1530}
1531
Tim Northover3b0846e2014-05-24 12:50:23 +00001532/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1533/// CC usable with the vector instructions. Fewer operations are available
1534/// without a real NZCV register, so we have to use less efficient combinations
1535/// to get the same effect.
1536static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1537 AArch64CC::CondCode &CondCode,
1538 AArch64CC::CondCode &CondCode2,
1539 bool &Invert) {
1540 Invert = false;
1541 switch (CC) {
1542 default:
1543 // Mostly the scalar mappings work fine.
1544 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1545 break;
1546 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001547 Invert = true;
1548 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001549 case ISD::SETO:
1550 CondCode = AArch64CC::MI;
1551 CondCode2 = AArch64CC::GE;
1552 break;
1553 case ISD::SETUEQ:
1554 case ISD::SETULT:
1555 case ISD::SETULE:
1556 case ISD::SETUGT:
1557 case ISD::SETUGE:
1558 // All of the compare-mask comparisons are ordered, but we can switch
1559 // between the two by a double inversion. E.g. ULE == !OGT.
1560 Invert = true;
1561 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1562 break;
1563 }
1564}
1565
1566static bool isLegalArithImmed(uint64_t C) {
1567 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001568 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001569 LLVM_DEBUG(dbgs() << "Is imm " << C
1570 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001571 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001572}
1573
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001574// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1575// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1576// can be set differently by this operation. It comes down to whether
1577// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1578// everything is fine. If not then the optimization is wrong. Thus general
1579// comparisons are only valid if op2 != 0.
1580//
1581// So, finally, the only LLVM-native comparisons that don't mention C and V
1582// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1583// the absence of information about op2.
1584static bool isCMN(SDValue Op, ISD::CondCode CC) {
1585 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1586 (CC == ISD::SETEQ || CC == ISD::SETNE);
1587}
1588
Tim Northover3b0846e2014-05-24 12:50:23 +00001589static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001590 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001591 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001592 const bool FullFP16 =
1593 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001594
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001595 if (VT.isFloatingPoint()) {
1596 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001597 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001598 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1599 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001600 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001601 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001602 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001603 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001604
1605 // The CMP instruction is just an alias for SUBS, and representing it as
1606 // SUBS means that it's possible to get CSE with subtract operations.
1607 // A later phase can perform the optimization of setting the destination
1608 // register to WZR/XZR if it ends up being unused.
1609 unsigned Opcode = AArch64ISD::SUBS;
1610
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001611 if (isCMN(RHS, CC)) {
1612 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001613 Opcode = AArch64ISD::ADDS;
1614 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001615 } else if (isCMN(LHS, CC)) {
1616 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1617 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1618 Opcode = AArch64ISD::ADDS;
1619 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001620 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001621 !isUnsignedIntSetCC(CC)) {
1622 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1623 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1624 // of the signed comparisons.
1625 Opcode = AArch64ISD::ANDS;
1626 RHS = LHS.getOperand(1);
1627 LHS = LHS.getOperand(0);
1628 }
1629
Matthias Braunaf7d7702015-07-16 20:02:37 +00001630 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001631 .getValue(1);
1632}
1633
Matthias Braunaf7d7702015-07-16 20:02:37 +00001634/// \defgroup AArch64CCMP CMP;CCMP matching
1635///
1636/// These functions deal with the formation of CMP;CCMP;... sequences.
1637/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1638/// a comparison. They set the NZCV flags to a predefined value if their
1639/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001640/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001641/// expressed as:
1642/// cmp A
1643/// ccmp B, inv(CB), CA
1644/// check for CB flags
1645///
Matthias Braund0412122018-12-06 01:40:23 +00001646/// This naturally lets us implement chains of AND operations with SETCC
1647/// operands. And we can even implement some other situations by transforming
1648/// them:
1649/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1650/// negating the flags used in a CCMP/FCCMP operations.
1651/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1652/// by negating the flags we test for afterwards. i.e.
1653/// NEG (CMP CCMP CCCMP ...) can be implemented.
1654/// - Note that we can only ever negate all previously processed results.
1655/// What we can not implement by flipping the flags to test is a negation
1656/// of two sub-trees (because the negation affects all sub-trees emitted so
1657/// far, so the 2nd sub-tree we emit would also affect the first).
1658/// With those tools we can implement some OR operations:
1659/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1660/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1661/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1662/// elimination rules from earlier to implement the whole thing as a
1663/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001664///
Matthias Braund0412122018-12-06 01:40:23 +00001665/// As complete example:
1666/// or (or (setCA (cmp A)) (setCB (cmp B)))
1667/// (and (setCC (cmp C)) (setCD (cmp D)))"
1668/// can be reassociated to:
1669/// or (and (setCC (cmp C)) setCD (cmp D))
1670// (or (setCA (cmp A)) (setCB (cmp B)))
1671/// can be transformed to:
1672/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1673/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1674/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001675/// cmp C
1676/// ccmp D, inv(CD), CC
1677/// ccmp A, CA, inv(CD)
1678/// ccmp B, CB, inv(CA)
1679/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001680///
1681/// A counterexample is "or (and A B) (and C D)" which translates to
1682/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1683/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001684/// @{
1685
Geoff Berrye41c2df2015-07-20 22:03:52 +00001686/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001687static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1688 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001689 AArch64CC::CondCode Predicate,
1690 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001691 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001692 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001693 const bool FullFP16 =
1694 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1695
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001696 if (LHS.getValueType().isFloatingPoint()) {
1697 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001698 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001699 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1700 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1701 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001702 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001703 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001704 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001705 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001706 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1707 Opcode = AArch64ISD::CCMN;
1708 RHS = RHS.getOperand(1);
1709 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001710 }
1711 if (Opcode == 0)
1712 Opcode = AArch64ISD::CCMP;
1713
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001714 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1715 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1716 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001717 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1718 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1719}
1720
Matthias Braun96d12512018-11-06 03:15:22 +00001721/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1722/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001723/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1724/// changing the conditions on the SETCC tests.
1725/// (this means we can call emitConjunctionRec() with
1726/// Negate==true on this sub-tree)
1727/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1728/// cannot do the negation naturally. We are required to
1729/// emit the subtree first in this case.
1730/// \param WillNegate Is true if are called when the result of this
1731/// subexpression must be negated. This happens when the
1732/// outer expression is an OR. We can use this fact to know
1733/// that we have a double negation (or (or ...) ...) that
1734/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001735static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001736 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001737 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001738 if (!Val.hasOneUse())
1739 return false;
1740 unsigned Opcode = Val->getOpcode();
1741 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001742 if (Val->getOperand(0).getValueType() == MVT::f128)
1743 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001744 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001745 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001746 return true;
1747 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001748 // Protect against exponential runtime and stack overflow.
1749 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001750 return false;
1751 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001752 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001753 SDValue O0 = Val->getOperand(0);
1754 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001755 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001756 bool MustBeFirstL;
1757 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001758 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001759 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001760 bool MustBeFirstR;
1761 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001762 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001763
Matthias Braund0412122018-12-06 01:40:23 +00001764 if (MustBeFirstL && MustBeFirstR)
1765 return false;
1766
1767 if (IsOR) {
1768 // For an OR expression we need to be able to naturally negate at least
1769 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001770 if (!CanNegateL && !CanNegateR)
1771 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001772 // If we the result of the OR will be negated and we can naturally negate
1773 // the leafs, then this sub-tree as a whole negates naturally.
1774 CanNegate = WillNegate && CanNegateL && CanNegateR;
1775 // If we cannot naturally negate the whole sub-tree, then this must be
1776 // emitted first.
1777 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001778 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001779 assert(Opcode == ISD::AND && "Must be OR or AND");
1780 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001781 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001782 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001783 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001784 return true;
1785 }
1786 return false;
1787}
1788
1789/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1790/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1791/// Tries to transform the given i1 producing node @p Val to a series compare
1792/// and conditional compare operations. @returns an NZCV flags producing node
1793/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1794/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001795/// \p Negate is true if we want this sub-tree being negated just by changing
1796/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001797static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001798 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001799 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001800 // We're at a tree leaf, produce a conditional comparison operation.
1801 unsigned Opcode = Val->getOpcode();
1802 if (Opcode == ISD::SETCC) {
1803 SDValue LHS = Val->getOperand(0);
1804 SDValue RHS = Val->getOperand(1);
1805 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1806 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001807 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001808 CC = getSetCCInverse(CC, isInteger);
1809 SDLoc DL(Val);
1810 // Determine OutCC and handle FP special case.
1811 if (isInteger) {
1812 OutCC = changeIntCCToAArch64CC(CC);
1813 } else {
1814 assert(LHS.getValueType().isFloatingPoint());
1815 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001816 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1817 // Some floating point conditions can't be tested with a single condition
1818 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001819 if (ExtraCC != AArch64CC::AL) {
1820 SDValue ExtraCmp;
1821 if (!CCOp.getNode())
1822 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001823 else
1824 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001825 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001826 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001827 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001828 }
1829 }
1830
1831 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001832 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001833 return emitComparison(LHS, RHS, CC, DL, DAG);
1834 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001835 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001836 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001837 }
Matthias Braund0412122018-12-06 01:40:23 +00001838 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001839
Matthias Braund0412122018-12-06 01:40:23 +00001840 bool IsOR = Opcode == ISD::OR;
1841
Matthias Braunaf7d7702015-07-16 20:02:37 +00001842 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001843 bool CanNegateL;
1844 bool MustBeFirstL;
1845 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1846 assert(ValidL && "Valid conjunction/disjunction tree");
1847 (void)ValidL;
1848
Matthias Braunaf7d7702015-07-16 20:02:37 +00001849 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001850 bool CanNegateR;
1851 bool MustBeFirstR;
1852 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1853 assert(ValidR && "Valid conjunction/disjunction tree");
1854 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001855
Matthias Braund0412122018-12-06 01:40:23 +00001856 // Swap sub-tree that must come first to the right side.
1857 if (MustBeFirstL) {
1858 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1859 std::swap(LHS, RHS);
1860 std::swap(CanNegateL, CanNegateR);
1861 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001862 }
1863
Matthias Braund0412122018-12-06 01:40:23 +00001864 bool NegateR;
1865 bool NegateAfterR;
1866 bool NegateL;
1867 bool NegateAfterAll;
1868 if (Opcode == ISD::OR) {
1869 // Swap the sub-tree that we can negate naturally to the left.
1870 if (!CanNegateL) {
1871 assert(CanNegateR && "at least one side must be negatable");
1872 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1873 assert(!Negate);
1874 std::swap(LHS, RHS);
1875 NegateR = false;
1876 NegateAfterR = true;
1877 } else {
1878 // Negate the left sub-tree if possible, otherwise negate the result.
1879 NegateR = CanNegateR;
1880 NegateAfterR = !CanNegateR;
1881 }
1882 NegateL = true;
1883 NegateAfterAll = !Negate;
1884 } else {
1885 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1886 assert(!Negate && "Valid conjunction/disjunction tree");
1887
1888 NegateL = false;
1889 NegateR = false;
1890 NegateAfterR = false;
1891 NegateAfterAll = false;
1892 }
1893
1894 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001895 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001896 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1897 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001898 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001899 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1900 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001901 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1902 return CmpL;
1903}
1904
Matthias Braun96d12512018-11-06 03:15:22 +00001905/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1906/// In some cases this is even possible with OR operations in the expression.
1907/// See \ref AArch64CCMP.
1908/// \see emitConjunctionRec().
1909static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1910 AArch64CC::CondCode &OutCC) {
1911 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001912 bool DummyMustBeFirst;
1913 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001914 return SDValue();
1915
Matthias Braun96d12512018-11-06 03:15:22 +00001916 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001917}
1918
Matthias Braunaf7d7702015-07-16 20:02:37 +00001919/// @}
1920
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001921/// Returns how profitable it is to fold a comparison's operand's shift and/or
1922/// extension operations.
1923static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1924 auto isSupportedExtend = [&](SDValue V) {
1925 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1926 return true;
1927
1928 if (V.getOpcode() == ISD::AND)
1929 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1930 uint64_t Mask = MaskCst->getZExtValue();
1931 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1932 }
1933
1934 return false;
1935 };
1936
1937 if (!Op.hasOneUse())
1938 return 0;
1939
1940 if (isSupportedExtend(Op))
1941 return 1;
1942
1943 unsigned Opc = Op.getOpcode();
1944 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1945 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1946 uint64_t Shift = ShiftCst->getZExtValue();
1947 if (isSupportedExtend(Op.getOperand(0)))
1948 return (Shift <= 4) ? 2 : 1;
1949 EVT VT = Op.getValueType();
1950 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1951 return 1;
1952 }
1953
1954 return 0;
1955}
1956
Tim Northover3b0846e2014-05-24 12:50:23 +00001957static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001958 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001959 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001960 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1961 EVT VT = RHS.getValueType();
1962 uint64_t C = RHSC->getZExtValue();
1963 if (!isLegalArithImmed(C)) {
1964 // Constant does not fit, try adjusting it by one?
1965 switch (CC) {
1966 default:
1967 break;
1968 case ISD::SETLT:
1969 case ISD::SETGE:
1970 if ((VT == MVT::i32 && C != 0x80000000 &&
1971 isLegalArithImmed((uint32_t)(C - 1))) ||
1972 (VT == MVT::i64 && C != 0x80000000ULL &&
1973 isLegalArithImmed(C - 1ULL))) {
1974 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
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::SETULT:
1980 case ISD::SETUGE:
1981 if ((VT == MVT::i32 && C != 0 &&
1982 isLegalArithImmed((uint32_t)(C - 1))) ||
1983 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1984 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1985 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001986 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001987 }
1988 break;
1989 case ISD::SETLE:
1990 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001991 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001992 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001993 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001994 isLegalArithImmed(C + 1ULL))) {
1995 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1996 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001997 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001998 }
1999 break;
2000 case ISD::SETULE:
2001 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00002002 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00002003 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00002004 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00002005 isLegalArithImmed(C + 1ULL))) {
2006 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2007 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002008 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002009 }
2010 break;
2011 }
2012 }
2013 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00002014
2015 // Comparisons are canonicalized so that the RHS operand is simpler than the
2016 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2017 // can fold some shift+extend operations on the RHS operand, so swap the
2018 // operands if that can be done.
2019 //
2020 // For example:
2021 // lsl w13, w11, #1
2022 // cmp w13, w12
2023 // can be turned into:
2024 // cmp w12, w11, lsl #1
2025 if (!isa<ConstantSDNode>(RHS) ||
2026 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2027 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2028
2029 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2030 std::swap(LHS, RHS);
2031 CC = ISD::getSetCCSwappedOperands(CC);
2032 }
2033 }
2034
Matthias Braunaf7d7702015-07-16 20:02:37 +00002035 SDValue Cmp;
2036 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00002037 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002038 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2039
2040 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2041 // For the i8 operand, the largest immediate is 255, so this can be easily
2042 // encoded in the compare instruction. For the i16 operand, however, the
2043 // largest immediate cannot be encoded in the compare.
2044 // Therefore, use a sign extending load and cmn to avoid materializing the
2045 // -1 constant. For example,
2046 // movz w1, #65535
2047 // ldrh w0, [x0, #0]
2048 // cmp w0, w1
2049 // >
2050 // ldrsh w0, [x0, #0]
2051 // cmn w0, #1
2052 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2053 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002054 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00002055 // transformation is profitable.
2056 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2057 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2058 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2059 LHS.getNode()->hasNUsesOfValue(1, 0)) {
2060 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2061 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2062 SDValue SExt =
2063 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2064 DAG.getValueType(MVT::i16));
2065 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2066 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002067 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002068 AArch64CC = changeIntCCToAArch64CC(CC);
2069 }
2070 }
2071
2072 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00002073 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00002074 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2075 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00002076 }
2077 }
2078 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00002079
2080 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00002081 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00002082 AArch64CC = changeIntCCToAArch64CC(CC);
2083 }
2084 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00002085 return Cmp;
2086}
2087
2088static std::pair<SDValue, SDValue>
2089getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2090 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2091 "Unsupported value type");
2092 SDValue Value, Overflow;
2093 SDLoc DL(Op);
2094 SDValue LHS = Op.getOperand(0);
2095 SDValue RHS = Op.getOperand(1);
2096 unsigned Opc = 0;
2097 switch (Op.getOpcode()) {
2098 default:
2099 llvm_unreachable("Unknown overflow instruction!");
2100 case ISD::SADDO:
2101 Opc = AArch64ISD::ADDS;
2102 CC = AArch64CC::VS;
2103 break;
2104 case ISD::UADDO:
2105 Opc = AArch64ISD::ADDS;
2106 CC = AArch64CC::HS;
2107 break;
2108 case ISD::SSUBO:
2109 Opc = AArch64ISD::SUBS;
2110 CC = AArch64CC::VS;
2111 break;
2112 case ISD::USUBO:
2113 Opc = AArch64ISD::SUBS;
2114 CC = AArch64CC::LO;
2115 break;
2116 // Multiply needs a little bit extra work.
2117 case ISD::SMULO:
2118 case ISD::UMULO: {
2119 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002120 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002121 if (Op.getValueType() == MVT::i32) {
2122 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2123 // For a 32 bit multiply with overflow check we want the instruction
2124 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2125 // need to generate the following pattern:
2126 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2127 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2128 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2129 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2130 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002131 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002132 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2133 // operation. We need to clear out the upper 32 bits, because we used a
2134 // widening multiply that wrote all 64 bits. In the end this should be a
2135 // noop.
2136 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2137 if (IsSigned) {
2138 // The signed overflow check requires more than just a simple check for
2139 // any bit set in the upper 32 bits of the result. These bits could be
2140 // just the sign bits of a negative number. To perform the overflow
2141 // check we have to arithmetic shift right the 32nd bit of the result by
2142 // 31 bits. Then we compare the result to the upper 32 bits.
2143 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002144 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002145 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2146 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002147 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002148 // It is important that LowerBits is last, otherwise the arithmetic
2149 // shift will not be folded into the compare (SUBS).
2150 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2151 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2152 .getValue(1);
2153 } else {
2154 // The overflow check for unsigned multiply is easy. We only need to
2155 // check if any of the upper 32 bits are set. This can be done with a
2156 // CMP (shifted register). For that we need to generate the following
2157 // pattern:
2158 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2159 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002160 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002161 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2162 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002163 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2164 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002165 UpperBits).getValue(1);
2166 }
2167 break;
2168 }
2169 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2170 // For the 64 bit multiply
2171 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2172 if (IsSigned) {
2173 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2174 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002175 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002176 // It is important that LowerBits is last, otherwise the arithmetic
2177 // shift will not be folded into the compare (SUBS).
2178 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2179 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2180 .getValue(1);
2181 } else {
2182 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2183 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2184 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002185 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2186 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002187 UpperBits).getValue(1);
2188 }
2189 break;
2190 }
2191 } // switch (...)
2192
2193 if (Opc) {
2194 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2195
2196 // Emit the AArch64 operation with overflow check.
2197 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2198 Overflow = Value.getValue(1);
2199 }
2200 return std::make_pair(Value, Overflow);
2201}
2202
2203SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2204 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002205 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Shiva Chen72a41e72019-08-22 04:59:43 +00002206 MakeLibCallOptions CallOptions;
2207 return makeLibCall(DAG, Call, MVT::f128, Ops, CallOptions, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002208}
2209
Amara Emerson24ca39c2017-10-09 15:15:09 +00002210// Returns true if the given Op is the overflow flag result of an overflow
2211// intrinsic operation.
2212static bool isOverflowIntrOpRes(SDValue Op) {
2213 unsigned Opc = Op.getOpcode();
2214 return (Op.getResNo() == 1 &&
2215 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2216 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2217}
2218
Tim Northover3b0846e2014-05-24 12:50:23 +00002219static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2220 SDValue Sel = Op.getOperand(0);
2221 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002222 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002223
Amara Emerson24ca39c2017-10-09 15:15:09 +00002224 // If the operand is an overflow checking operation, invert the condition
2225 // code and kill the Not operation. I.e., transform:
2226 // (xor (overflow_op_bool, 1))
2227 // -->
2228 // (csel 1, 0, invert(cc), overflow_op_bool)
2229 // ... which later gets transformed to just a cset instruction with an
2230 // inverted condition code, rather than a cset + eor sequence.
2231 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2232 // Only lower legal XALUO ops.
2233 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2234 return SDValue();
2235
2236 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2237 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2238 AArch64CC::CondCode CC;
2239 SDValue Value, Overflow;
2240 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2241 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2242 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2243 CCVal, Overflow);
2244 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002245 // If neither operand is a SELECT_CC, give up.
2246 if (Sel.getOpcode() != ISD::SELECT_CC)
2247 std::swap(Sel, Other);
2248 if (Sel.getOpcode() != ISD::SELECT_CC)
2249 return Op;
2250
2251 // The folding we want to perform is:
2252 // (xor x, (select_cc a, b, cc, 0, -1) )
2253 // -->
2254 // (csel x, (xor x, -1), cc ...)
2255 //
2256 // The latter will get matched to a CSINV instruction.
2257
2258 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2259 SDValue LHS = Sel.getOperand(0);
2260 SDValue RHS = Sel.getOperand(1);
2261 SDValue TVal = Sel.getOperand(2);
2262 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002263
2264 // FIXME: This could be generalized to non-integer comparisons.
2265 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2266 return Op;
2267
2268 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2269 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2270
Eric Christopher572e03a2015-06-19 01:53:21 +00002271 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002272 if (!CFVal || !CTVal)
2273 return Op;
2274
2275 // We can commute the SELECT_CC by inverting the condition. This
2276 // might be needed to make this fit into a CSINV pattern.
2277 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2278 std::swap(TVal, FVal);
2279 std::swap(CTVal, CFVal);
2280 CC = ISD::getSetCCInverse(CC, true);
2281 }
2282
2283 // If the constants line up, perform the transform!
2284 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2285 SDValue CCVal;
2286 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2287
2288 FVal = Other;
2289 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002290 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002291
2292 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2293 CCVal, Cmp);
2294 }
2295
2296 return Op;
2297}
2298
2299static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2300 EVT VT = Op.getValueType();
2301
2302 // Let legalize expand this if it isn't a legal type yet.
2303 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2304 return SDValue();
2305
2306 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2307
2308 unsigned Opc;
2309 bool ExtraOp = false;
2310 switch (Op.getOpcode()) {
2311 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002312 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002313 case ISD::ADDC:
2314 Opc = AArch64ISD::ADDS;
2315 break;
2316 case ISD::SUBC:
2317 Opc = AArch64ISD::SUBS;
2318 break;
2319 case ISD::ADDE:
2320 Opc = AArch64ISD::ADCS;
2321 ExtraOp = true;
2322 break;
2323 case ISD::SUBE:
2324 Opc = AArch64ISD::SBCS;
2325 ExtraOp = true;
2326 break;
2327 }
2328
2329 if (!ExtraOp)
2330 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2331 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2332 Op.getOperand(2));
2333}
2334
2335static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2336 // Let legalize expand this if it isn't a legal type yet.
2337 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2338 return SDValue();
2339
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002340 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002341 AArch64CC::CondCode CC;
2342 // The actual operation that sets the overflow or carry flag.
2343 SDValue Value, Overflow;
2344 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2345
2346 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002347 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2348 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002349
2350 // We use an inverted condition, because the conditional select is inverted
2351 // too. This will allow it to be selected to a single instruction:
2352 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002353 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2354 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002355 CCVal, Overflow);
2356
2357 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002358 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002359}
2360
2361// Prefetch operands are:
2362// 1: Address to prefetch
2363// 2: bool isWrite
2364// 3: int locality (0 = no locality ... 3 = extreme locality)
2365// 4: bool isDataCache
2366static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2367 SDLoc DL(Op);
2368 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2369 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002370 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002371
2372 bool IsStream = !Locality;
2373 // When the locality number is set
2374 if (Locality) {
2375 // The front-end should have filtered out the out-of-range values
2376 assert(Locality <= 3 && "Prefetch locality out-of-range");
2377 // The locality degree is the opposite of the cache speed.
2378 // Put the number the other way around.
2379 // The encoding starts at 0 for level 1
2380 Locality = 3 - Locality;
2381 }
2382
2383 // built the mask value encoding the expected behavior.
2384 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002385 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002386 (Locality << 1) | // Cache level bits
2387 (unsigned)IsStream; // Stream bit
2388 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002389 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002390}
2391
2392SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2393 SelectionDAG &DAG) const {
2394 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2395
2396 RTLIB::Libcall LC;
2397 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2398
2399 return LowerF128Call(Op, DAG, LC);
2400}
2401
2402SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2403 SelectionDAG &DAG) const {
2404 if (Op.getOperand(0).getValueType() != MVT::f128) {
2405 // It's legal except when f128 is involved
2406 return Op;
2407 }
2408
2409 RTLIB::Libcall LC;
2410 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2411
2412 // FP_ROUND node has a second operand indicating whether it is known to be
2413 // precise. That doesn't take part in the LibCall so we can't directly use
2414 // LowerF128Call.
2415 SDValue SrcVal = Op.getOperand(0);
Shiva Chen72a41e72019-08-22 04:59:43 +00002416 MakeLibCallOptions CallOptions;
2417 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, CallOptions,
Craig Topper8fe40e02015-10-22 17:05:00 +00002418 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002419}
2420
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002421SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2422 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002423 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2424 // Any additional optimization in this function should be recorded
2425 // in the cost tables.
2426 EVT InVT = Op.getOperand(0).getValueType();
2427 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002428 unsigned NumElts = InVT.getVectorNumElements();
2429
Abderrazek Zaafrani5ced5962019-03-06 20:30:06 +00002430 // f16 conversions are promoted to f32 when full fp16 is not supported.
2431 if (InVT.getVectorElementType() == MVT::f16 &&
2432 !Subtarget->hasFullFP16()) {
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002433 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2434 SDLoc dl(Op);
2435 return DAG.getNode(
2436 Op.getOpcode(), dl, Op.getValueType(),
2437 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2438 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002439
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002440 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002441 SDLoc dl(Op);
2442 SDValue Cv =
2443 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2444 Op.getOperand(0));
2445 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002446 }
2447
2448 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002449 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002450 MVT ExtVT =
2451 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2452 VT.getVectorNumElements());
2453 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002454 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2455 }
2456
2457 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002458 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002459}
2460
2461SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2462 SelectionDAG &DAG) const {
2463 if (Op.getOperand(0).getValueType().isVector())
2464 return LowerVectorFP_TO_INT(Op, DAG);
2465
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002466 // f16 conversions are promoted to f32 when full fp16 is not supported.
2467 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2468 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002469 SDLoc dl(Op);
2470 return DAG.getNode(
2471 Op.getOpcode(), dl, Op.getValueType(),
2472 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2473 }
2474
Tim Northover3b0846e2014-05-24 12:50:23 +00002475 if (Op.getOperand(0).getValueType() != MVT::f128) {
2476 // It's legal except when f128 is involved
2477 return Op;
2478 }
2479
2480 RTLIB::Libcall LC;
2481 if (Op.getOpcode() == ISD::FP_TO_SINT)
2482 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2483 else
2484 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2485
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002486 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Shiva Chen72a41e72019-08-22 04:59:43 +00002487 MakeLibCallOptions CallOptions;
2488 return makeLibCall(DAG, LC, Op.getValueType(), Ops, CallOptions, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002489}
2490
2491static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2492 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2493 // Any additional optimization in this function should be recorded
2494 // in the cost tables.
2495 EVT VT = Op.getValueType();
2496 SDLoc dl(Op);
2497 SDValue In = Op.getOperand(0);
2498 EVT InVT = In.getValueType();
2499
Tim Northoveref0d7602014-06-15 09:27:06 +00002500 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2501 MVT CastVT =
2502 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2503 InVT.getVectorNumElements());
2504 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002505 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002506 }
2507
Tim Northoveref0d7602014-06-15 09:27:06 +00002508 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2509 unsigned CastOpc =
2510 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2511 EVT CastVT = VT.changeVectorElementTypeToInteger();
2512 In = DAG.getNode(CastOpc, dl, CastVT, In);
2513 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002514 }
2515
Tim Northoveref0d7602014-06-15 09:27:06 +00002516 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002517}
2518
2519SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2520 SelectionDAG &DAG) const {
2521 if (Op.getValueType().isVector())
2522 return LowerVectorINT_TO_FP(Op, DAG);
2523
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002524 // f16 conversions are promoted to f32 when full fp16 is not supported.
2525 if (Op.getValueType() == MVT::f16 &&
2526 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002527 SDLoc dl(Op);
2528 return DAG.getNode(
2529 ISD::FP_ROUND, dl, MVT::f16,
2530 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002531 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002532 }
2533
Tim Northover3b0846e2014-05-24 12:50:23 +00002534 // i128 conversions are libcalls.
2535 if (Op.getOperand(0).getValueType() == MVT::i128)
2536 return SDValue();
2537
2538 // Other conversions are legal, unless it's to the completely software-based
2539 // fp128.
2540 if (Op.getValueType() != MVT::f128)
2541 return Op;
2542
2543 RTLIB::Libcall LC;
2544 if (Op.getOpcode() == ISD::SINT_TO_FP)
2545 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2546 else
2547 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2548
2549 return LowerF128Call(Op, DAG, LC);
2550}
2551
2552SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2553 SelectionDAG &DAG) const {
2554 // For iOS, we want to call an alternative entry point: __sincos_stret,
2555 // which returns the values in two S / D registers.
2556 SDLoc dl(Op);
2557 SDValue Arg = Op.getOperand(0);
2558 EVT ArgVT = Arg.getValueType();
2559 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2560
2561 ArgListTy Args;
2562 ArgListEntry Entry;
2563
2564 Entry.Node = Arg;
2565 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002566 Entry.IsSExt = false;
2567 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002568 Args.push_back(Entry);
2569
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002570 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2571 : RTLIB::SINCOS_STRET_F32;
2572 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002573 SDValue Callee =
2574 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002575
Serge Gueltone38003f2017-05-09 19:31:13 +00002576 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002577 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002578 CLI.setDebugLoc(dl)
2579 .setChain(DAG.getEntryNode())
2580 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002581
2582 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2583 return CallResult.first;
2584}
2585
Tim Northoverf8bfe212014-07-18 13:07:05 +00002586static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2587 if (Op.getValueType() != MVT::f16)
2588 return SDValue();
2589
2590 assert(Op.getOperand(0).getValueType() == MVT::i16);
2591 SDLoc DL(Op);
2592
2593 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2594 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2595 return SDValue(
2596 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002597 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002598 0);
2599}
2600
Chad Rosierd9d0f862014-10-08 02:31:24 +00002601static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2602 if (OrigVT.getSizeInBits() >= 64)
2603 return OrigVT;
2604
2605 assert(OrigVT.isSimple() && "Expecting a simple value type");
2606
2607 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2608 switch (OrigSimpleTy) {
2609 default: llvm_unreachable("Unexpected Vector Type");
2610 case MVT::v2i8:
2611 case MVT::v2i16:
2612 return MVT::v2i32;
2613 case MVT::v4i8:
2614 return MVT::v4i16;
2615 }
2616}
2617
2618static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2619 const EVT &OrigTy,
2620 const EVT &ExtTy,
2621 unsigned ExtOpcode) {
2622 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2623 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2624 // 64-bits we need to insert a new extension so that it will be 64-bits.
2625 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2626 if (OrigTy.getSizeInBits() >= 64)
2627 return N;
2628
2629 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2630 EVT NewVT = getExtensionTo64Bits(OrigTy);
2631
2632 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2633}
2634
2635static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2636 bool isSigned) {
2637 EVT VT = N->getValueType(0);
2638
2639 if (N->getOpcode() != ISD::BUILD_VECTOR)
2640 return false;
2641
Pete Cooper3af9a252015-06-26 18:17:36 +00002642 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002643 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002644 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002645 unsigned HalfSize = EltSize / 2;
2646 if (isSigned) {
2647 if (!isIntN(HalfSize, C->getSExtValue()))
2648 return false;
2649 } else {
2650 if (!isUIntN(HalfSize, C->getZExtValue()))
2651 return false;
2652 }
2653 continue;
2654 }
2655 return false;
2656 }
2657
2658 return true;
2659}
2660
2661static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2662 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2663 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2664 N->getOperand(0)->getValueType(0),
2665 N->getValueType(0),
2666 N->getOpcode());
2667
2668 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2669 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002670 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002671 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002672 unsigned NumElts = VT.getVectorNumElements();
2673 MVT TruncVT = MVT::getIntegerVT(EltSize);
2674 SmallVector<SDValue, 8> Ops;
2675 for (unsigned i = 0; i != NumElts; ++i) {
2676 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2677 const APInt &CInt = C->getAPIntValue();
2678 // Element types smaller than 32 bits are not legal, so use i32 elements.
2679 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002680 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002681 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002682 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002683}
2684
2685static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002686 return N->getOpcode() == ISD::SIGN_EXTEND ||
2687 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002688}
2689
2690static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002691 return N->getOpcode() == ISD::ZERO_EXTEND ||
2692 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002693}
2694
2695static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2696 unsigned Opcode = N->getOpcode();
2697 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2698 SDNode *N0 = N->getOperand(0).getNode();
2699 SDNode *N1 = N->getOperand(1).getNode();
2700 return N0->hasOneUse() && N1->hasOneUse() &&
2701 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2702 }
2703 return false;
2704}
2705
2706static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2707 unsigned Opcode = N->getOpcode();
2708 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2709 SDNode *N0 = N->getOperand(0).getNode();
2710 SDNode *N1 = N->getOperand(1).getNode();
2711 return N0->hasOneUse() && N1->hasOneUse() &&
2712 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2713 }
2714 return false;
2715}
2716
Tim Northover70666e72018-06-20 12:09:01 +00002717SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2718 SelectionDAG &DAG) const {
2719 // The rounding mode is in bits 23:22 of the FPSCR.
2720 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2721 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2722 // so that the shift + and get folded into a bitfield extract.
2723 SDLoc dl(Op);
2724
2725 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2726 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2727 MVT::i64));
2728 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2729 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2730 DAG.getConstant(1U << 22, dl, MVT::i32));
2731 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2732 DAG.getConstant(22, dl, MVT::i32));
2733 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2734 DAG.getConstant(3, dl, MVT::i32));
2735}
2736
Chad Rosierd9d0f862014-10-08 02:31:24 +00002737static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2738 // Multiplications are only custom-lowered for 128-bit vectors so that
2739 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2740 EVT VT = Op.getValueType();
2741 assert(VT.is128BitVector() && VT.isInteger() &&
2742 "unexpected type for custom-lowering ISD::MUL");
2743 SDNode *N0 = Op.getOperand(0).getNode();
2744 SDNode *N1 = Op.getOperand(1).getNode();
2745 unsigned NewOpc = 0;
2746 bool isMLA = false;
2747 bool isN0SExt = isSignExtended(N0, DAG);
2748 bool isN1SExt = isSignExtended(N1, DAG);
2749 if (isN0SExt && isN1SExt)
2750 NewOpc = AArch64ISD::SMULL;
2751 else {
2752 bool isN0ZExt = isZeroExtended(N0, DAG);
2753 bool isN1ZExt = isZeroExtended(N1, DAG);
2754 if (isN0ZExt && isN1ZExt)
2755 NewOpc = AArch64ISD::UMULL;
2756 else if (isN1SExt || isN1ZExt) {
2757 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2758 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2759 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2760 NewOpc = AArch64ISD::SMULL;
2761 isMLA = true;
2762 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2763 NewOpc = AArch64ISD::UMULL;
2764 isMLA = true;
2765 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2766 std::swap(N0, N1);
2767 NewOpc = AArch64ISD::UMULL;
2768 isMLA = true;
2769 }
2770 }
2771
2772 if (!NewOpc) {
2773 if (VT == MVT::v2i64)
2774 // Fall through to expand this. It is not legal.
2775 return SDValue();
2776 else
2777 // Other vector multiplications are legal.
2778 return Op;
2779 }
2780 }
2781
2782 // Legalize to a S/UMULL instruction
2783 SDLoc DL(Op);
2784 SDValue Op0;
2785 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2786 if (!isMLA) {
2787 Op0 = skipExtensionForVectorMULL(N0, DAG);
2788 assert(Op0.getValueType().is64BitVector() &&
2789 Op1.getValueType().is64BitVector() &&
2790 "unexpected types for extended operands to VMULL");
2791 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2792 }
2793 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2794 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2795 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2796 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2797 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2798 EVT Op1VT = Op1.getValueType();
2799 return DAG.getNode(N0->getOpcode(), DL, VT,
2800 DAG.getNode(NewOpc, DL, VT,
2801 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2802 DAG.getNode(NewOpc, DL, VT,
2803 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2804}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002805
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002806SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2807 SelectionDAG &DAG) const {
2808 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2809 SDLoc dl(Op);
2810 switch (IntNo) {
2811 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002812 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002813 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2814 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2815 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002816 case Intrinsic::aarch64_neon_abs: {
2817 EVT Ty = Op.getValueType();
2818 if (Ty == MVT::i64) {
2819 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2820 Op.getOperand(1));
2821 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2822 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2823 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2824 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2825 } else {
2826 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2827 }
2828 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002829 case Intrinsic::aarch64_neon_smax:
2830 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2831 Op.getOperand(1), Op.getOperand(2));
2832 case Intrinsic::aarch64_neon_umax:
2833 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2834 Op.getOperand(1), Op.getOperand(2));
2835 case Intrinsic::aarch64_neon_smin:
2836 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2837 Op.getOperand(1), Op.getOperand(2));
2838 case Intrinsic::aarch64_neon_umin:
2839 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2840 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002841
2842 case Intrinsic::localaddress: {
Mandeep Singh Grang70d484d2019-02-01 21:41:33 +00002843 const auto &MF = DAG.getMachineFunction();
2844 const auto *RegInfo = Subtarget->getRegisterInfo();
2845 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002846 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2847 Op.getSimpleValueType());
2848 }
2849
2850 case Intrinsic::eh_recoverfp: {
2851 // FIXME: This needs to be implemented to correctly handle highly aligned
2852 // stack objects. For now we simply return the incoming FP. Refer D53541
2853 // for more details.
2854 SDValue FnOp = Op.getOperand(1);
2855 SDValue IncomingFPOp = Op.getOperand(2);
2856 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2857 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2858 if (!Fn)
2859 report_fatal_error(
2860 "llvm.eh.recoverfp must take a function as the first argument");
2861 return IncomingFPOp;
2862 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002863 }
2864}
2865
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002866// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2867static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2868 EVT VT, EVT MemVT,
2869 SelectionDAG &DAG) {
2870 assert(VT.isVector() && "VT should be a vector type");
2871 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2872
2873 SDValue Value = ST->getValue();
2874
2875 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2876 // the word lane which represent the v4i8 subvector. It optimizes the store
2877 // to:
2878 //
2879 // xtn v0.8b, v0.8h
2880 // str s0, [x0]
2881
2882 SDValue Undef = DAG.getUNDEF(MVT::i16);
2883 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2884 {Undef, Undef, Undef, Undef});
2885
2886 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2887 Value, UndefVec);
2888 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2889
2890 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2891 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2892 Trunc, DAG.getConstant(0, DL, MVT::i64));
2893
2894 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2895 ST->getBasePtr(), ST->getMemOperand());
2896}
2897
2898// Custom lowering for any store, vector or scalar and/or default or with
2899// a truncate operations. Currently only custom lower truncate operation
2900// from vector v4i16 to v4i8.
2901SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2902 SelectionDAG &DAG) const {
2903 SDLoc Dl(Op);
2904 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2905 assert (StoreNode && "Can only custom lower store nodes");
2906
2907 SDValue Value = StoreNode->getValue();
2908
2909 EVT VT = Value.getValueType();
2910 EVT MemVT = StoreNode->getMemoryVT();
2911
2912 assert (VT.isVector() && "Can only custom lower vector store types");
2913
2914 unsigned AS = StoreNode->getAddressSpace();
2915 unsigned Align = StoreNode->getAlignment();
2916 if (Align < MemVT.getStoreSize() &&
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00002917 !allowsMisalignedMemoryAccesses(
2918 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002919 return scalarizeVectorStore(StoreNode, DAG);
2920 }
2921
2922 if (StoreNode->isTruncatingStore()) {
2923 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2924 }
2925
2926 return SDValue();
2927}
2928
Tim Northover3b0846e2014-05-24 12:50:23 +00002929SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2930 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002931 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2932 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002933
Tim Northover3b0846e2014-05-24 12:50:23 +00002934 switch (Op.getOpcode()) {
2935 default:
2936 llvm_unreachable("unimplemented operand");
2937 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002938 case ISD::BITCAST:
2939 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002940 case ISD::GlobalAddress:
2941 return LowerGlobalAddress(Op, DAG);
2942 case ISD::GlobalTLSAddress:
2943 return LowerGlobalTLSAddress(Op, DAG);
2944 case ISD::SETCC:
2945 return LowerSETCC(Op, DAG);
2946 case ISD::BR_CC:
2947 return LowerBR_CC(Op, DAG);
2948 case ISD::SELECT:
2949 return LowerSELECT(Op, DAG);
2950 case ISD::SELECT_CC:
2951 return LowerSELECT_CC(Op, DAG);
2952 case ISD::JumpTable:
2953 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002954 case ISD::BR_JT:
2955 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002956 case ISD::ConstantPool:
2957 return LowerConstantPool(Op, DAG);
2958 case ISD::BlockAddress:
2959 return LowerBlockAddress(Op, DAG);
2960 case ISD::VASTART:
2961 return LowerVASTART(Op, DAG);
2962 case ISD::VACOPY:
2963 return LowerVACOPY(Op, DAG);
2964 case ISD::VAARG:
2965 return LowerVAARG(Op, DAG);
2966 case ISD::ADDC:
2967 case ISD::ADDE:
2968 case ISD::SUBC:
2969 case ISD::SUBE:
2970 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2971 case ISD::SADDO:
2972 case ISD::UADDO:
2973 case ISD::SSUBO:
2974 case ISD::USUBO:
2975 case ISD::SMULO:
2976 case ISD::UMULO:
2977 return LowerXALUO(Op, DAG);
2978 case ISD::FADD:
2979 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2980 case ISD::FSUB:
2981 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2982 case ISD::FMUL:
2983 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2984 case ISD::FDIV:
2985 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2986 case ISD::FP_ROUND:
2987 return LowerFP_ROUND(Op, DAG);
2988 case ISD::FP_EXTEND:
2989 return LowerFP_EXTEND(Op, DAG);
2990 case ISD::FRAMEADDR:
2991 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002992 case ISD::SPONENTRY:
2993 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002994 case ISD::RETURNADDR:
2995 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002996 case ISD::ADDROFRETURNADDR:
2997 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002998 case ISD::INSERT_VECTOR_ELT:
2999 return LowerINSERT_VECTOR_ELT(Op, DAG);
3000 case ISD::EXTRACT_VECTOR_ELT:
3001 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3002 case ISD::BUILD_VECTOR:
3003 return LowerBUILD_VECTOR(Op, DAG);
3004 case ISD::VECTOR_SHUFFLE:
3005 return LowerVECTOR_SHUFFLE(Op, DAG);
3006 case ISD::EXTRACT_SUBVECTOR:
3007 return LowerEXTRACT_SUBVECTOR(Op, DAG);
3008 case ISD::SRA:
3009 case ISD::SRL:
3010 case ISD::SHL:
3011 return LowerVectorSRA_SRL_SHL(Op, DAG);
3012 case ISD::SHL_PARTS:
3013 return LowerShiftLeftParts(Op, DAG);
3014 case ISD::SRL_PARTS:
3015 case ISD::SRA_PARTS:
3016 return LowerShiftRightParts(Op, DAG);
3017 case ISD::CTPOP:
3018 return LowerCTPOP(Op, DAG);
3019 case ISD::FCOPYSIGN:
3020 return LowerFCOPYSIGN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003021 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00003022 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003023 case ISD::XOR:
3024 return LowerXOR(Op, DAG);
3025 case ISD::PREFETCH:
3026 return LowerPREFETCH(Op, DAG);
3027 case ISD::SINT_TO_FP:
3028 case ISD::UINT_TO_FP:
3029 return LowerINT_TO_FP(Op, DAG);
3030 case ISD::FP_TO_SINT:
3031 case ISD::FP_TO_UINT:
3032 return LowerFP_TO_INT(Op, DAG);
3033 case ISD::FSINCOS:
3034 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00003035 case ISD::FLT_ROUNDS_:
3036 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00003037 case ISD::MUL:
3038 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00003039 case ISD::INTRINSIC_WO_CHAIN:
3040 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00003041 case ISD::STORE:
3042 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00003043 case ISD::VECREDUCE_ADD:
3044 case ISD::VECREDUCE_SMAX:
3045 case ISD::VECREDUCE_SMIN:
3046 case ISD::VECREDUCE_UMAX:
3047 case ISD::VECREDUCE_UMIN:
3048 case ISD::VECREDUCE_FMAX:
3049 case ISD::VECREDUCE_FMIN:
3050 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00003051 case ISD::ATOMIC_LOAD_SUB:
3052 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00003053 case ISD::ATOMIC_LOAD_AND:
3054 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00003055 case ISD::DYNAMIC_STACKALLOC:
3056 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003057 }
3058}
3059
Tim Northover3b0846e2014-05-24 12:50:23 +00003060//===----------------------------------------------------------------------===//
3061// Calling Convention Implementation
3062//===----------------------------------------------------------------------===//
3063
Robin Morisset039781e2014-08-29 21:53:01 +00003064/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00003065CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3066 bool IsVarArg) const {
3067 switch (CC) {
3068 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00003069 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00003070 case CallingConv::WebKit_JS:
3071 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00003072 case CallingConv::GHC:
3073 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00003074 case CallingConv::C:
3075 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00003076 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00003077 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00003078 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00003079 if (Subtarget->isTargetWindows() && IsVarArg)
3080 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00003081 if (!Subtarget->isTargetDarwin())
3082 return CC_AArch64_AAPCS;
Tim Northoverf1c28922019-09-12 10:22:23 +00003083 if (!IsVarArg)
3084 return CC_AArch64_DarwinPCS;
3085 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3086 : CC_AArch64_DarwinPCS_VarArg;
3087 case CallingConv::Win64:
Martin Storsjo2f24e932017-07-17 20:05:19 +00003088 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00003089 case CallingConv::AArch64_VectorCall:
3090 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00003091 }
3092}
3093
Tim Northover406024a2016-08-10 21:44:01 +00003094CCAssignFn *
3095AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3096 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3097 : RetCC_AArch64_AAPCS;
3098}
3099
Tim Northover3b0846e2014-05-24 12:50:23 +00003100SDValue AArch64TargetLowering::LowerFormalArguments(
3101 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003102 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3103 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003104 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003105 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003106 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003107
3108 // Assign locations to all of the incoming arguments.
3109 SmallVector<CCValAssign, 16> ArgLocs;
Tim Northoverf1c28922019-09-12 10:22:23 +00003110 DenseMap<unsigned, SDValue> CopiedRegs;
Eric Christopherb5217502014-08-06 18:45:26 +00003111 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3112 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003113
3114 // At this point, Ins[].VT may already be promoted to i32. To correctly
3115 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3116 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3117 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3118 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3119 // LocVT.
3120 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003121 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003122 unsigned CurArgIdx = 0;
3123 for (unsigned i = 0; i != NumArgs; ++i) {
3124 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003125 if (Ins[i].isOrigArg()) {
3126 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3127 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003128
Andrew Trick05938a52015-02-16 18:10:47 +00003129 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003130 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3131 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003132 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3133 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3134 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3135 ValVT = MVT::i8;
3136 else if (ActualMVT == MVT::i16)
3137 ValVT = MVT::i16;
3138 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003139 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3140 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003141 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003142 assert(!Res && "Call operand has unhandled type");
3143 (void)Res;
3144 }
3145 assert(ArgLocs.size() == Ins.size());
3146 SmallVector<SDValue, 16> ArgValues;
3147 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3148 CCValAssign &VA = ArgLocs[i];
3149
3150 if (Ins[i].Flags.isByVal()) {
3151 // Byval is used for HFAs in the PCS, but the system should work in a
3152 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003153 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003154 int Size = Ins[i].Flags.getByValSize();
3155 unsigned NumRegs = (Size + 7) / 8;
3156
3157 // FIXME: This works on big-endian for composite byvals, which are the common
3158 // case. It should also work for fundamental types too.
3159 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003160 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003161 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003162 InVals.push_back(FrameIdxN);
3163
3164 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003165 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003166
Tim Northoverf1c28922019-09-12 10:22:23 +00003167 SDValue ArgValue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003168 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003169 // Arguments stored in registers.
3170 EVT RegVT = VA.getLocVT();
Tim Northover3b0846e2014-05-24 12:50:23 +00003171 const TargetRegisterClass *RC;
3172
3173 if (RegVT == MVT::i32)
3174 RC = &AArch64::GPR32RegClass;
3175 else if (RegVT == MVT::i64)
3176 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003177 else if (RegVT == MVT::f16)
3178 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003179 else if (RegVT == MVT::f32)
3180 RC = &AArch64::FPR32RegClass;
3181 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3182 RC = &AArch64::FPR64RegClass;
3183 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3184 RC = &AArch64::FPR128RegClass;
Cullen Rhodes2a481762019-08-05 13:44:10 +00003185 else if (RegVT.isScalableVector() &&
3186 RegVT.getVectorElementType() == MVT::i1)
3187 RC = &AArch64::PPRRegClass;
3188 else if (RegVT.isScalableVector())
3189 RC = &AArch64::ZPRRegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003190 else
3191 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3192
3193 // Transform the arguments in physical registers into virtual ones.
3194 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3195 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3196
3197 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3198 // to 64 bits. Insert an assert[sz]ext to capture this, then
3199 // truncate to the right size.
3200 switch (VA.getLocInfo()) {
3201 default:
3202 llvm_unreachable("Unknown loc info!");
3203 case CCValAssign::Full:
3204 break;
Cullen Rhodes2a481762019-08-05 13:44:10 +00003205 case CCValAssign::Indirect:
3206 assert(VA.getValVT().isScalableVector() &&
3207 "Only scalable vectors can be passed indirectly");
3208 llvm_unreachable("Spilling of SVE vectors not yet implemented");
Tim Northover3b0846e2014-05-24 12:50:23 +00003209 case CCValAssign::BCvt:
3210 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3211 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003212 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003213 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003214 case CCValAssign::ZExt:
Tim Northoverf1c28922019-09-12 10:22:23 +00003215 break;
3216 case CCValAssign::AExtUpper:
3217 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3218 DAG.getConstant(32, DL, RegVT));
3219 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
Tim Northover3b0846e2014-05-24 12:50:23 +00003220 break;
3221 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003222 } else { // VA.isRegLoc()
3223 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3224 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003225 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003226
3227 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003228 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3229 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003230 BEAlign = 8 - ArgSize;
3231
Matthias Braun941a7052016-07-28 18:40:00 +00003232 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003233
3234 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003235 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003236
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003237 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003238 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003239 MVT MemVT = VA.getValVT();
3240
Tim Northover47e003c2014-05-26 17:21:53 +00003241 switch (VA.getLocInfo()) {
3242 default:
3243 break;
Tim Northoverf1c28922019-09-12 10:22:23 +00003244 case CCValAssign::Trunc:
Tim Northover6890add2014-06-03 13:54:53 +00003245 case CCValAssign::BCvt:
3246 MemVT = VA.getLocVT();
3247 break;
Cullen Rhodes2a481762019-08-05 13:44:10 +00003248 case CCValAssign::Indirect:
3249 assert(VA.getValVT().isScalableVector() &&
3250 "Only scalable vectors can be passed indirectly");
3251 llvm_unreachable("Spilling of SVE vectors not yet implemented");
Tim Northover47e003c2014-05-26 17:21:53 +00003252 case CCValAssign::SExt:
3253 ExtType = ISD::SEXTLOAD;
3254 break;
3255 case CCValAssign::ZExt:
3256 ExtType = ISD::ZEXTLOAD;
3257 break;
3258 case CCValAssign::AExt:
3259 ExtType = ISD::EXTLOAD;
3260 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003261 }
3262
Alex Lorenze40c8a22015-08-11 23:09:45 +00003263 ArgValue = DAG.getExtLoad(
3264 ExtType, DL, VA.getLocVT(), Chain, FIN,
3265 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003266 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003267
Tim Northover3b0846e2014-05-24 12:50:23 +00003268 }
Tim Northoverf1c28922019-09-12 10:22:23 +00003269 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3270 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3271 ArgValue, DAG.getValueType(MVT::i32));
3272 InVals.push_back(ArgValue);
Tim Northover3b0846e2014-05-24 12:50:23 +00003273 }
3274
3275 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003276 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003277 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003278 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003279 // The AAPCS variadic function ABI is identical to the non-variadic
3280 // one. As a result there may be more arguments in registers and we should
3281 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003282 // Win64 variadic functions also pass arguments in registers, but all float
3283 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003284 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3285 }
3286
Tim Northover3b0846e2014-05-24 12:50:23 +00003287 // This will point to the next argument passed via stack.
3288 unsigned StackOffset = CCInfo.getNextStackOffset();
Tim Northoverf1c28922019-09-12 10:22:23 +00003289 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3290 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
Matthias Braun941a7052016-07-28 18:40:00 +00003291 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003292
3293 if (MFI.hasMustTailInVarArgFunc()) {
3294 SmallVector<MVT, 2> RegParmTypes;
3295 RegParmTypes.push_back(MVT::i64);
3296 RegParmTypes.push_back(MVT::f128);
3297 // Compute the set of forwarded registers. The rest are scratch.
3298 SmallVectorImpl<ForwardedRegister> &Forwards =
3299 FuncInfo->getForwardedMustTailRegParms();
3300 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3301 CC_AArch64_AAPCS);
Reid Klecknerb7a78c72019-05-24 01:27:20 +00003302
3303 // Conservatively forward X8, since it might be used for aggregate return.
3304 if (!CCInfo.isAllocated(AArch64::X8)) {
3305 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3306 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3307 }
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003308 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003309 }
3310
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003311 // On Windows, InReg pointers must be returned, so record the pointer in a
3312 // virtual register at the start of the function so it can be returned in the
3313 // epilogue.
3314 if (IsWin64) {
3315 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3316 if (Ins[I].Flags.isInReg()) {
3317 assert(!FuncInfo->getSRetReturnReg());
3318
3319 MVT PtrTy = getPointerTy(DAG.getDataLayout());
Daniel Sanders5ae66e52019-08-12 22:40:53 +00003320 Register Reg =
3321 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003322 FuncInfo->setSRetReturnReg(Reg);
3323
3324 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3325 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3326 break;
3327 }
3328 }
3329 }
3330
Tim Northover3b0846e2014-05-24 12:50:23 +00003331 unsigned StackArgSize = CCInfo.getNextStackOffset();
3332 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3333 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3334 // This is a non-standard ABI so by fiat I say we're allowed to make full
3335 // use of the stack area to be popped, which must be aligned to 16 bytes in
3336 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003337 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003338
3339 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3340 // a multiple of 16.
3341 FuncInfo->setArgumentStackToRestore(StackArgSize);
3342
3343 // This realignment carries over to the available bytes below. Our own
3344 // callers will guarantee the space is free by giving an aligned value to
3345 // CALLSEQ_START.
3346 }
3347 // Even if we're not expected to free up the space, it's useful to know how
3348 // much is there while considering tail calls (because we can reuse it).
3349 FuncInfo->setBytesInStackArgArea(StackArgSize);
3350
Tri Vo6c47c622018-09-22 22:17:50 +00003351 if (Subtarget->hasCustomCallingConv())
3352 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3353
Tim Northover3b0846e2014-05-24 12:50:23 +00003354 return Chain;
3355}
3356
3357void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003358 SelectionDAG &DAG,
3359 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003360 SDValue &Chain) const {
3361 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003362 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003363 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003364 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003365 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003366
3367 SmallVector<SDValue, 8> MemOps;
3368
3369 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3370 AArch64::X3, AArch64::X4, AArch64::X5,
3371 AArch64::X6, AArch64::X7 };
3372 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003373 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003374
3375 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3376 int GPRIdx = 0;
3377 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003378 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003379 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003380 if (GPRSaveSize & 15)
3381 // The extra size here, if triggered, will always be 8.
3382 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3383 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003384 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003385
Mehdi Amini44ede332015-07-09 02:09:04 +00003386 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003387
3388 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3389 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3390 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003391 SDValue Store = DAG.getStore(
3392 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003393 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003394 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3395 GPRIdx,
3396 (i - FirstVariadicGPR) * 8)
3397 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003398 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003399 FIN =
3400 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003401 }
3402 }
3403 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3404 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3405
Martin Storsjo2f24e932017-07-17 20:05:19 +00003406 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003407 static const MCPhysReg FPRArgRegs[] = {
3408 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3409 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3410 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003411 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003412
3413 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3414 int FPRIdx = 0;
3415 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003416 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003417
Mehdi Amini44ede332015-07-09 02:09:04 +00003418 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003419
3420 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3421 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3422 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3423
Alex Lorenze40c8a22015-08-11 23:09:45 +00003424 SDValue Store = DAG.getStore(
3425 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003426 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003427 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003428 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3429 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003430 }
3431 }
3432 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3433 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3434 }
3435
3436 if (!MemOps.empty()) {
3437 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3438 }
3439}
3440
3441/// LowerCallResult - Lower the result values of a call into the
3442/// appropriate copies out of appropriate physical registers.
3443SDValue AArch64TargetLowering::LowerCallResult(
3444 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003445 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3446 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003447 SDValue ThisVal) const {
3448 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3449 ? RetCC_AArch64_WebKit_JS
3450 : RetCC_AArch64_AAPCS;
3451 // Assign locations to each value returned by this call.
3452 SmallVector<CCValAssign, 16> RVLocs;
Tim Northoverf1c28922019-09-12 10:22:23 +00003453 DenseMap<unsigned, SDValue> CopiedRegs;
Eric Christopherb5217502014-08-06 18:45:26 +00003454 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3455 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003456 CCInfo.AnalyzeCallResult(Ins, RetCC);
3457
3458 // Copy all of the result registers out of their specified physreg.
3459 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3460 CCValAssign VA = RVLocs[i];
3461
3462 // Pass 'this' value directly from the argument to return value, to avoid
3463 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003464 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003465 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3466 "unexpected return calling convention register assignment");
3467 InVals.push_back(ThisVal);
3468 continue;
3469 }
3470
Tim Northoverf1c28922019-09-12 10:22:23 +00003471 // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3472 // allows one use of a physreg per block.
3473 SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3474 if (!Val) {
3475 Val =
3476 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3477 Chain = Val.getValue(1);
3478 InFlag = Val.getValue(2);
3479 CopiedRegs[VA.getLocReg()] = Val;
3480 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003481
3482 switch (VA.getLocInfo()) {
3483 default:
3484 llvm_unreachable("Unknown loc info!");
3485 case CCValAssign::Full:
3486 break;
3487 case CCValAssign::BCvt:
3488 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3489 break;
Tim Northoverf1c28922019-09-12 10:22:23 +00003490 case CCValAssign::AExtUpper:
3491 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3492 DAG.getConstant(32, DL, VA.getLocVT()));
3493 LLVM_FALLTHROUGH;
3494 case CCValAssign::AExt:
3495 LLVM_FALLTHROUGH;
3496 case CCValAssign::ZExt:
3497 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3498 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003499 }
3500
3501 InVals.push_back(Val);
3502 }
3503
3504 return Chain;
3505}
3506
Matthias Braun1af14142016-09-13 19:27:38 +00003507/// Return true if the calling convention is one that we can guarantee TCO for.
3508static bool canGuaranteeTCO(CallingConv::ID CC) {
3509 return CC == CallingConv::Fast;
3510}
3511
3512/// Return true if we might ever do TCO for calls with this calling convention.
3513static bool mayTailCallThisCC(CallingConv::ID CC) {
3514 switch (CC) {
3515 case CallingConv::C:
3516 case CallingConv::PreserveMost:
3517 case CallingConv::Swift:
3518 return true;
3519 default:
3520 return canGuaranteeTCO(CC);
3521 }
3522}
3523
Tim Northover3b0846e2014-05-24 12:50:23 +00003524bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3525 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003526 const SmallVectorImpl<ISD::OutputArg> &Outs,
3527 const SmallVectorImpl<SDValue> &OutVals,
3528 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003529 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003530 return false;
3531
Matthias Braun8d414362016-03-30 22:46:04 +00003532 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003533 const Function &CallerF = MF.getFunction();
3534 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003535 bool CCMatch = CallerCC == CalleeCC;
3536
3537 // Byval parameters hand the function a pointer directly into the stack area
3538 // we want to reuse during a tail call. Working around this *is* possible (see
3539 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003540 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3541 e = CallerF.arg_end();
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003542 i != e; ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003543 if (i->hasByValAttr())
3544 return false;
3545
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00003546 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3547 // In this case, it is necessary to save/restore X0 in the callee. Tail
3548 // call opt interferes with this. So we disable tail call opt when the
3549 // caller has an argument with "inreg" attribute.
3550
3551 // FIXME: Check whether the callee also has an "inreg" argument.
3552 if (i->hasInRegAttr())
3553 return false;
3554 }
3555
Matthias Braun1af14142016-09-13 19:27:38 +00003556 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3557 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003558
Oliver Stannard12993dd2014-08-18 12:42:15 +00003559 // Externally-defined functions with weak linkage should not be
3560 // tail-called on AArch64 when the OS does not support dynamic
3561 // pre-emption of symbols, as the AAELF spec requires normal calls
3562 // to undefined weak functions to be replaced with a NOP or jump to the
3563 // next instruction. The behaviour of branch instructions in this
3564 // situation (as used for tail calls) is implementation-defined, so we
3565 // cannot rely on the linker replacing the tail call with a return.
3566 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3567 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003568 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003569 if (GV->hasExternalWeakLinkage() &&
3570 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003571 return false;
3572 }
3573
Tim Northover3b0846e2014-05-24 12:50:23 +00003574 // Now we search for cases where we can use a tail call without changing the
3575 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3576 // concept.
3577
3578 // I want anyone implementing a new calling convention to think long and hard
3579 // about this assert.
3580 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3581 "Unexpected variadic calling convention");
3582
Matthias Braun8d414362016-03-30 22:46:04 +00003583 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003584 if (isVarArg && !Outs.empty()) {
3585 // At least two cases here: if caller is fastcc then we can't have any
3586 // memory arguments (we'd be expected to clean up the stack afterwards). If
3587 // caller is C then we could potentially use its argument area.
3588
3589 // FIXME: for now we take the most conservative of these in both cases:
3590 // disallow all variadic memory operands.
3591 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003592 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003593
3594 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003595 for (const CCValAssign &ArgLoc : ArgLocs)
3596 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003597 return false;
3598 }
3599
Matthias Braun8d414362016-03-30 22:46:04 +00003600 // Check that the call results are passed in the same way.
3601 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3602 CCAssignFnForCall(CalleeCC, isVarArg),
3603 CCAssignFnForCall(CallerCC, isVarArg)))
3604 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003605 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003606 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3607 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003608 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003609 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003610 if (Subtarget->hasCustomCallingConv()) {
3611 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3612 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3613 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003614 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003615 return false;
3616 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003617
3618 // Nothing more to check if the callee is taking no arguments
3619 if (Outs.empty())
3620 return true;
3621
3622 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003623 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003624
3625 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3626
3627 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3628
Matthias Braun74a0bd32016-04-13 21:43:16 +00003629 // If the stack arguments for this call do not fit into our own save area then
3630 // the call cannot be made tail.
3631 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3632 return false;
3633
Matthias Braun46b0f032016-04-14 01:10:42 +00003634 const MachineRegisterInfo &MRI = MF.getRegInfo();
3635 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3636 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003637
3638 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003639}
3640
3641SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3642 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003643 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003644 int ClobberedFI) const {
3645 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003646 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3647 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003648
3649 // Include the original chain at the beginning of the list. When this is
3650 // used by target LowerCall hooks, this helps legalize find the
3651 // CALLSEQ_BEGIN node.
3652 ArgChains.push_back(Chain);
3653
3654 // Add a chain value for each stack argument corresponding
3655 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3656 UE = DAG.getEntryNode().getNode()->use_end();
3657 U != UE; ++U)
3658 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3659 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3660 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003661 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003662 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003663 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003664
3665 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3666 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3667 ArgChains.push_back(SDValue(L, 1));
3668 }
3669
3670 // Build a tokenfactor for all the chains.
3671 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3672}
3673
3674bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3675 bool TailCallOpt) const {
3676 return CallCC == CallingConv::Fast && TailCallOpt;
3677}
3678
Tim Northover3b0846e2014-05-24 12:50:23 +00003679/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3680/// and add input and output parameter nodes.
3681SDValue
3682AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3683 SmallVectorImpl<SDValue> &InVals) const {
3684 SelectionDAG &DAG = CLI.DAG;
3685 SDLoc &DL = CLI.DL;
3686 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3687 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3688 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3689 SDValue Chain = CLI.Chain;
3690 SDValue Callee = CLI.Callee;
3691 bool &IsTailCall = CLI.IsTailCall;
3692 CallingConv::ID CallConv = CLI.CallConv;
3693 bool IsVarArg = CLI.IsVarArg;
3694
3695 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003696 bool IsThisReturn = false;
3697
3698 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3699 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3700 bool IsSibCall = false;
3701
3702 if (IsTailCall) {
3703 // Check if it's really possible to do a tail call.
3704 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003705 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003706 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003707 report_fatal_error("failed to perform tail call elimination on a call "
3708 "site marked musttail");
3709
3710 // A sibling call is one where we're under the usual C ABI and not planning
3711 // to change that but can still do a tail call:
3712 if (!TailCallOpt && IsTailCall)
3713 IsSibCall = true;
3714
3715 if (IsTailCall)
3716 ++NumTailCalls;
3717 }
3718
3719 // Analyze operands of the call, assigning locations to each operand.
3720 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003721 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3722 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003723
3724 if (IsVarArg) {
3725 // Handle fixed and variable vector arguments differently.
3726 // Variable vector arguments always go into memory.
3727 unsigned NumArgs = Outs.size();
3728
3729 for (unsigned i = 0; i != NumArgs; ++i) {
3730 MVT ArgVT = Outs[i].VT;
3731 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3732 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3733 /*IsVarArg=*/ !Outs[i].IsFixed);
3734 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3735 assert(!Res && "Call operand has unhandled type");
3736 (void)Res;
3737 }
3738 } else {
3739 // At this point, Outs[].VT may already be promoted to i32. To correctly
3740 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3741 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3742 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3743 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3744 // LocVT.
3745 unsigned NumArgs = Outs.size();
3746 for (unsigned i = 0; i != NumArgs; ++i) {
3747 MVT ValVT = Outs[i].VT;
3748 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003749 EVT ActualVT = getValueType(DAG.getDataLayout(),
3750 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003751 /*AllowUnknown*/ true);
3752 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3753 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3754 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003755 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003756 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003757 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003758 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003759
3760 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003761 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003762 assert(!Res && "Call operand has unhandled type");
3763 (void)Res;
3764 }
3765 }
3766
3767 // Get a count of how many bytes are to be pushed on the stack.
3768 unsigned NumBytes = CCInfo.getNextStackOffset();
3769
3770 if (IsSibCall) {
3771 // Since we're not changing the ABI to make this a tail call, the memory
3772 // operands are already available in the caller's incoming argument space.
3773 NumBytes = 0;
3774 }
3775
3776 // FPDiff is the byte offset of the call's argument area from the callee's.
3777 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3778 // by this amount for a tail call. In a sibling call it must be 0 because the
3779 // caller will deallocate the entire stack and the callee still expects its
3780 // arguments to begin at SP+0. Completely unused for non-tail calls.
3781 int FPDiff = 0;
3782
3783 if (IsTailCall && !IsSibCall) {
3784 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3785
3786 // Since callee will pop argument stack as a tail call, we must keep the
3787 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003788 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003789
3790 // FPDiff will be negative if this tail call requires more space than we
3791 // would automatically have in our incoming argument space. Positive if we
3792 // can actually shrink the stack.
3793 FPDiff = NumReusableBytes - NumBytes;
3794
3795 // The stack pointer must be 16-byte aligned at all times it's used for a
3796 // memory operation, which in practice means at *all* times and in
3797 // particular across call boundaries. Therefore our own arguments started at
3798 // a 16-byte aligned SP and the delta applied for the tail call should
3799 // satisfy the same constraint.
3800 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3801 }
3802
3803 // Adjust the stack pointer for the new arguments...
3804 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003805 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003806 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003807
Mehdi Amini44ede332015-07-09 02:09:04 +00003808 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3809 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003810
3811 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
Tim Northoverf1c28922019-09-12 10:22:23 +00003812 SmallSet<unsigned, 8> RegsUsed;
Tim Northover3b0846e2014-05-24 12:50:23 +00003813 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003814 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003815
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003816 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3817 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3818 for (const auto &F : Forwards) {
3819 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
Tim Northoverf1c28922019-09-12 10:22:23 +00003820 RegsToPass.emplace_back(F.PReg, Val);
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003821 }
3822 }
3823
Tim Northover3b0846e2014-05-24 12:50:23 +00003824 // Walk the register/memloc assignments, inserting copies/loads.
3825 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3826 ++i, ++realArgIdx) {
3827 CCValAssign &VA = ArgLocs[i];
3828 SDValue Arg = OutVals[realArgIdx];
3829 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3830
3831 // Promote the value if needed.
3832 switch (VA.getLocInfo()) {
3833 default:
3834 llvm_unreachable("Unknown loc info!");
3835 case CCValAssign::Full:
3836 break;
3837 case CCValAssign::SExt:
3838 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3839 break;
3840 case CCValAssign::ZExt:
3841 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3842 break;
3843 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003844 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3845 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3846 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3847 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3848 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003849 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3850 break;
Tim Northoverf1c28922019-09-12 10:22:23 +00003851 case CCValAssign::AExtUpper:
3852 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
3853 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3854 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
3855 DAG.getConstant(32, DL, VA.getLocVT()));
3856 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003857 case CCValAssign::BCvt:
Tim Northoverf1c28922019-09-12 10:22:23 +00003858 Arg = DAG.getBitcast(VA.getLocVT(), Arg);
3859 break;
3860 case CCValAssign::Trunc:
3861 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
Tim Northover3b0846e2014-05-24 12:50:23 +00003862 break;
3863 case CCValAssign::FPExt:
3864 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3865 break;
Cullen Rhodes2a481762019-08-05 13:44:10 +00003866 case CCValAssign::Indirect:
3867 assert(VA.getValVT().isScalableVector() &&
3868 "Only scalable vectors can be passed indirectly");
3869 llvm_unreachable("Spilling of SVE vectors not yet implemented");
Tim Northover3b0846e2014-05-24 12:50:23 +00003870 }
3871
3872 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003873 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3874 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003875 assert(VA.getLocVT() == MVT::i64 &&
3876 "unexpected calling convention register assignment");
3877 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3878 "unexpected use of 'returned'");
3879 IsThisReturn = true;
3880 }
Tim Northoverf1c28922019-09-12 10:22:23 +00003881 if (RegsUsed.count(VA.getLocReg())) {
3882 // If this register has already been used then we're trying to pack
3883 // parts of an [N x i32] into an X-register. The extension type will
3884 // take care of putting the two halves in the right place but we have to
3885 // combine them.
3886 SDValue &Bits =
3887 std::find_if(RegsToPass.begin(), RegsToPass.end(),
3888 [=](const std::pair<unsigned, SDValue> &Elt) {
3889 return Elt.first == VA.getLocReg();
3890 })
3891 ->second;
3892 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
3893 } else {
3894 RegsToPass.emplace_back(VA.getLocReg(), Arg);
3895 RegsUsed.insert(VA.getLocReg());
3896 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003897 } else {
3898 assert(VA.isMemLoc());
3899
3900 SDValue DstAddr;
3901 MachinePointerInfo DstInfo;
3902
3903 // FIXME: This works on big-endian for composite byvals, which are the
3904 // common case. It should also work for fundamental types too.
3905 uint32_t BEAlign = 0;
3906 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003907 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003908 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003909 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3910 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003911 if (OpSize < 8)
3912 BEAlign = 8 - OpSize;
3913 }
3914 unsigned LocMemOffset = VA.getLocMemOffset();
3915 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003916 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003917 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003918
3919 if (IsTailCall) {
3920 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003921 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003922
Mehdi Amini44ede332015-07-09 02:09:04 +00003923 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003924 DstInfo =
3925 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003926
3927 // Make sure any stack arguments overlapping with where we're storing
3928 // are loaded before this eventual operation. Otherwise they'll be
3929 // clobbered.
3930 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3931 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003932 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003933
Mehdi Amini44ede332015-07-09 02:09:04 +00003934 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003935 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3936 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003937 }
3938
3939 if (Outs[i].Flags.isByVal()) {
3940 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003941 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003942 SDValue Cpy = DAG.getMemcpy(
3943 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003944 /*isVol = */ false, /*AlwaysInline = */ false,
3945 /*isTailCall = */ false,
3946 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003947
3948 MemOpChains.push_back(Cpy);
3949 } else {
3950 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3951 // promoted to a legal register type i32, we should truncate Arg back to
3952 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003953 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3954 VA.getValVT() == MVT::i16)
3955 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003956
Justin Lebar9c375812016-07-15 18:27:10 +00003957 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003958 MemOpChains.push_back(Store);
3959 }
3960 }
3961 }
3962
3963 if (!MemOpChains.empty())
3964 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3965
3966 // Build a sequence of copy-to-reg nodes chained together with token chain
3967 // and flag operands which copy the outgoing args into the appropriate regs.
3968 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003969 for (auto &RegToPass : RegsToPass) {
3970 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3971 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003972 InFlag = Chain.getValue(1);
3973 }
3974
3975 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3976 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3977 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003978 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3979 auto GV = G->getGlobal();
3980 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3981 AArch64II::MO_GOT) {
3982 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3983 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003984 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3985 assert(Subtarget->isTargetWindows() &&
3986 "Windows is the only supported COFF target");
3987 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003988 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003989 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003990 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3991 }
3992 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3993 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3994 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003995 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003996 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3997 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003998 } else {
3999 const char *Sym = S->getSymbol();
4000 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004001 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004002 }
4003
4004 // We don't usually want to end the call-sequence here because we would tidy
4005 // the frame up *after* the call, however in the ABI-changing tail-call case
4006 // we've carefully laid out the parameters so that when sp is reset they'll be
4007 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00004008 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004009 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4010 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00004011 InFlag = Chain.getValue(1);
4012 }
4013
4014 std::vector<SDValue> Ops;
4015 Ops.push_back(Chain);
4016 Ops.push_back(Callee);
4017
4018 if (IsTailCall) {
4019 // Each tail call may have to adjust the stack by a different amount, so
4020 // this information must travel along with the operation for eventual
4021 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004022 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004023 }
4024
4025 // Add argument registers to the end of the list so that they are known live
4026 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00004027 for (auto &RegToPass : RegsToPass)
4028 Ops.push_back(DAG.getRegister(RegToPass.first,
4029 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004030
Cullen Rhodes2a481762019-08-05 13:44:10 +00004031 // Check callee args/returns for SVE registers and set calling convention
4032 // accordingly.
4033 if (CallConv == CallingConv::C) {
4034 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4035 return Out.VT.isScalableVector();
4036 });
4037 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4038 return In.VT.isScalableVector();
4039 });
4040
4041 if (CalleeInSVE || CalleeOutSVE)
4042 CallConv = CallingConv::AArch64_SVE_VectorCall;
4043 }
4044
Tim Northover3b0846e2014-05-24 12:50:23 +00004045 // Add a register mask operand representing the call-preserved registers.
4046 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00004047 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00004048 if (IsThisReturn) {
4049 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00004050 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00004051 if (!Mask) {
4052 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00004053 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00004054 }
4055 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00004056 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00004057
Tri Vo6c47c622018-09-22 22:17:50 +00004058 if (Subtarget->hasCustomCallingConv())
4059 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4060
Nick Desaulniers287a3be2018-09-07 20:58:57 +00004061 if (TRI->isAnyArgRegReserved(MF))
4062 TRI->emitReservedArgRegCallError(MF);
4063
Tim Northover3b0846e2014-05-24 12:50:23 +00004064 assert(Mask && "Missing call preserved mask for calling convention");
4065 Ops.push_back(DAG.getRegisterMask(Mask));
4066
4067 if (InFlag.getNode())
4068 Ops.push_back(InFlag);
4069
4070 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4071
4072 // If we're doing a tall call, use a TC_RETURN here rather than an
4073 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00004074 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00004075 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00004076 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00004077 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004078
4079 // Returns a chain and a flag for retval copy to use.
4080 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4081 InFlag = Chain.getValue(1);
4082
Rui Ueyamada00f2f2016-01-14 21:06:47 +00004083 uint64_t CalleePopBytes =
4084 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004085
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00004086 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4087 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4088 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00004089 if (!Ins.empty())
4090 InFlag = Chain.getValue(1);
4091
4092 // Handle result values, copying them out of physregs into vregs that we
4093 // return.
4094 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4095 InVals, IsThisReturn,
4096 IsThisReturn ? OutVals[0] : SDValue());
4097}
4098
4099bool AArch64TargetLowering::CanLowerReturn(
4100 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4101 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4102 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4103 ? RetCC_AArch64_WebKit_JS
4104 : RetCC_AArch64_AAPCS;
4105 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00004106 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00004107 return CCInfo.CheckReturn(Outs, RetCC);
4108}
4109
4110SDValue
4111AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4112 bool isVarArg,
4113 const SmallVectorImpl<ISD::OutputArg> &Outs,
4114 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004115 const SDLoc &DL, SelectionDAG &DAG) const {
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00004116 auto &MF = DAG.getMachineFunction();
4117 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4118
Tim Northover3b0846e2014-05-24 12:50:23 +00004119 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4120 ? RetCC_AArch64_WebKit_JS
4121 : RetCC_AArch64_AAPCS;
4122 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00004123 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4124 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00004125 CCInfo.AnalyzeReturn(Outs, RetCC);
4126
4127 // Copy the result values into the output registers.
4128 SDValue Flag;
Tim Northoverf1c28922019-09-12 10:22:23 +00004129 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4130 SmallSet<unsigned, 4> RegsUsed;
Tim Northover3b0846e2014-05-24 12:50:23 +00004131 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4132 ++i, ++realRVLocIdx) {
4133 CCValAssign &VA = RVLocs[i];
4134 assert(VA.isRegLoc() && "Can only return in registers!");
4135 SDValue Arg = OutVals[realRVLocIdx];
4136
4137 switch (VA.getLocInfo()) {
4138 default:
4139 llvm_unreachable("Unknown loc info!");
4140 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00004141 if (Outs[i].ArgVT == MVT::i1) {
4142 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4143 // value. This is strictly redundant on Darwin (which uses "zeroext
4144 // i1"), but will be optimised out before ISel.
4145 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4146 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4147 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004148 break;
4149 case CCValAssign::BCvt:
4150 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4151 break;
Tim Northoverf1c28922019-09-12 10:22:23 +00004152 case CCValAssign::AExt:
4153 case CCValAssign::ZExt:
4154 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4155 break;
4156 case CCValAssign::AExtUpper:
4157 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4158 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4159 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4160 DAG.getConstant(32, DL, VA.getLocVT()));
4161 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00004162 }
4163
Tim Northoverf1c28922019-09-12 10:22:23 +00004164 if (RegsUsed.count(VA.getLocReg())) {
4165 SDValue &Bits =
4166 std::find_if(RetVals.begin(), RetVals.end(),
4167 [=](const std::pair<unsigned, SDValue> &Elt) {
4168 return Elt.first == VA.getLocReg();
4169 })
4170 ->second;
4171 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4172 } else {
4173 RetVals.emplace_back(VA.getLocReg(), Arg);
4174 RegsUsed.insert(VA.getLocReg());
4175 }
4176 }
4177
4178 SmallVector<SDValue, 4> RetOps(1, Chain);
4179 for (auto &RetVal : RetVals) {
4180 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
Tim Northover3b0846e2014-05-24 12:50:23 +00004181 Flag = Chain.getValue(1);
Tim Northoverf1c28922019-09-12 10:22:23 +00004182 RetOps.push_back(
4183 DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004184 }
Mandeep Singh Grang5dc8aeb2019-05-03 21:12:36 +00004185
4186 // Windows AArch64 ABIs require that for returning structs by value we copy
4187 // the sret argument into X0 for the return.
4188 // We saved the argument into a virtual register in the entry block,
4189 // so now we copy the value out and into X0.
4190 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4191 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4192 getPointerTy(MF.getDataLayout()));
4193
4194 unsigned RetValReg = AArch64::X0;
4195 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4196 Flag = Chain.getValue(1);
4197
4198 RetOps.push_back(
4199 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4200 }
4201
Manman Rencbe4f942015-12-16 21:04:19 +00004202 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4203 const MCPhysReg *I =
4204 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4205 if (I) {
4206 for (; *I; ++I) {
4207 if (AArch64::GPR64RegClass.contains(*I))
4208 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4209 else if (AArch64::FPR64RegClass.contains(*I))
4210 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4211 else
4212 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4213 }
4214 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004215
4216 RetOps[0] = Chain; // Update chain.
4217
4218 // Add the flag if we have it.
4219 if (Flag.getNode())
4220 RetOps.push_back(Flag);
4221
4222 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4223}
4224
4225//===----------------------------------------------------------------------===//
4226// Other Lowering Code
4227//===----------------------------------------------------------------------===//
4228
Joel Jonesa7c4a522017-04-21 17:31:03 +00004229SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4230 SelectionDAG &DAG,
4231 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004232 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4233 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004234}
4235
4236SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4237 SelectionDAG &DAG,
4238 unsigned Flag) const {
4239 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4240}
4241
4242SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4243 SelectionDAG &DAG,
4244 unsigned Flag) const {
4245 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4246 N->getOffset(), Flag);
4247}
4248
4249SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4250 SelectionDAG &DAG,
4251 unsigned Flag) const {
4252 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4253}
4254
4255// (loadGOT sym)
4256template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004257SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4258 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004259 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004260 SDLoc DL(N);
4261 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004262 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004263 // FIXME: Once remat is capable of dealing with instructions with register
4264 // operands, expand this into two nodes instead of using a wrapper node.
4265 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4266}
4267
4268// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4269template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004270SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4271 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004272 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004273 SDLoc DL(N);
4274 EVT Ty = getPointerTy(DAG.getDataLayout());
4275 const unsigned char MO_NC = AArch64II::MO_NC;
4276 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004277 AArch64ISD::WrapperLarge, DL, Ty,
4278 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4279 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4280 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4281 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004282}
4283
4284// (addlow (adrp %hi(sym)) %lo(sym))
4285template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004286SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4287 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004288 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004289 SDLoc DL(N);
4290 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004291 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004292 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004293 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004294 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4295 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4296}
4297
David Green9dd1d452018-08-22 11:31:39 +00004298// (adr sym)
4299template <class NodeTy>
4300SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4301 unsigned Flags) const {
4302 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4303 SDLoc DL(N);
4304 EVT Ty = getPointerTy(DAG.getDataLayout());
4305 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4306 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4307}
4308
Tim Northover3b0846e2014-05-24 12:50:23 +00004309SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4310 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004311 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004312 const GlobalValue *GV = GN->getGlobal();
Peter Collingbourne33773d52019-07-31 20:14:09 +00004313 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004314
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004315 if (OpFlags != AArch64II::MO_NO_FLAG)
4316 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4317 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004318
David Green9dd1d452018-08-22 11:31:39 +00004319 // This also catches the large code model case for Darwin, and tiny code
4320 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004321 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004322 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004323 }
4324
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004325 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004326 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004327 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004328 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004329 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004330 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004331 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004332 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004333 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4334 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004335 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004336 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4337 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4338 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004339}
4340
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004341/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004342/// and calls to compute the variable's address (for Darwin, currently) and
4343/// return an SDValue containing the final node.
4344
4345/// Darwin only has one TLS scheme which must be capable of dealing with the
4346/// fully general situation, in the worst case. This means:
4347/// + "extern __thread" declaration.
4348/// + Defined in a possibly unknown dynamic library.
4349///
4350/// The general system is that each __thread variable has a [3 x i64] descriptor
4351/// which contains information used by the runtime to calculate the address. The
4352/// only part of this the compiler needs to know about is the first xword, which
4353/// contains a function pointer that must be called with the address of the
4354/// entire descriptor in "x0".
4355///
4356/// Since this descriptor may be in a different unit, in general even the
4357/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4358/// is:
4359/// adrp x0, _var@TLVPPAGE
4360/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4361/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4362/// ; the function pointer
4363/// blr x1 ; Uses descriptor address in x0
4364/// ; Address of _var is now in x0.
4365///
4366/// If the address of _var's descriptor *is* known to the linker, then it can
4367/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4368/// a slight efficiency gain.
4369SDValue
4370AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4371 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004372 assert(Subtarget->isTargetDarwin() &&
4373 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004374
4375 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004376 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northoverf1c28922019-09-12 10:22:23 +00004377 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004378 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4379
4380 SDValue TLVPAddr =
4381 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4382 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4383
4384 // The first entry in the descriptor is a function pointer that we must call
4385 // to obtain the address of the variable.
4386 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004387 SDValue FuncTLVGet = DAG.getLoad(
Tim Northoverf1c28922019-09-12 10:22:23 +00004388 PtrMemVT, DL, Chain, DescAddr,
Justin Lebaradbf09e2016-09-11 01:38:58 +00004389 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
Tim Northoverf1c28922019-09-12 10:22:23 +00004390 /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
Eli Friedmanb5eb3e12019-08-13 23:12:14 +00004391 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004392 Chain = FuncTLVGet.getValue(1);
4393
Tim Northoverf1c28922019-09-12 10:22:23 +00004394 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4395 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4396
Matthias Braun941a7052016-07-28 18:40:00 +00004397 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4398 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004399
4400 // TLS calls preserve all registers except those that absolutely must be
4401 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4402 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004403 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4404 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4405 if (Subtarget->hasCustomCallingConv())
4406 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004407
4408 // Finally, we can make the call. This is just a degenerate version of a
4409 // normal AArch64 call node: x0 takes the address of the descriptor, and
4410 // returns the address of the variable in this thread.
4411 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4412 Chain =
4413 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4414 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4415 DAG.getRegisterMask(Mask), Chain.getValue(1));
4416 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4417}
4418
4419/// When accessing thread-local variables under either the general-dynamic or
4420/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4421/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004422/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004423///
Kristof Beylsaea84612015-03-04 09:12:08 +00004424/// The sequence is:
4425/// adrp x0, :tlsdesc:var
4426/// ldr x1, [x0, #:tlsdesc_lo12:var]
4427/// add x0, x0, #:tlsdesc_lo12:var
4428/// .tlsdesccall var
4429/// blr x1
4430/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004431///
Kristof Beylsaea84612015-03-04 09:12:08 +00004432/// The above sequence must be produced unscheduled, to enable the linker to
4433/// optimize/relax this sequence.
4434/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4435/// above sequence, and expanded really late in the compilation flow, to ensure
4436/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004437SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4438 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004439 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004440 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004441
Kristof Beylsaea84612015-03-04 09:12:08 +00004442 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004443 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004444
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004445 Chain =
4446 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004447 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004448
4449 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4450}
4451
4452SDValue
4453AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4454 SelectionDAG &DAG) const {
4455 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004456 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4457 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004458 // Different choices can be made for the maximum size of the TLS area for a
4459 // module. For the small address model, the default TLS size is 16MiB and the
4460 // maximum TLS size is 4GiB.
4461 // FIXME: add -mtls-size command line option and make it control the 16MiB
4462 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004463 // FIXME: add tiny codemodel support. We currently generate the same code as
4464 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004465 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4466
4467 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004468
Kristof Beylsaea84612015-03-04 09:12:08 +00004469 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4470 if (Model == TLSModel::LocalDynamic)
4471 Model = TLSModel::GeneralDynamic;
4472 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004473
4474 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004475 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004476 SDLoc DL(Op);
4477 const GlobalValue *GV = GA->getGlobal();
4478
4479 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4480
4481 if (Model == TLSModel::LocalExec) {
4482 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004483 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004484 SDValue LoVar = DAG.getTargetGlobalAddress(
4485 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004486 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004487
Kristof Beylsaea84612015-03-04 09:12:08 +00004488 SDValue TPWithOff_lo =
4489 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004490 HiVar,
4491 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004492 0);
4493 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004494 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4495 LoVar,
4496 DAG.getTargetConstant(0, DL, MVT::i32)),
4497 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004498 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004499 } else if (Model == TLSModel::InitialExec) {
4500 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4501 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4502 } else if (Model == TLSModel::LocalDynamic) {
4503 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4504 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4505 // the beginning of the module's TLS region, followed by a DTPREL offset
4506 // calculation.
4507
4508 // These accesses will need deduplicating if there's more than one.
4509 AArch64FunctionInfo *MFI =
4510 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4511 MFI->incNumLocalDynamicTLSAccesses();
4512
Tim Northover3b0846e2014-05-24 12:50:23 +00004513 // The call needs a relocation too for linker relaxation. It doesn't make
4514 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4515 // the address.
4516 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4517 AArch64II::MO_TLS);
4518
4519 // Now we can calculate the offset from TPIDR_EL0 to this module's
4520 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004521 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004522
4523 // Now use :dtprel_whatever: operations to calculate this variable's offset
4524 // in its thread-storage area.
4525 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004526 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004527 SDValue LoVar = DAG.getTargetGlobalAddress(
4528 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004529 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4530
Kristof Beylsaea84612015-03-04 09:12:08 +00004531 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004532 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004533 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004534 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4535 DAG.getTargetConstant(0, DL, MVT::i32)),
4536 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004537 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004538 // The call needs a relocation too for linker relaxation. It doesn't make
4539 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4540 // the address.
4541 SDValue SymAddr =
4542 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4543
4544 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004545 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004546 } else
4547 llvm_unreachable("Unsupported ELF TLS access model");
4548
4549 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4550}
4551
Martin Storsjocc240962018-03-10 19:05:21 +00004552SDValue
4553AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4554 SelectionDAG &DAG) const {
4555 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4556
4557 SDValue Chain = DAG.getEntryNode();
4558 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4559 SDLoc DL(Op);
4560
4561 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4562
4563 // Load the ThreadLocalStoragePointer from the TEB
4564 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4565 SDValue TLSArray =
4566 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4567 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4568 Chain = TLSArray.getValue(1);
4569
4570 // Load the TLS index from the C runtime;
4571 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4572 // This also does the same as LOADgot, but using a generic i32 load,
4573 // while LOADgot only loads i64.
4574 SDValue TLSIndexHi =
4575 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4576 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4577 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4578 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4579 SDValue TLSIndex =
4580 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4581 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4582 Chain = TLSIndex.getValue(1);
4583
4584 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4585 // offset into the TLSArray.
4586 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4587 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4588 DAG.getConstant(3, DL, PtrVT));
4589 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4590 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4591 MachinePointerInfo());
4592 Chain = TLS.getValue(1);
4593
4594 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4595 const GlobalValue *GV = GA->getGlobal();
4596 SDValue TGAHi = DAG.getTargetGlobalAddress(
4597 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4598 SDValue TGALo = DAG.getTargetGlobalAddress(
4599 GV, DL, PtrVT, 0,
4600 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4601
4602 // Add the offset from the start of the .tls section (section base).
4603 SDValue Addr =
4604 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4605 DAG.getTargetConstant(0, DL, MVT::i32)),
4606 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004607 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004608 return Addr;
4609}
4610
Tim Northover3b0846e2014-05-24 12:50:23 +00004611SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4612 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004613 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004614 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004615 return LowerToTLSEmulatedModel(GA, DAG);
4616
Tim Northover3b0846e2014-05-24 12:50:23 +00004617 if (Subtarget->isTargetDarwin())
4618 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004619 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004620 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004621 if (Subtarget->isTargetWindows())
4622 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004623
4624 llvm_unreachable("Unexpected platform trying to use TLS");
4625}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004626
Tim Northover3b0846e2014-05-24 12:50:23 +00004627SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4628 SDValue Chain = Op.getOperand(0);
4629 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4630 SDValue LHS = Op.getOperand(2);
4631 SDValue RHS = Op.getOperand(3);
4632 SDValue Dest = Op.getOperand(4);
4633 SDLoc dl(Op);
4634
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004635 MachineFunction &MF = DAG.getMachineFunction();
4636 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4637 // will not be produced, as they are conditional branch instructions that do
4638 // not set flags.
4639 bool ProduceNonFlagSettingCondBr =
4640 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4641
Tim Northover3b0846e2014-05-24 12:50:23 +00004642 // Handle f128 first, since lowering it will result in comparing the return
4643 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4644 // is expecting to deal with.
4645 if (LHS.getValueType() == MVT::f128) {
Shiva Chenb39876d2019-08-28 23:40:37 +00004646 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00004647
4648 // If softenSetCCOperands returned a scalar, we need to compare the result
4649 // against zero to select between true and false values.
4650 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004651 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004652 CC = ISD::SETNE;
4653 }
4654 }
4655
4656 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4657 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004658 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4659 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004660 // Only lower legal XALUO ops.
4661 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4662 return SDValue();
4663
4664 // The actual operation with overflow check.
4665 AArch64CC::CondCode OFCC;
4666 SDValue Value, Overflow;
4667 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4668
4669 if (CC == ISD::SETNE)
4670 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004671 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004672
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004673 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4674 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004675 }
4676
4677 if (LHS.getValueType().isInteger()) {
4678 assert((LHS.getValueType() == RHS.getValueType()) &&
4679 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4680
4681 // If the RHS of the comparison is zero, we can potentially fold this
4682 // to a specialized branch.
4683 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004684 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004685 if (CC == ISD::SETEQ) {
4686 // See if we can use a TBZ to fold in an AND as well.
4687 // TBZ has a smaller branch displacement than CBZ. If the offset is
4688 // out of bounds, a late MI-layer pass rewrites branches.
4689 // 403.gcc is an example that hits this case.
4690 if (LHS.getOpcode() == ISD::AND &&
4691 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4692 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4693 SDValue Test = LHS.getOperand(0);
4694 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004695 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004696 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4697 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004698 }
4699
4700 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4701 } else if (CC == ISD::SETNE) {
4702 // See if we can use a TBZ to fold in an AND as well.
4703 // TBZ has a smaller branch displacement than CBZ. If the offset is
4704 // out of bounds, a late MI-layer pass rewrites branches.
4705 // 403.gcc is an example that hits this case.
4706 if (LHS.getOpcode() == ISD::AND &&
4707 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4708 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4709 SDValue Test = LHS.getOperand(0);
4710 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004711 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004712 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4713 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004714 }
4715
4716 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004717 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4718 // Don't combine AND since emitComparison converts the AND to an ANDS
4719 // (a.k.a. TST) and the test in the test bit and branch instruction
4720 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004721 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004722 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004723 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004724 }
4725 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004726 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004727 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004728 // Don't combine AND since emitComparison converts the AND to an ANDS
4729 // (a.k.a. TST) and the test in the test bit and branch instruction
4730 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004731 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004732 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004733 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004734 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004735
4736 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004737 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004738 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4739 Cmp);
4740 }
4741
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004742 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4743 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004744
4745 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4746 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004747 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004748 AArch64CC::CondCode CC1, CC2;
4749 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004750 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004751 SDValue BR1 =
4752 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4753 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004754 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004755 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4756 Cmp);
4757 }
4758
4759 return BR1;
4760}
4761
4762SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4763 SelectionDAG &DAG) const {
4764 EVT VT = Op.getValueType();
4765 SDLoc DL(Op);
4766
4767 SDValue In1 = Op.getOperand(0);
4768 SDValue In2 = Op.getOperand(1);
4769 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004770
4771 if (SrcVT.bitsLT(VT))
4772 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4773 else if (SrcVT.bitsGT(VT))
4774 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004775
4776 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004777 uint64_t EltMask;
4778 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004779
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004780 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004781 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004782 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004783 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004784 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004785 DAG.getUNDEF(VecVT), In2);
4786 } else {
4787 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4788 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4789 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004790 };
4791
4792 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4793 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4794 EltMask = 0x80000000ULL;
4795 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004796 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004797 VecVT = MVT::v2i64;
4798
Eric Christopher572e03a2015-06-19 01:53:21 +00004799 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004800 // immediate moves cannot materialize that in a single instruction for
4801 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004802 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004803
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004804 setVecVal(AArch64::dsub);
4805 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4806 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4807 EltMask = 0x8000ULL;
4808 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004809 } else {
4810 llvm_unreachable("Invalid type for copysign!");
4811 }
4812
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004813 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004814
4815 // If we couldn't materialize the mask above, then the mask vector will be
4816 // the zero vector, and we need to negate it here.
4817 if (VT == MVT::f64 || VT == MVT::v2f64) {
4818 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4819 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4820 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4821 }
4822
4823 SDValue Sel =
4824 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4825
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004826 if (VT == MVT::f16)
4827 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004828 if (VT == MVT::f32)
4829 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4830 else if (VT == MVT::f64)
4831 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4832 else
4833 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4834}
4835
4836SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004837 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004838 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004839 return SDValue();
4840
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004841 if (!Subtarget->hasNEON())
4842 return SDValue();
4843
Tim Northover3b0846e2014-05-24 12:50:23 +00004844 // While there is no integer popcount instruction, it can
4845 // be more efficiently lowered to the following sequence that uses
4846 // AdvSIMD registers/instructions as long as the copies to/from
4847 // the AdvSIMD registers are cheap.
4848 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4849 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4850 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4851 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4852 SDValue Val = Op.getOperand(0);
4853 SDLoc DL(Op);
4854 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004855
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004856 if (VT == MVT::i32 || VT == MVT::i64) {
4857 if (VT == MVT::i32)
4858 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4859 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004860
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004861 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4862 SDValue UaddLV = DAG.getNode(
4863 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4864 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004865
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004866 if (VT == MVT::i64)
4867 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4868 return UaddLV;
4869 }
4870
4871 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4872 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4873 "Unexpected type for custom ctpop lowering");
4874
4875 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4876 Val = DAG.getBitcast(VT8Bit, Val);
4877 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4878
4879 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4880 unsigned EltSize = 8;
4881 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4882 while (EltSize != VT.getScalarSizeInBits()) {
4883 EltSize *= 2;
4884 NumElts /= 2;
4885 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4886 Val = DAG.getNode(
4887 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4888 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4889 }
4890
4891 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004892}
4893
4894SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4895
4896 if (Op.getValueType().isVector())
4897 return LowerVSETCC(Op, DAG);
4898
4899 SDValue LHS = Op.getOperand(0);
4900 SDValue RHS = Op.getOperand(1);
4901 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4902 SDLoc dl(Op);
4903
4904 // We chose ZeroOrOneBooleanContents, so use zero and one.
4905 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004906 SDValue TVal = DAG.getConstant(1, dl, VT);
4907 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004908
4909 // Handle f128 first, since one possible outcome is a normal integer
4910 // comparison which gets picked up by the next if statement.
4911 if (LHS.getValueType() == MVT::f128) {
Shiva Chenb39876d2019-08-28 23:40:37 +00004912 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00004913
4914 // If softenSetCCOperands returned a scalar, use it.
4915 if (!RHS.getNode()) {
4916 assert(LHS.getValueType() == Op.getValueType() &&
4917 "Unexpected setcc expansion!");
4918 return LHS;
4919 }
4920 }
4921
4922 if (LHS.getValueType().isInteger()) {
4923 SDValue CCVal;
4924 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004925 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004926
4927 // Note that we inverted the condition above, so we reverse the order of
4928 // the true and false operands here. This will allow the setcc to be
4929 // matched to a single CSINC instruction.
4930 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4931 }
4932
4933 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004934 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4935 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004936
4937 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4938 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004939 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004940
4941 AArch64CC::CondCode CC1, CC2;
4942 changeFPCCToAArch64CC(CC, CC1, CC2);
4943 if (CC2 == AArch64CC::AL) {
4944 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004945 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004946
4947 // Note that we inverted the condition above, so we reverse the order of
4948 // the true and false operands here. This will allow the setcc to be
4949 // matched to a single CSINC instruction.
4950 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4951 } else {
4952 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4953 // totally clean. Some of them require two CSELs to implement. As is in
4954 // this case, we emit the first CSEL and then emit a second using the output
4955 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4956
4957 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004958 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004959 SDValue CS1 =
4960 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4961
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004962 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004963 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4964 }
4965}
4966
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004967SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4968 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004969 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004970 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004971 // Handle f128 first, because it will result in a comparison of some RTLIB
4972 // call result against zero.
4973 if (LHS.getValueType() == MVT::f128) {
Shiva Chenb39876d2019-08-28 23:40:37 +00004974 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00004975
4976 // If softenSetCCOperands returned a scalar, we need to compare the result
4977 // against zero to select between true and false values.
4978 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004979 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004980 CC = ISD::SETNE;
4981 }
4982 }
4983
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004984 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004985 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004986 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4987 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4988 }
4989
4990 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004991 if (LHS.getValueType().isInteger()) {
4992 assert((LHS.getValueType() == RHS.getValueType()) &&
4993 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4994
4995 unsigned Opcode = AArch64ISD::CSEL;
4996
4997 // If both the TVal and the FVal are constants, see if we can swap them in
4998 // order to for a CSINV or CSINC out of them.
4999 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5000 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5001
5002 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5003 std::swap(TVal, FVal);
5004 std::swap(CTVal, CFVal);
5005 CC = ISD::getSetCCInverse(CC, true);
5006 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5007 std::swap(TVal, FVal);
5008 std::swap(CTVal, CFVal);
5009 CC = ISD::getSetCCInverse(CC, true);
5010 } else if (TVal.getOpcode() == ISD::XOR) {
5011 // If TVal is a NOT we want to swap TVal and FVal so that we can match
5012 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005013 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005014 std::swap(TVal, FVal);
5015 std::swap(CTVal, CFVal);
5016 CC = ISD::getSetCCInverse(CC, true);
5017 }
5018 } else if (TVal.getOpcode() == ISD::SUB) {
5019 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5020 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005021 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005022 std::swap(TVal, FVal);
5023 std::swap(CTVal, CFVal);
5024 CC = ISD::getSetCCInverse(CC, true);
5025 }
5026 } else if (CTVal && CFVal) {
5027 const int64_t TrueVal = CTVal->getSExtValue();
5028 const int64_t FalseVal = CFVal->getSExtValue();
5029 bool Swap = false;
5030
5031 // If both TVal and FVal are constants, see if FVal is the
5032 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5033 // instead of a CSEL in that case.
5034 if (TrueVal == ~FalseVal) {
5035 Opcode = AArch64ISD::CSINV;
5036 } else if (TrueVal == -FalseVal) {
5037 Opcode = AArch64ISD::CSNEG;
5038 } else if (TVal.getValueType() == MVT::i32) {
5039 // If our operands are only 32-bit wide, make sure we use 32-bit
5040 // arithmetic for the check whether we can use CSINC. This ensures that
5041 // the addition in the check will wrap around properly in case there is
5042 // an overflow (which would not be the case if we do the check with
5043 // 64-bit arithmetic).
5044 const uint32_t TrueVal32 = CTVal->getZExtValue();
5045 const uint32_t FalseVal32 = CFVal->getZExtValue();
5046
5047 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5048 Opcode = AArch64ISD::CSINC;
5049
5050 if (TrueVal32 > FalseVal32) {
5051 Swap = true;
5052 }
5053 }
5054 // 64-bit check whether we can use CSINC.
5055 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5056 Opcode = AArch64ISD::CSINC;
5057
5058 if (TrueVal > FalseVal) {
5059 Swap = true;
5060 }
5061 }
5062
5063 // Swap TVal and FVal if necessary.
5064 if (Swap) {
5065 std::swap(TVal, FVal);
5066 std::swap(CTVal, CFVal);
5067 CC = ISD::getSetCCInverse(CC, true);
5068 }
5069
5070 if (Opcode != AArch64ISD::CSEL) {
5071 // Drop FVal since we can get its value by simply inverting/negating
5072 // TVal.
5073 FVal = TVal;
5074 }
5075 }
5076
Chad Rosier58f505b2016-08-26 18:05:50 +00005077 // Avoid materializing a constant when possible by reusing a known value in
5078 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00005079 // is one, zero or negative one in the case of a CSEL. We can always
5080 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5081 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00005082 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5083 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5084 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5085 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5086 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5087 // "a != C ? x : a" to avoid materializing C.
5088 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5089 TVal = LHS;
5090 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5091 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00005092 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5093 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5094 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5095 // avoid materializing C.
5096 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5097 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5098 Opcode = AArch64ISD::CSINV;
5099 TVal = LHS;
5100 FVal = DAG.getConstant(0, dl, FVal.getValueType());
5101 }
Chad Rosier58f505b2016-08-26 18:05:50 +00005102 }
5103
Tim Northover3b0846e2014-05-24 12:50:23 +00005104 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00005105 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005106 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00005107 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5108 }
5109
5110 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00005111 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5112 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005113 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005114 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00005115 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005116
5117 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5118 // clean. Some of them require two CSELs to implement.
5119 AArch64CC::CondCode CC1, CC2;
5120 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00005121
5122 if (DAG.getTarget().Options.UnsafeFPMath) {
5123 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5124 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5125 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5126 if (RHSVal && RHSVal->isZero()) {
5127 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5128 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5129
5130 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00005131 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00005132 TVal = LHS;
5133 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00005134 CFVal && CFVal->isZero() &&
5135 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00005136 FVal = LHS;
5137 }
5138 }
5139
5140 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005141 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00005142 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5143
5144 // If we need a second CSEL, emit it, using the output of the first as the
5145 // RHS. We're effectively OR'ing the two CC's together.
5146 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005147 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00005148 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5149 }
5150
5151 // Otherwise, return the output of the first CSEL.
5152 return CS1;
5153}
5154
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005155SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5156 SelectionDAG &DAG) const {
5157 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5158 SDValue LHS = Op.getOperand(0);
5159 SDValue RHS = Op.getOperand(1);
5160 SDValue TVal = Op.getOperand(2);
5161 SDValue FVal = Op.getOperand(3);
5162 SDLoc DL(Op);
5163 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5164}
5165
5166SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5167 SelectionDAG &DAG) const {
5168 SDValue CCVal = Op->getOperand(0);
5169 SDValue TVal = Op->getOperand(1);
5170 SDValue FVal = Op->getOperand(2);
5171 SDLoc DL(Op);
5172
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005173 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5174 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00005175 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005176 // Only lower legal XALUO ops.
5177 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5178 return SDValue();
5179
5180 AArch64CC::CondCode OFCC;
5181 SDValue Value, Overflow;
5182 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005183 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005184
5185 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5186 CCVal, Overflow);
5187 }
5188
5189 // Lower it the same way as we would lower a SELECT_CC node.
5190 ISD::CondCode CC;
5191 SDValue LHS, RHS;
5192 if (CCVal.getOpcode() == ISD::SETCC) {
5193 LHS = CCVal.getOperand(0);
5194 RHS = CCVal.getOperand(1);
5195 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5196 } else {
5197 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005198 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00005199 CC = ISD::SETNE;
5200 }
5201 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5202}
5203
Tim Northover3b0846e2014-05-24 12:50:23 +00005204SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5205 SelectionDAG &DAG) const {
5206 // Jump table entries as PC relative offsets. No additional tweaking
5207 // is necessary here. Just get the address of the jump table.
5208 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005209
5210 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5211 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005212 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005213 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5214 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005215 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005216 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005217}
5218
Tim Northover1c353412018-10-24 20:19:09 +00005219SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5220 SelectionDAG &DAG) const {
5221 // Jump table entries as PC relative offsets. No additional tweaking
5222 // is necessary here. Just get the address of the jump table.
5223 SDLoc DL(Op);
5224 SDValue JT = Op.getOperand(1);
5225 SDValue Entry = Op.getOperand(2);
5226 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5227
5228 SDNode *Dest =
5229 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5230 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5231 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5232 SDValue(Dest, 0));
5233}
5234
Tim Northover3b0846e2014-05-24 12:50:23 +00005235SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5236 SelectionDAG &DAG) const {
5237 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005238
5239 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5240 // Use the GOT for the large code model on iOS.
5241 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005242 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005243 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00005244 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005245 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5246 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005247 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005248 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005249 }
5250}
5251
5252SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5253 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005254 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005255 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5256 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005257 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005258 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5259 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005260 }
David Green9dd1d452018-08-22 11:31:39 +00005261 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005262}
5263
5264SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5265 SelectionDAG &DAG) const {
5266 AArch64FunctionInfo *FuncInfo =
5267 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5268
5269 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005270 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5271 getPointerTy(DAG.getDataLayout()));
Tim Northoverf1c28922019-09-12 10:22:23 +00005272 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005273 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5274 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005275 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005276}
5277
Martin Storsjo68266fa2017-07-13 17:03:12 +00005278SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5279 SelectionDAG &DAG) const {
5280 AArch64FunctionInfo *FuncInfo =
5281 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5282
5283 SDLoc DL(Op);
5284 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5285 ? FuncInfo->getVarArgsGPRIndex()
5286 : FuncInfo->getVarArgsStackIndex(),
5287 getPointerTy(DAG.getDataLayout()));
5288 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5289 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5290 MachinePointerInfo(SV));
5291}
5292
Tim Northover3b0846e2014-05-24 12:50:23 +00005293SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5294 SelectionDAG &DAG) const {
5295 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5296 // Standard, section B.3.
5297 MachineFunction &MF = DAG.getMachineFunction();
5298 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005299 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005300 SDLoc DL(Op);
5301
5302 SDValue Chain = Op.getOperand(0);
5303 SDValue VAList = Op.getOperand(1);
5304 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5305 SmallVector<SDValue, 4> MemOps;
5306
5307 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005308 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005309 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005310 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005311
5312 // void *__gr_top at offset 8
5313 int GPRSize = FuncInfo->getVarArgsGPRSize();
5314 if (GPRSize > 0) {
5315 SDValue GRTop, GRTopAddr;
5316
Mehdi Amini44ede332015-07-09 02:09:04 +00005317 GRTopAddr =
5318 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005319
Mehdi Amini44ede332015-07-09 02:09:04 +00005320 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5321 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5322 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005323
5324 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005325 MachinePointerInfo(SV, 8),
5326 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005327 }
5328
5329 // void *__vr_top at offset 16
5330 int FPRSize = FuncInfo->getVarArgsFPRSize();
5331 if (FPRSize > 0) {
5332 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005333 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5334 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005335
Mehdi Amini44ede332015-07-09 02:09:04 +00005336 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5337 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5338 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005339
5340 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005341 MachinePointerInfo(SV, 16),
5342 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005343 }
5344
5345 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005346 SDValue GROffsAddr =
5347 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005348 MemOps.push_back(DAG.getStore(
5349 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5350 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005351
5352 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005353 SDValue VROffsAddr =
5354 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005355 MemOps.push_back(DAG.getStore(
5356 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5357 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005358
5359 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5360}
5361
5362SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5363 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005364 MachineFunction &MF = DAG.getMachineFunction();
5365
Matthias Braunf1caa282017-12-15 22:22:58 +00005366 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005367 return LowerWin64_VASTART(Op, DAG);
5368 else if (Subtarget->isTargetDarwin())
5369 return LowerDarwin_VASTART(Op, DAG);
5370 else
5371 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005372}
5373
5374SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5375 SelectionDAG &DAG) const {
5376 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5377 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005378 SDLoc DL(Op);
Tim Northoverf1c28922019-09-12 10:22:23 +00005379 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5380 unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5381 Subtarget->isTargetWindows()) ? PtrSize : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005382 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5383 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5384
Tim Northoverf1c28922019-09-12 10:22:23 +00005385 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5386 DAG.getConstant(VaListSize, DL, MVT::i32), PtrSize,
5387 false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005388 MachinePointerInfo(SrcSV));
5389}
5390
5391SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5392 assert(Subtarget->isTargetDarwin() &&
5393 "automatic va_arg instruction only works on Darwin");
5394
5395 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5396 EVT VT = Op.getValueType();
5397 SDLoc DL(Op);
5398 SDValue Chain = Op.getOperand(0);
5399 SDValue Addr = Op.getOperand(1);
5400 unsigned Align = Op.getConstantOperandVal(3);
Tim Northoverf1c28922019-09-12 10:22:23 +00005401 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
Mehdi Amini44ede332015-07-09 02:09:04 +00005402 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northoverf1c28922019-09-12 10:22:23 +00005403 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5404 SDValue VAList =
5405 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005406 Chain = VAList.getValue(1);
Tim Northoverf1c28922019-09-12 10:22:23 +00005407 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005408
Tim Northoverf1c28922019-09-12 10:22:23 +00005409 if (Align > MinSlotSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005410 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005411 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5412 DAG.getConstant(Align - 1, DL, PtrVT));
5413 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5414 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005415 }
5416
5417 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Tim Northoverf1c28922019-09-12 10:22:23 +00005418 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005419
5420 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5421 // up to 64 bits. At the very least, we have to increase the striding of the
5422 // vaargs list to match this, and for FP values we need to introduce
5423 // FP_ROUND nodes as well.
5424 if (VT.isInteger() && !VT.isVector())
Tim Northoverf1c28922019-09-12 10:22:23 +00005425 ArgSize = std::max(ArgSize, MinSlotSize);
Tim Northover3b0846e2014-05-24 12:50:23 +00005426 bool NeedFPTrunc = false;
5427 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5428 ArgSize = 8;
5429 NeedFPTrunc = true;
5430 }
5431
5432 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005433 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5434 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northoverf1c28922019-09-12 10:22:23 +00005435 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5436
Tim Northover3b0846e2014-05-24 12:50:23 +00005437 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005438 SDValue APStore =
5439 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005440
5441 // Load the actual argument out of the pointer VAList
5442 if (NeedFPTrunc) {
5443 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005444 SDValue WideFP =
5445 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005446 // Round the value down to an f32.
5447 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005448 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005449 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5450 // Merge the rounded value with the chain output of the load.
5451 return DAG.getMergeValues(Ops, DL);
5452 }
5453
Justin Lebar9c375812016-07-15 18:27:10 +00005454 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005455}
5456
5457SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5458 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005459 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5460 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005461
5462 EVT VT = Op.getValueType();
5463 SDLoc DL(Op);
5464 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5465 SDValue FrameAddr =
Tim Northoverf1c28922019-09-12 10:22:23 +00005466 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005467 while (Depth--)
5468 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005469 MachinePointerInfo());
Tim Northoverf1c28922019-09-12 10:22:23 +00005470
5471 if (Subtarget->isTargetILP32())
5472 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5473 DAG.getValueType(VT));
5474
Tim Northover3b0846e2014-05-24 12:50:23 +00005475 return FrameAddr;
5476}
5477
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005478SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5479 SelectionDAG &DAG) const {
5480 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5481
5482 EVT VT = getPointerTy(DAG.getDataLayout());
5483 SDLoc DL(Op);
5484 int FI = MFI.CreateFixedObject(4, 0, false);
5485 return DAG.getFrameIndex(FI, VT);
5486}
5487
Petr Hosekfcbec022019-02-13 17:28:47 +00005488#define GET_REGISTER_MATCHER
5489#include "AArch64GenAsmMatcher.inc"
5490
Tim Northover3b0846e2014-05-24 12:50:23 +00005491// FIXME? Maybe this could be a TableGen attribute on some registers and
5492// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005493unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5494 SelectionDAG &DAG) const {
Petr Hosekfcbec022019-02-13 17:28:47 +00005495 unsigned Reg = MatchRegisterName(RegName);
5496 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5497 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5498 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5499 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5500 Reg = 0;
5501 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005502 if (Reg)
5503 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005504 report_fatal_error(Twine("Invalid register name \""
5505 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005506}
5507
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005508SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5509 SelectionDAG &DAG) const {
5510 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5511
5512 EVT VT = Op.getValueType();
5513 SDLoc DL(Op);
5514
5515 SDValue FrameAddr =
5516 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5517 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5518
5519 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5520}
5521
Tim Northover3b0846e2014-05-24 12:50:23 +00005522SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5523 SelectionDAG &DAG) const {
5524 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005525 MachineFrameInfo &MFI = MF.getFrameInfo();
5526 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005527
5528 EVT VT = Op.getValueType();
5529 SDLoc DL(Op);
5530 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5531 if (Depth) {
5532 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005533 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005534 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5535 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005536 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005537 }
5538
5539 // Return LR, which contains the return address. Mark it an implicit live-in.
5540 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5541 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5542}
5543
5544/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5545/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5546SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5547 SelectionDAG &DAG) const {
5548 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5549 EVT VT = Op.getValueType();
5550 unsigned VTBits = VT.getSizeInBits();
5551 SDLoc dl(Op);
5552 SDValue ShOpLo = Op.getOperand(0);
5553 SDValue ShOpHi = Op.getOperand(1);
5554 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005555 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5556
5557 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5558
5559 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005560 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005561 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5562
5563 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5564 // is "undef". We wanted 0, so CSEL it directly.
5565 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5566 ISD::SETEQ, dl, DAG);
5567 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5568 HiBitsForLo =
5569 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5570 HiBitsForLo, CCVal, Cmp);
5571
Tim Northover3b0846e2014-05-24 12:50:23 +00005572 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005573 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005574
Tim Northoverf3be9d52015-12-02 00:33:54 +00005575 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5576 SDValue LoForNormalShift =
5577 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005578
Tim Northoverf3be9d52015-12-02 00:33:54 +00005579 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5580 dl, DAG);
5581 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5582 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5583 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5584 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005585
5586 // AArch64 shifts larger than the register width are wrapped rather than
5587 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005588 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5589 SDValue HiForBigShift =
5590 Opc == ISD::SRA
5591 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5592 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5593 : DAG.getConstant(0, dl, VT);
5594 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5595 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005596
5597 SDValue Ops[2] = { Lo, Hi };
5598 return DAG.getMergeValues(Ops, dl);
5599}
5600
5601/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5602/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5603SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005604 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005605 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5606 EVT VT = Op.getValueType();
5607 unsigned VTBits = VT.getSizeInBits();
5608 SDLoc dl(Op);
5609 SDValue ShOpLo = Op.getOperand(0);
5610 SDValue ShOpHi = Op.getOperand(1);
5611 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005612
5613 assert(Op.getOpcode() == ISD::SHL_PARTS);
5614 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005615 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005616 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5617
5618 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5619 // is "undef". We wanted 0, so CSEL it directly.
5620 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5621 ISD::SETEQ, dl, DAG);
5622 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5623 LoBitsForHi =
5624 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5625 LoBitsForHi, CCVal, Cmp);
5626
Tim Northover3b0846e2014-05-24 12:50:23 +00005627 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005628 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005629 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5630 SDValue HiForNormalShift =
5631 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005632
Tim Northoverf3be9d52015-12-02 00:33:54 +00005633 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005634
Tim Northoverf3be9d52015-12-02 00:33:54 +00005635 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5636 dl, DAG);
5637 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5638 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5639 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005640
5641 // AArch64 shifts of larger than register sizes are wrapped rather than
5642 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005643 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5644 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5645 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5646 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005647
5648 SDValue Ops[2] = { Lo, Hi };
5649 return DAG.getMergeValues(Ops, dl);
5650}
5651
5652bool AArch64TargetLowering::isOffsetFoldingLegal(
5653 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005654 // Offsets are folded in the DAG combine rather than here so that we can
5655 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005656 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005657}
5658
Adhemerval Zanella664c1ef2019-03-18 18:40:07 +00005659bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5660 bool OptForSize) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005661 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005662 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5663 // 16-bit case when target has full fp16 support.
5664 // FIXME: We should be able to handle f128 as well with a clever lowering.
5665 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005666 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005667 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005668 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005669 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005670 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005671 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5672 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5673 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005674
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005675 // If we can not materialize in immediate field for fmov, check if the
5676 // value can be encoded as the immediate operand of a logical instruction.
5677 // The immediate value will be created with either MOVZ, MOVN, or ORR.
Adhemerval Zanellaa3cefa52019-03-18 18:45:57 +00005678 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5679 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5680 // however the mov+fmov sequence is always better because of the reduced
5681 // cache pressure. The timings are still the same if you consider
5682 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5683 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5684 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5685 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5686 Insn);
5687 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5688 IsLegal = Insn.size() <= Limit;
5689 }
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005690
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005691 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5692 << " imm value: "; Imm.dump(););
5693 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005694}
5695
5696//===----------------------------------------------------------------------===//
5697// AArch64 Optimization Hooks
5698//===----------------------------------------------------------------------===//
5699
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005700static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5701 SDValue Operand, SelectionDAG &DAG,
5702 int &ExtraSteps) {
5703 EVT VT = Operand.getValueType();
5704 if (ST->hasNEON() &&
5705 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5706 VT == MVT::f32 || VT == MVT::v1f32 ||
5707 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5708 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5709 // For the reciprocal estimates, convergence is quadratic, so the number
5710 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5711 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5712 // the result for float (23 mantissa bits) is 2 and for double (52
5713 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005714 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005715
5716 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5717 }
5718
5719 return SDValue();
5720}
5721
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005722SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5723 SelectionDAG &DAG, int Enabled,
5724 int &ExtraSteps,
5725 bool &UseOneConst,
5726 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005727 if (Enabled == ReciprocalEstimate::Enabled ||
5728 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5729 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5730 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005731 SDLoc DL(Operand);
5732 EVT VT = Operand.getValueType();
5733
5734 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005735 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005736
5737 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5738 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5739 for (int i = ExtraSteps; i > 0; --i) {
5740 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005741 Flags);
5742 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5743 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005744 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005745 if (!Reciprocal) {
5746 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5747 VT);
5748 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5749 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5750
Amara Emersond28f0cd42017-05-01 15:17:51 +00005751 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005752 // Correct the result if the operand is 0.0.
5753 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5754 VT, Eq, Operand, Estimate);
5755 }
5756
5757 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005758 return Estimate;
5759 }
5760
5761 return SDValue();
5762}
5763
5764SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5765 SelectionDAG &DAG, int Enabled,
5766 int &ExtraSteps) const {
5767 if (Enabled == ReciprocalEstimate::Enabled)
5768 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005769 DAG, ExtraSteps)) {
5770 SDLoc DL(Operand);
5771 EVT VT = Operand.getValueType();
5772
5773 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005774 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005775
5776 // Newton reciprocal iteration: E * (2 - X * E)
5777 // AArch64 reciprocal iteration instruction: (2 - M * N)
5778 for (int i = ExtraSteps; i > 0; --i) {
5779 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005780 Estimate, Flags);
5781 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005782 }
5783
5784 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005785 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005786 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005787
5788 return SDValue();
5789}
5790
Tim Northover3b0846e2014-05-24 12:50:23 +00005791//===----------------------------------------------------------------------===//
5792// AArch64 Inline Assembly Support
5793//===----------------------------------------------------------------------===//
5794
5795// Table of Constraints
5796// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005797// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005798//
5799// r - A general register
5800// w - An FP/SIMD register of some size in the range v0-v31
5801// x - An FP/SIMD register of some size in the range v0-v15
5802// I - Constant that can be used with an ADD instruction
5803// J - Constant that can be used with a SUB instruction
5804// K - Constant that can be used with a 32-bit logical instruction
5805// L - Constant that can be used with a 64-bit logical instruction
5806// M - Constant that can be used as a 32-bit MOV immediate
5807// N - Constant that can be used as a 64-bit MOV immediate
5808// Q - A memory reference with base register and no offset
5809// S - A symbolic address
5810// Y - Floating point constant zero
5811// Z - Integer constant zero
5812//
5813// Note that general register operands will be output using their 64-bit x
5814// register name, whatever the size of the variable, unless the asm operand
5815// is prefixed by the %w modifier. Floating-point and SIMD register operands
5816// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5817// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005818const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5819 // At this point, we have to lower this constraint to something else, so we
5820 // lower it to an "r" or "w". However, by doing this we will force the result
5821 // to be in register, while the X constraint is much more permissive.
5822 //
5823 // Although we are correct (we are free to emit anything, without
5824 // constraints), we might break use cases that would expect us to be more
5825 // efficient and emit something else.
5826 if (!Subtarget->hasFPARMv8())
5827 return "r";
5828
5829 if (ConstraintVT.isFloatingPoint())
5830 return "w";
5831
5832 if (ConstraintVT.isVector() &&
5833 (ConstraintVT.getSizeInBits() == 64 ||
5834 ConstraintVT.getSizeInBits() == 128))
5835 return "w";
5836
5837 return "r";
5838}
Tim Northover3b0846e2014-05-24 12:50:23 +00005839
Kerry McLaughline55b3bf2019-09-16 09:45:27 +00005840enum PredicateConstraint {
5841 Upl,
5842 Upa,
5843 Invalid
5844};
5845
Benjamin Kramerdf4b9a32019-09-17 12:56:29 +00005846static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
Kerry McLaughline55b3bf2019-09-16 09:45:27 +00005847 PredicateConstraint P = PredicateConstraint::Invalid;
5848 if (Constraint == "Upa")
5849 P = PredicateConstraint::Upa;
5850 if (Constraint == "Upl")
5851 P = PredicateConstraint::Upl;
5852 return P;
5853}
5854
Tim Northover3b0846e2014-05-24 12:50:23 +00005855/// getConstraintType - Given a constraint letter, return the type of
5856/// constraint it is for this target.
5857AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005858AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005859 if (Constraint.size() == 1) {
5860 switch (Constraint[0]) {
5861 default:
5862 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005863 case 'x':
5864 case 'w':
Kerry McLaughlinda4ef9b2019-09-02 16:12:31 +00005865 case 'y':
Tim Northover3b0846e2014-05-24 12:50:23 +00005866 return C_RegisterClass;
5867 // An address with a single base register. Due to the way we
5868 // currently handle addresses it is the same as 'r'.
5869 case 'Q':
5870 return C_Memory;
Bill Wendling41a28472019-08-03 05:52:47 +00005871 case 'I':
5872 case 'J':
5873 case 'K':
5874 case 'L':
5875 case 'M':
5876 case 'N':
5877 case 'Y':
5878 case 'Z':
5879 return C_Immediate;
5880 case 'z':
Peter Smithc8117582018-05-16 09:33:25 +00005881 case 'S': // A symbolic address
5882 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005883 }
Kerry McLaughline55b3bf2019-09-16 09:45:27 +00005884 } else if (parsePredicateConstraint(Constraint) !=
5885 PredicateConstraint::Invalid)
5886 return C_RegisterClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00005887 return TargetLowering::getConstraintType(Constraint);
5888}
5889
5890/// Examine constraint type and operand type and determine a weight value.
5891/// This object must already have been set up with the operand type
5892/// and the current alternative constraint selected.
5893TargetLowering::ConstraintWeight
5894AArch64TargetLowering::getSingleConstraintMatchWeight(
5895 AsmOperandInfo &info, const char *constraint) const {
5896 ConstraintWeight weight = CW_Invalid;
5897 Value *CallOperandVal = info.CallOperandVal;
5898 // If we don't have a value, we can't do a match,
5899 // but allow it at the lowest weight.
5900 if (!CallOperandVal)
5901 return CW_Default;
5902 Type *type = CallOperandVal->getType();
5903 // Look at the constraint type.
5904 switch (*constraint) {
5905 default:
5906 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5907 break;
5908 case 'x':
5909 case 'w':
Kerry McLaughlinda4ef9b2019-09-02 16:12:31 +00005910 case 'y':
Tim Northover3b0846e2014-05-24 12:50:23 +00005911 if (type->isFloatingPointTy() || type->isVectorTy())
5912 weight = CW_Register;
5913 break;
5914 case 'z':
5915 weight = CW_Constant;
5916 break;
Kerry McLaughline55b3bf2019-09-16 09:45:27 +00005917 case 'U':
5918 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
5919 weight = CW_Register;
5920 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005921 }
5922 return weight;
5923}
5924
5925std::pair<unsigned, const TargetRegisterClass *>
5926AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005927 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005928 if (Constraint.size() == 1) {
5929 switch (Constraint[0]) {
5930 case 'r':
5931 if (VT.getSizeInBits() == 64)
5932 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5933 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5934 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005935 if (!Subtarget->hasFPARMv8())
5936 break;
Kerry McLaughlinda4ef9b2019-09-02 16:12:31 +00005937 if (VT.isScalableVector())
5938 return std::make_pair(0U, &AArch64::ZPRRegClass);
Amara Emerson614b44b2016-11-07 15:42:12 +00005939 if (VT.getSizeInBits() == 16)
5940 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005941 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005942 return std::make_pair(0U, &AArch64::FPR32RegClass);
5943 if (VT.getSizeInBits() == 64)
5944 return std::make_pair(0U, &AArch64::FPR64RegClass);
5945 if (VT.getSizeInBits() == 128)
5946 return std::make_pair(0U, &AArch64::FPR128RegClass);
5947 break;
5948 // The instructions that this constraint is designed for can
5949 // only take 128-bit registers so just use that regclass.
5950 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005951 if (!Subtarget->hasFPARMv8())
5952 break;
Kerry McLaughlinda4ef9b2019-09-02 16:12:31 +00005953 if (VT.isScalableVector())
5954 return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
Tim Northover3b0846e2014-05-24 12:50:23 +00005955 if (VT.getSizeInBits() == 128)
5956 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
Kerry McLaughlin7b5c6b82019-09-03 15:45:42 +00005957 break;
Kerry McLaughlinda4ef9b2019-09-02 16:12:31 +00005958 case 'y':
5959 if (!Subtarget->hasFPARMv8())
5960 break;
5961 if (VT.isScalableVector())
5962 return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
Tim Northover3b0846e2014-05-24 12:50:23 +00005963 break;
5964 }
Kerry McLaughline55b3bf2019-09-16 09:45:27 +00005965 } else {
5966 PredicateConstraint PC = parsePredicateConstraint(Constraint);
5967 if (PC != PredicateConstraint::Invalid) {
5968 assert(VT.isScalableVector());
5969 bool restricted = (PC == PredicateConstraint::Upl);
5970 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
5971 : std::make_pair(0U, &AArch64::PPRRegClass);
5972 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005973 }
5974 if (StringRef("{cc}").equals_lower(Constraint))
5975 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5976
5977 // Use the default implementation in TargetLowering to convert the register
5978 // constraint into a member of a register class.
5979 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005980 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005981
5982 // Not found as a standard register?
5983 if (!Res.second) {
5984 unsigned Size = Constraint.size();
5985 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5986 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005987 int RegNo;
5988 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5989 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005990 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005991 // By default we'll emit v0-v31 for this unless there's a modifier where
5992 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005993 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5994 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5995 Res.second = &AArch64::FPR64RegClass;
5996 } else {
5997 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5998 Res.second = &AArch64::FPR128RegClass;
5999 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006000 }
6001 }
6002 }
6003
Eli Friedman071203b2018-08-24 19:12:13 +00006004 if (Res.second && !Subtarget->hasFPARMv8() &&
6005 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6006 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6007 return std::make_pair(0U, nullptr);
6008
Tim Northover3b0846e2014-05-24 12:50:23 +00006009 return Res;
6010}
6011
6012/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6013/// vector. If it is invalid, don't add anything to Ops.
6014void AArch64TargetLowering::LowerAsmOperandForConstraint(
6015 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6016 SelectionDAG &DAG) const {
6017 SDValue Result;
6018
6019 // Currently only support length 1 constraints.
6020 if (Constraint.length() != 1)
6021 return;
6022
6023 char ConstraintLetter = Constraint[0];
6024 switch (ConstraintLetter) {
6025 default:
6026 break;
6027
6028 // This set of constraints deal with valid constants for various instructions.
6029 // Validate and return a target constant for them if we can.
6030 case 'z': {
6031 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00006032 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00006033 return;
6034
6035 if (Op.getValueType() == MVT::i64)
6036 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6037 else
6038 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6039 break;
6040 }
Peter Smithc8117582018-05-16 09:33:25 +00006041 case 'S': {
6042 // An absolute symbolic address or label reference.
6043 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6044 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6045 GA->getValueType(0));
6046 } else if (const BlockAddressSDNode *BA =
6047 dyn_cast<BlockAddressSDNode>(Op)) {
6048 Result =
6049 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6050 } else if (const ExternalSymbolSDNode *ES =
6051 dyn_cast<ExternalSymbolSDNode>(Op)) {
6052 Result =
6053 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6054 } else
6055 return;
6056 break;
6057 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006058
6059 case 'I':
6060 case 'J':
6061 case 'K':
6062 case 'L':
6063 case 'M':
6064 case 'N':
6065 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6066 if (!C)
6067 return;
6068
6069 // Grab the value and do some validation.
6070 uint64_t CVal = C->getZExtValue();
6071 switch (ConstraintLetter) {
6072 // The I constraint applies only to simple ADD or SUB immediate operands:
6073 // i.e. 0 to 4095 with optional shift by 12
6074 // The J constraint applies only to ADD or SUB immediates that would be
6075 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6076 // instruction [or vice versa], in other words -1 to -4095 with optional
6077 // left shift by 12.
6078 case 'I':
6079 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6080 break;
6081 return;
6082 case 'J': {
6083 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00006084 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6085 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00006086 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00006087 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006088 return;
6089 }
6090 // The K and L constraints apply *only* to logical immediates, including
6091 // what used to be the MOVI alias for ORR (though the MOVI alias has now
6092 // been removed and MOV should be used). So these constraints have to
6093 // distinguish between bit patterns that are valid 32-bit or 64-bit
6094 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6095 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6096 // versa.
6097 case 'K':
6098 if (AArch64_AM::isLogicalImmediate(CVal, 32))
6099 break;
6100 return;
6101 case 'L':
6102 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6103 break;
6104 return;
6105 // The M and N constraints are a superset of K and L respectively, for use
6106 // with the MOV (immediate) alias. As well as the logical immediates they
6107 // also match 32 or 64-bit immediates that can be loaded either using a
6108 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6109 // (M) or 64-bit 0x1234000000000000 (N) etc.
6110 // As a note some of this code is liberally stolen from the asm parser.
6111 case 'M': {
6112 if (!isUInt<32>(CVal))
6113 return;
6114 if (AArch64_AM::isLogicalImmediate(CVal, 32))
6115 break;
6116 if ((CVal & 0xFFFF) == CVal)
6117 break;
6118 if ((CVal & 0xFFFF0000ULL) == CVal)
6119 break;
6120 uint64_t NCVal = ~(uint32_t)CVal;
6121 if ((NCVal & 0xFFFFULL) == NCVal)
6122 break;
6123 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6124 break;
6125 return;
6126 }
6127 case 'N': {
6128 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6129 break;
6130 if ((CVal & 0xFFFFULL) == CVal)
6131 break;
6132 if ((CVal & 0xFFFF0000ULL) == CVal)
6133 break;
6134 if ((CVal & 0xFFFF00000000ULL) == CVal)
6135 break;
6136 if ((CVal & 0xFFFF000000000000ULL) == CVal)
6137 break;
6138 uint64_t NCVal = ~CVal;
6139 if ((NCVal & 0xFFFFULL) == NCVal)
6140 break;
6141 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6142 break;
6143 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6144 break;
6145 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6146 break;
6147 return;
6148 }
6149 default:
6150 return;
6151 }
6152
6153 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006154 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006155 break;
6156 }
6157
6158 if (Result.getNode()) {
6159 Ops.push_back(Result);
6160 return;
6161 }
6162
6163 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6164}
6165
6166//===----------------------------------------------------------------------===//
6167// AArch64 Advanced SIMD Support
6168//===----------------------------------------------------------------------===//
6169
6170/// WidenVector - Given a value in the V64 register class, produce the
6171/// equivalent value in the V128 register class.
6172static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6173 EVT VT = V64Reg.getValueType();
6174 unsigned NarrowSize = VT.getVectorNumElements();
6175 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6176 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6177 SDLoc DL(V64Reg);
6178
6179 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006180 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006181}
6182
6183/// getExtFactor - Determine the adjustment factor for the position when
6184/// generating an "extract from vector registers" instruction.
6185static unsigned getExtFactor(SDValue &V) {
6186 EVT EltType = V.getValueType().getVectorElementType();
6187 return EltType.getSizeInBits() / 8;
6188}
6189
6190/// NarrowVector - Given a value in the V128 register class, produce the
6191/// equivalent value in the V64 register class.
6192static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6193 EVT VT = V128Reg.getValueType();
6194 unsigned WideSize = VT.getVectorNumElements();
6195 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6196 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6197 SDLoc DL(V128Reg);
6198
6199 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6200}
6201
6202// Gather data to see if the operation can be modelled as a
6203// shuffle in combination with VEXTs.
6204SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6205 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00006206 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006207 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006208 SDLoc dl(Op);
6209 EVT VT = Op.getValueType();
6210 unsigned NumElts = VT.getVectorNumElements();
6211
Tim Northover7324e842014-07-24 15:39:55 +00006212 struct ShuffleSourceInfo {
6213 SDValue Vec;
6214 unsigned MinElt;
6215 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006216
Tim Northover7324e842014-07-24 15:39:55 +00006217 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6218 // be compatible with the shuffle we intend to construct. As a result
6219 // ShuffleVec will be some sliding window into the original Vec.
6220 SDValue ShuffleVec;
6221
6222 // Code should guarantee that element i in Vec starts at element "WindowBase
6223 // + i * WindowScale in ShuffleVec".
6224 int WindowBase;
6225 int WindowScale;
6226
Tim Northover7324e842014-07-24 15:39:55 +00006227 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00006228 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6229 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6230
6231 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00006232 };
6233
6234 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6235 // node.
6236 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00006237 for (unsigned i = 0; i < NumElts; ++i) {
6238 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006239 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006240 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00006241 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6242 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006243 LLVM_DEBUG(
6244 dbgs() << "Reshuffle failed: "
6245 "a shuffle can only come from building a vector from "
6246 "various elements of other vectors, provided their "
6247 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006248 return SDValue();
6249 }
6250
Tim Northover7324e842014-07-24 15:39:55 +00006251 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00006252 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00006253 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00006254 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00006255 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00006256
Tim Northover7324e842014-07-24 15:39:55 +00006257 // Update the minimum and maximum lane number seen.
6258 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6259 Source->MinElt = std::min(Source->MinElt, EltNo);
6260 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00006261 }
6262
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006263 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006264 LLVM_DEBUG(
6265 dbgs() << "Reshuffle failed: currently only do something sane when at "
6266 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006267 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006268 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006269
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006270 // Find out the smallest element size among result and two sources, and use
6271 // it as element size to build the shuffle_vector.
6272 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00006273 for (auto &Source : Sources) {
6274 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006275 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6276 SmallestEltTy = SrcEltTy;
6277 }
6278 }
6279 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006280 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006281 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6282 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00006283
Tim Northover7324e842014-07-24 15:39:55 +00006284 // If the source vector is too wide or too narrow, we may nevertheless be able
6285 // to construct a compatible shuffle either by concatenating it with UNDEF or
6286 // extracting a suitable range of elements.
6287 for (auto &Src : Sources) {
6288 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00006289
Tim Northover7324e842014-07-24 15:39:55 +00006290 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00006291 continue;
Tim Northover7324e842014-07-24 15:39:55 +00006292
6293 // This stage of the search produces a source with the same element type as
6294 // the original, but with a total width matching the BUILD_VECTOR output.
6295 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00006296 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6297 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00006298
6299 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6300 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006301 // We can pad out the smaller vector for free, so if it's part of a
6302 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00006303 Src.ShuffleVec =
6304 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6305 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00006306 continue;
6307 }
6308
Tim Northover7324e842014-07-24 15:39:55 +00006309 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006310
James Molloyf497d552014-10-17 17:06:31 +00006311 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006312 LLVM_DEBUG(
6313 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006314 return SDValue();
6315 }
6316
James Molloyf497d552014-10-17 17:06:31 +00006317 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006318 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00006319 Src.ShuffleVec =
6320 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006321 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00006322 Src.WindowBase = -NumSrcElts;
6323 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006324 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006325 Src.ShuffleVec =
6326 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006327 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006328 } else {
6329 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006330 SDValue VEXTSrc1 =
6331 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006332 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006333 SDValue VEXTSrc2 =
6334 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006335 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006336 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6337
6338 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006339 VEXTSrc2,
6340 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006341 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006342 }
6343 }
6344
Tim Northover7324e842014-07-24 15:39:55 +00006345 // Another possible incompatibility occurs from the vector element types. We
6346 // can fix this by bitcasting the source vectors to the same type we intend
6347 // for the shuffle.
6348 for (auto &Src : Sources) {
6349 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6350 if (SrcEltTy == SmallestEltTy)
6351 continue;
6352 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6353 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6354 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6355 Src.WindowBase *= Src.WindowScale;
6356 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006357
Tim Northover7324e842014-07-24 15:39:55 +00006358 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006359 LLVM_DEBUG(for (auto Src
6360 : Sources)
6361 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006362
6363 // The stars all align, our next step is to produce the mask for the shuffle.
6364 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006365 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006366 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006367 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006368 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006369 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006370
David Majnemer0d955d02016-08-11 22:21:41 +00006371 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006372 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6373
6374 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6375 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6376 // segment.
6377 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006378 int BitsDefined =
6379 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006380 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6381
6382 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6383 // starting at the appropriate offset.
6384 int *LaneMask = &Mask[i * ResMultiplier];
6385
6386 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6387 ExtractBase += NumElts * (Src - Sources.begin());
6388 for (int j = 0; j < LanesDefined; ++j)
6389 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006390 }
6391
6392 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006393 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006394 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006395 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006396 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006397
Tim Northover7324e842014-07-24 15:39:55 +00006398 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6399 for (unsigned i = 0; i < Sources.size(); ++i)
6400 ShuffleOps[i] = Sources[i].ShuffleVec;
6401
6402 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006403 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006404 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6405
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006406 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6407 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006408
6409 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006410}
6411
6412// check if an EXT instruction can handle the shuffle mask when the
6413// vector sources of the shuffle are the same.
6414static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6415 unsigned NumElts = VT.getVectorNumElements();
6416
6417 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6418 if (M[0] < 0)
6419 return false;
6420
6421 Imm = M[0];
6422
6423 // If this is a VEXT shuffle, the immediate value is the index of the first
6424 // element. The other shuffle indices must be the successive elements after
6425 // the first one.
6426 unsigned ExpectedElt = Imm;
6427 for (unsigned i = 1; i < NumElts; ++i) {
6428 // Increment the expected index. If it wraps around, just follow it
6429 // back to index zero and keep going.
6430 ++ExpectedElt;
6431 if (ExpectedElt == NumElts)
6432 ExpectedElt = 0;
6433
6434 if (M[i] < 0)
6435 continue; // ignore UNDEF indices
6436 if (ExpectedElt != static_cast<unsigned>(M[i]))
6437 return false;
6438 }
6439
6440 return true;
6441}
6442
6443// check if an EXT instruction can handle the shuffle mask when the
6444// vector sources of the shuffle are different.
6445static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6446 unsigned &Imm) {
6447 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006448 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006449
6450 // Benefit form APInt to handle overflow when calculating expected element.
6451 unsigned NumElts = VT.getVectorNumElements();
6452 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6453 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6454 // The following shuffle indices must be the successive elements after the
6455 // first real element.
6456 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6457 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6458 if (FirstWrongElt != M.end())
6459 return false;
6460
6461 // The index of an EXT is the first element if it is not UNDEF.
6462 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006463 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006464 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6465 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6466 // ExpectedElt is the last mask index plus 1.
6467 Imm = ExpectedElt.getZExtValue();
6468
6469 // There are two difference cases requiring to reverse input vectors.
6470 // For example, for vector <4 x i32> we have the following cases,
6471 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6472 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6473 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6474 // to reverse two input vectors.
6475 if (Imm < NumElts)
6476 ReverseEXT = true;
6477 else
6478 Imm -= NumElts;
6479
6480 return true;
6481}
6482
6483/// isREVMask - Check if a vector shuffle corresponds to a REV
6484/// instruction with the specified blocksize. (The order of the elements
6485/// within each block of the vector is reversed.)
6486static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6487 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6488 "Only possible block sizes for REV are: 16, 32, 64");
6489
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006490 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006491 if (EltSz == 64)
6492 return false;
6493
6494 unsigned NumElts = VT.getVectorNumElements();
6495 unsigned BlockElts = M[0] + 1;
6496 // If the first shuffle index is UNDEF, be optimistic.
6497 if (M[0] < 0)
6498 BlockElts = BlockSize / EltSz;
6499
6500 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6501 return false;
6502
6503 for (unsigned i = 0; i < NumElts; ++i) {
6504 if (M[i] < 0)
6505 continue; // ignore UNDEF indices
6506 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6507 return false;
6508 }
6509
6510 return true;
6511}
6512
6513static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6514 unsigned NumElts = VT.getVectorNumElements();
Florian Hahne3ea97b2019-08-05 11:12:23 +00006515 if (NumElts % 2 != 0)
6516 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006517 WhichResult = (M[0] == 0 ? 0 : 1);
6518 unsigned Idx = WhichResult * NumElts / 2;
6519 for (unsigned i = 0; i != NumElts; i += 2) {
6520 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6521 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6522 return false;
6523 Idx += 1;
6524 }
6525
6526 return true;
6527}
6528
6529static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6530 unsigned NumElts = VT.getVectorNumElements();
6531 WhichResult = (M[0] == 0 ? 0 : 1);
6532 for (unsigned i = 0; i != NumElts; ++i) {
6533 if (M[i] < 0)
6534 continue; // ignore UNDEF indices
6535 if ((unsigned)M[i] != 2 * i + WhichResult)
6536 return false;
6537 }
6538
6539 return true;
6540}
6541
6542static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6543 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006544 if (NumElts % 2 != 0)
6545 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006546 WhichResult = (M[0] == 0 ? 0 : 1);
6547 for (unsigned i = 0; i < NumElts; i += 2) {
6548 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6549 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6550 return false;
6551 }
6552 return true;
6553}
6554
6555/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6556/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6557/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6558static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6559 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006560 if (NumElts % 2 != 0)
6561 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006562 WhichResult = (M[0] == 0 ? 0 : 1);
6563 unsigned Idx = WhichResult * NumElts / 2;
6564 for (unsigned i = 0; i != NumElts; i += 2) {
6565 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6566 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6567 return false;
6568 Idx += 1;
6569 }
6570
6571 return true;
6572}
6573
6574/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6575/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6576/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6577static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6578 unsigned Half = VT.getVectorNumElements() / 2;
6579 WhichResult = (M[0] == 0 ? 0 : 1);
6580 for (unsigned j = 0; j != 2; ++j) {
6581 unsigned Idx = WhichResult;
6582 for (unsigned i = 0; i != Half; ++i) {
6583 int MIdx = M[i + j * Half];
6584 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6585 return false;
6586 Idx += 2;
6587 }
6588 }
6589
6590 return true;
6591}
6592
6593/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6594/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6595/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6596static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6597 unsigned NumElts = VT.getVectorNumElements();
Florian Hahn4a8835c2019-05-21 10:05:26 +00006598 if (NumElts % 2 != 0)
6599 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006600 WhichResult = (M[0] == 0 ? 0 : 1);
6601 for (unsigned i = 0; i < NumElts; i += 2) {
6602 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6603 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6604 return false;
6605 }
6606 return true;
6607}
6608
6609static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6610 bool &DstIsLeft, int &Anomaly) {
6611 if (M.size() != static_cast<size_t>(NumInputElements))
6612 return false;
6613
6614 int NumLHSMatch = 0, NumRHSMatch = 0;
6615 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6616
6617 for (int i = 0; i < NumInputElements; ++i) {
6618 if (M[i] == -1) {
6619 ++NumLHSMatch;
6620 ++NumRHSMatch;
6621 continue;
6622 }
6623
6624 if (M[i] == i)
6625 ++NumLHSMatch;
6626 else
6627 LastLHSMismatch = i;
6628
6629 if (M[i] == i + NumInputElements)
6630 ++NumRHSMatch;
6631 else
6632 LastRHSMismatch = i;
6633 }
6634
6635 if (NumLHSMatch == NumInputElements - 1) {
6636 DstIsLeft = true;
6637 Anomaly = LastLHSMismatch;
6638 return true;
6639 } else if (NumRHSMatch == NumInputElements - 1) {
6640 DstIsLeft = false;
6641 Anomaly = LastRHSMismatch;
6642 return true;
6643 }
6644
6645 return false;
6646}
6647
6648static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6649 if (VT.getSizeInBits() != 128)
6650 return false;
6651
6652 unsigned NumElts = VT.getVectorNumElements();
6653
6654 for (int I = 0, E = NumElts / 2; I != E; I++) {
6655 if (Mask[I] != I)
6656 return false;
6657 }
6658
6659 int Offset = NumElts / 2;
6660 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6661 if (Mask[I] != I + SplitLHS * Offset)
6662 return false;
6663 }
6664
6665 return true;
6666}
6667
6668static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6669 SDLoc DL(Op);
6670 EVT VT = Op.getValueType();
6671 SDValue V0 = Op.getOperand(0);
6672 SDValue V1 = Op.getOperand(1);
6673 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6674
6675 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6676 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6677 return SDValue();
6678
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006679 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006680
6681 if (!isConcatMask(Mask, VT, SplitV0))
6682 return SDValue();
6683
Simon Pilgrimc88408c2019-08-23 12:37:09 +00006684 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00006685 if (SplitV0) {
6686 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006687 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006688 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006689 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006690 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006691 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006692 }
6693 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6694}
6695
6696/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6697/// the specified operations to build the shuffle.
6698static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6699 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006700 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006701 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6702 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6703 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6704
6705 enum {
6706 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6707 OP_VREV,
6708 OP_VDUP0,
6709 OP_VDUP1,
6710 OP_VDUP2,
6711 OP_VDUP3,
6712 OP_VEXT1,
6713 OP_VEXT2,
6714 OP_VEXT3,
6715 OP_VUZPL, // VUZP, left result
6716 OP_VUZPR, // VUZP, right result
6717 OP_VZIPL, // VZIP, left result
6718 OP_VZIPR, // VZIP, right result
6719 OP_VTRNL, // VTRN, left result
6720 OP_VTRNR // VTRN, right result
6721 };
6722
6723 if (OpNum == OP_COPY) {
6724 if (LHSID == (1 * 9 + 2) * 9 + 3)
6725 return LHS;
6726 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6727 return RHS;
6728 }
6729
6730 SDValue OpLHS, OpRHS;
6731 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6732 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6733 EVT VT = OpLHS.getValueType();
6734
6735 switch (OpNum) {
6736 default:
6737 llvm_unreachable("Unknown shuffle opcode!");
6738 case OP_VREV:
6739 // VREV divides the vector in half and swaps within the half.
6740 if (VT.getVectorElementType() == MVT::i32 ||
6741 VT.getVectorElementType() == MVT::f32)
6742 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6743 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006744 if (VT.getVectorElementType() == MVT::i16 ||
6745 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006746 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6747 // vrev <4 x i8> -> REV16
6748 assert(VT.getVectorElementType() == MVT::i8);
6749 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6750 case OP_VDUP0:
6751 case OP_VDUP1:
6752 case OP_VDUP2:
6753 case OP_VDUP3: {
6754 EVT EltTy = VT.getVectorElementType();
6755 unsigned Opcode;
6756 if (EltTy == MVT::i8)
6757 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006758 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006759 Opcode = AArch64ISD::DUPLANE16;
6760 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6761 Opcode = AArch64ISD::DUPLANE32;
6762 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6763 Opcode = AArch64ISD::DUPLANE64;
6764 else
6765 llvm_unreachable("Invalid vector element type?");
6766
6767 if (VT.getSizeInBits() == 64)
6768 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006769 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006770 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6771 }
6772 case OP_VEXT1:
6773 case OP_VEXT2:
6774 case OP_VEXT3: {
6775 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6776 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006777 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006778 }
6779 case OP_VUZPL:
6780 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6781 OpRHS);
6782 case OP_VUZPR:
6783 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6784 OpRHS);
6785 case OP_VZIPL:
6786 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6787 OpRHS);
6788 case OP_VZIPR:
6789 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6790 OpRHS);
6791 case OP_VTRNL:
6792 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6793 OpRHS);
6794 case OP_VTRNR:
6795 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6796 OpRHS);
6797 }
6798}
6799
6800static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6801 SelectionDAG &DAG) {
6802 // Check to see if we can use the TBL instruction.
6803 SDValue V1 = Op.getOperand(0);
6804 SDValue V2 = Op.getOperand(1);
6805 SDLoc DL(Op);
6806
6807 EVT EltVT = Op.getValueType().getVectorElementType();
6808 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6809
6810 SmallVector<SDValue, 8> TBLMask;
6811 for (int Val : ShuffleMask) {
6812 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6813 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006814 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006815 }
6816 }
6817
6818 MVT IndexVT = MVT::v8i8;
6819 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006820 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006821 IndexVT = MVT::v16i8;
6822 IndexLen = 16;
6823 }
6824
6825 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6826 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6827
6828 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006829 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006830 if (IndexLen == 8)
6831 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6832 Shuffle = DAG.getNode(
6833 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006834 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006835 DAG.getBuildVector(IndexVT, DL,
6836 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006837 } else {
6838 if (IndexLen == 8) {
6839 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6840 Shuffle = DAG.getNode(
6841 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006842 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006843 DAG.getBuildVector(IndexVT, DL,
6844 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006845 } else {
6846 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6847 // cannot currently represent the register constraints on the input
6848 // table registers.
6849 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006850 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6851 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006852 Shuffle = DAG.getNode(
6853 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006854 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6855 V2Cst, DAG.getBuildVector(IndexVT, DL,
6856 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006857 }
6858 }
6859 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6860}
6861
6862static unsigned getDUPLANEOp(EVT EltType) {
6863 if (EltType == MVT::i8)
6864 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006865 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006866 return AArch64ISD::DUPLANE16;
6867 if (EltType == MVT::i32 || EltType == MVT::f32)
6868 return AArch64ISD::DUPLANE32;
6869 if (EltType == MVT::i64 || EltType == MVT::f64)
6870 return AArch64ISD::DUPLANE64;
6871
6872 llvm_unreachable("Invalid vector element type?");
6873}
6874
6875SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6876 SelectionDAG &DAG) const {
6877 SDLoc dl(Op);
6878 EVT VT = Op.getValueType();
6879
6880 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6881
6882 // Convert shuffles that are directly supported on NEON to target-specific
6883 // DAG nodes, instead of keeping them as shuffles and matching them again
6884 // during code selection. This is more efficient and avoids the possibility
6885 // of inconsistencies between legalization and selection.
6886 ArrayRef<int> ShuffleMask = SVN->getMask();
6887
6888 SDValue V1 = Op.getOperand(0);
6889 SDValue V2 = Op.getOperand(1);
6890
Craig Topperbc56e3b2016-06-30 04:38:51 +00006891 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006892 int Lane = SVN->getSplatIndex();
6893 // If this is undef splat, generate it via "just" vdup, if possible.
6894 if (Lane == -1)
6895 Lane = 0;
6896
6897 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6898 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6899 V1.getOperand(0));
6900 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6901 // constant. If so, we can just reference the lane's definition directly.
6902 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6903 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6904 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6905
6906 // Otherwise, duplicate from the lane of the input vector.
6907 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6908
6909 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6910 // to make a vector of the same size as this SHUFFLE. We can ignore the
6911 // extract entirely, and canonicalise the concat using WidenVector.
6912 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6913 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6914 V1 = V1.getOperand(0);
6915 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6916 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6917 Lane -= Idx * VT.getVectorNumElements() / 2;
6918 V1 = WidenVector(V1.getOperand(Idx), DAG);
6919 } else if (VT.getSizeInBits() == 64)
6920 V1 = WidenVector(V1, DAG);
6921
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006922 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006923 }
6924
6925 if (isREVMask(ShuffleMask, VT, 64))
6926 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6927 if (isREVMask(ShuffleMask, VT, 32))
6928 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6929 if (isREVMask(ShuffleMask, VT, 16))
6930 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6931
6932 bool ReverseEXT = false;
6933 unsigned Imm;
6934 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6935 if (ReverseEXT)
6936 std::swap(V1, V2);
6937 Imm *= getExtFactor(V1);
6938 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006939 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006940 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006941 Imm *= getExtFactor(V1);
6942 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006943 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006944 }
6945
6946 unsigned WhichResult;
6947 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6948 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6949 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6950 }
6951 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6952 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6953 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6954 }
6955 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6956 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6957 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6958 }
6959
6960 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6961 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6962 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6963 }
6964 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6965 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6966 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6967 }
6968 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6969 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6970 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6971 }
6972
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006973 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006974 return Concat;
6975
6976 bool DstIsLeft;
6977 int Anomaly;
6978 int NumInputElements = V1.getValueType().getVectorNumElements();
6979 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6980 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006981 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006982
6983 SDValue SrcVec = V1;
6984 int SrcLane = ShuffleMask[Anomaly];
6985 if (SrcLane >= NumInputElements) {
6986 SrcVec = V2;
6987 SrcLane -= VT.getVectorNumElements();
6988 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006989 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006990
6991 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006992
6993 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006994 ScalarVT = MVT::i32;
6995
6996 return DAG.getNode(
6997 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6998 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6999 DstLaneV);
7000 }
7001
7002 // If the shuffle is not directly supported and it has 4 elements, use
7003 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7004 unsigned NumElts = VT.getVectorNumElements();
7005 if (NumElts == 4) {
7006 unsigned PFIndexes[4];
7007 for (unsigned i = 0; i != 4; ++i) {
7008 if (ShuffleMask[i] < 0)
7009 PFIndexes[i] = 8;
7010 else
7011 PFIndexes[i] = ShuffleMask[i];
7012 }
7013
7014 // Compute the index in the perfect shuffle table.
7015 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7016 PFIndexes[2] * 9 + PFIndexes[3];
7017 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7018 unsigned Cost = (PFEntry >> 30);
7019
7020 if (Cost <= 4)
7021 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7022 }
7023
7024 return GenerateTBL(Op, ShuffleMask, DAG);
7025}
7026
7027static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7028 APInt &UndefBits) {
7029 EVT VT = BVN->getValueType(0);
7030 APInt SplatBits, SplatUndef;
7031 unsigned SplatBitSize;
7032 bool HasAnyUndefs;
7033 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7034 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7035
7036 for (unsigned i = 0; i < NumSplats; ++i) {
7037 CnstBits <<= SplatBitSize;
7038 UndefBits <<= SplatBitSize;
7039 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7040 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7041 }
7042
7043 return true;
7044 }
7045
7046 return false;
7047}
7048
Evandro Menezes72f39832018-02-20 20:31:45 +00007049// Try 64-bit splatted SIMD immediate.
7050static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7051 const APInt &Bits) {
7052 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7053 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7054 EVT VT = Op.getValueType();
7055 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7056
7057 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7058 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7059
7060 SDLoc dl(Op);
7061 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7062 DAG.getConstant(Value, dl, MVT::i32));
7063 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7064 }
7065 }
7066
7067 return SDValue();
7068}
7069
7070// Try 32-bit splatted SIMD immediate.
7071static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7072 const APInt &Bits,
7073 const SDValue *LHS = nullptr) {
7074 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7075 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7076 EVT VT = Op.getValueType();
7077 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7078 bool isAdvSIMDModImm = false;
7079 uint64_t Shift;
7080
7081 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7082 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7083 Shift = 0;
7084 }
7085 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7086 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7087 Shift = 8;
7088 }
7089 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7090 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7091 Shift = 16;
7092 }
7093 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7094 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7095 Shift = 24;
7096 }
7097
7098 if (isAdvSIMDModImm) {
7099 SDLoc dl(Op);
7100 SDValue Mov;
7101
7102 if (LHS)
7103 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7104 DAG.getConstant(Value, dl, MVT::i32),
7105 DAG.getConstant(Shift, dl, MVT::i32));
7106 else
7107 Mov = DAG.getNode(NewOp, dl, MovTy,
7108 DAG.getConstant(Value, dl, MVT::i32),
7109 DAG.getConstant(Shift, dl, MVT::i32));
7110
7111 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7112 }
7113 }
7114
7115 return SDValue();
7116}
7117
7118// Try 16-bit splatted SIMD immediate.
7119static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7120 const APInt &Bits,
7121 const SDValue *LHS = nullptr) {
7122 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7123 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7124 EVT VT = Op.getValueType();
7125 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7126 bool isAdvSIMDModImm = false;
7127 uint64_t Shift;
7128
7129 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7130 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7131 Shift = 0;
7132 }
7133 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7134 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7135 Shift = 8;
7136 }
7137
7138 if (isAdvSIMDModImm) {
7139 SDLoc dl(Op);
7140 SDValue Mov;
7141
7142 if (LHS)
7143 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00007144 DAG.getConstant(Value, dl, MVT::i32),
7145 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00007146 else
7147 Mov = DAG.getNode(NewOp, dl, MovTy,
7148 DAG.getConstant(Value, dl, MVT::i32),
7149 DAG.getConstant(Shift, dl, MVT::i32));
7150
7151 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7152 }
7153 }
7154
7155 return SDValue();
7156}
7157
7158// Try 32-bit splatted SIMD immediate with shifted ones.
7159static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7160 SelectionDAG &DAG, const APInt &Bits) {
7161 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7162 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7163 EVT VT = Op.getValueType();
7164 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7165 bool isAdvSIMDModImm = false;
7166 uint64_t Shift;
7167
7168 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7169 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7170 Shift = 264;
7171 }
7172 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7173 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7174 Shift = 272;
7175 }
7176
7177 if (isAdvSIMDModImm) {
7178 SDLoc dl(Op);
7179 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7180 DAG.getConstant(Value, dl, MVT::i32),
7181 DAG.getConstant(Shift, dl, MVT::i32));
7182 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7183 }
7184 }
7185
7186 return SDValue();
7187}
7188
7189// Try 8-bit splatted SIMD immediate.
7190static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7191 const APInt &Bits) {
7192 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7193 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7194 EVT VT = Op.getValueType();
7195 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7196
7197 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7198 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7199
7200 SDLoc dl(Op);
7201 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7202 DAG.getConstant(Value, dl, MVT::i32));
7203 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7204 }
7205 }
7206
7207 return SDValue();
7208}
7209
7210// Try FP splatted SIMD immediate.
7211static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7212 const APInt &Bits) {
7213 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7214 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7215 EVT VT = Op.getValueType();
7216 bool isWide = (VT.getSizeInBits() == 128);
7217 MVT MovTy;
7218 bool isAdvSIMDModImm = false;
7219
7220 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7221 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7222 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7223 }
7224 else if (isWide &&
7225 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7226 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7227 MovTy = MVT::v2f64;
7228 }
7229
7230 if (isAdvSIMDModImm) {
7231 SDLoc dl(Op);
7232 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7233 DAG.getConstant(Value, dl, MVT::i32));
7234 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7235 }
7236 }
7237
7238 return SDValue();
7239}
7240
Tim Northover3b0846e2014-05-24 12:50:23 +00007241// Specialized code to quickly find if PotentialBVec is a BuildVector that
7242// consists of only the same constant int value, returned in reference arg
7243// ConstVal
7244static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7245 uint64_t &ConstVal) {
7246 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7247 if (!Bvec)
7248 return false;
7249 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7250 if (!FirstElt)
7251 return false;
7252 EVT VT = Bvec->getValueType(0);
7253 unsigned NumElts = VT.getVectorNumElements();
7254 for (unsigned i = 1; i < NumElts; ++i)
7255 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7256 return false;
7257 ConstVal = FirstElt->getZExtValue();
7258 return true;
7259}
7260
7261static unsigned getIntrinsicID(const SDNode *N) {
7262 unsigned Opcode = N->getOpcode();
7263 switch (Opcode) {
7264 default:
7265 return Intrinsic::not_intrinsic;
7266 case ISD::INTRINSIC_WO_CHAIN: {
7267 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7268 if (IID < Intrinsic::num_intrinsics)
7269 return IID;
7270 return Intrinsic::not_intrinsic;
7271 }
7272 }
7273}
7274
7275// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7276// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7277// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7278// Also, logical shift right -> sri, with the same structure.
7279static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7280 EVT VT = N->getValueType(0);
7281
7282 if (!VT.isVector())
7283 return SDValue();
7284
7285 SDLoc DL(N);
7286
7287 // Is the first op an AND?
7288 const SDValue And = N->getOperand(0);
7289 if (And.getOpcode() != ISD::AND)
7290 return SDValue();
7291
7292 // Is the second op an shl or lshr?
7293 SDValue Shift = N->getOperand(1);
7294 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7295 // or AArch64ISD::VLSHR vector, #shift
7296 unsigned ShiftOpc = Shift.getOpcode();
7297 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7298 return SDValue();
7299 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7300
7301 // Is the shift amount constant?
7302 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7303 if (!C2node)
7304 return SDValue();
7305
7306 // Is the and mask vector all constant?
7307 uint64_t C1;
7308 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7309 return SDValue();
7310
7311 // Is C1 == ~C2, taking into account how much one can shift elements of a
7312 // particular size?
7313 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007314 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007315 if (C2 > ElemSizeInBits)
7316 return SDValue();
7317 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7318 if ((C1 & ElemMask) != (~C2 & ElemMask))
7319 return SDValue();
7320
7321 SDValue X = And.getOperand(0);
7322 SDValue Y = Shift.getOperand(0);
7323
7324 unsigned Intrin =
7325 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7326 SDValue ResultSLI =
7327 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007328 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7329 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007330
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007331 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7332 LLVM_DEBUG(N->dump(&DAG));
7333 LLVM_DEBUG(dbgs() << "into: \n");
7334 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007335
7336 ++NumShiftInserts;
7337 return ResultSLI;
7338}
7339
7340SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7341 SelectionDAG &DAG) const {
7342 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7343 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007344 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007345 return Res;
7346 }
7347
Tim Northover3b0846e2014-05-24 12:50:23 +00007348 EVT VT = Op.getValueType();
7349
Evandro Menezescd855f72018-03-05 17:02:47 +00007350 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007351 BuildVectorSDNode *BVN =
7352 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007353 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007354 // OR commutes, so try swapping the operands.
7355 LHS = Op.getOperand(1);
7356 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007357 }
7358 if (!BVN)
7359 return Op;
7360
Evandro Menezes72f39832018-02-20 20:31:45 +00007361 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007362 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007363 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7364 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007365
Evandro Menezes72f39832018-02-20 20:31:45 +00007366 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7367 DefBits, &LHS)) ||
7368 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7369 DefBits, &LHS)))
7370 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007371
7372 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7373 UndefBits, &LHS)) ||
7374 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7375 UndefBits, &LHS)))
7376 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007377 }
7378
Evandro Menezes72f39832018-02-20 20:31:45 +00007379 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007380 return Op;
7381}
7382
Kevin Qin4473c192014-07-07 02:45:40 +00007383// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7384// be truncated to fit element width.
7385static SDValue NormalizeBuildVector(SDValue Op,
7386 SelectionDAG &DAG) {
7387 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007388 SDLoc dl(Op);
7389 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007390 EVT EltTy= VT.getVectorElementType();
7391
7392 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7393 return Op;
7394
7395 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007396 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007397 // For integer vectors, type legalization would have promoted the
7398 // operands already. Otherwise, if Op is a floating-point splat
7399 // (with operands cast to integers), then the only possibilities
7400 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007401 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007402 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007403 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007404 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007405 } else if (Lane.getNode()->isUndef()) {
7406 Lane = DAG.getUNDEF(MVT::i32);
7407 } else {
7408 assert(Lane.getValueType() == MVT::i32 &&
7409 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007410 }
7411 Ops.push_back(Lane);
7412 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007413 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007414}
7415
Evandro Menezescd855f72018-03-05 17:02:47 +00007416static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007417 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007418
Evandro Menezes72f39832018-02-20 20:31:45 +00007419 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007420 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007421 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007422 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007423 SDValue NewOp;
7424 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7425 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7426 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7427 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7428 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7429 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7430 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007431
Evandro Menezes72f39832018-02-20 20:31:45 +00007432 DefBits = ~DefBits;
7433 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7434 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7435 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7436 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007437
Evandro Menezes72f39832018-02-20 20:31:45 +00007438 DefBits = UndefBits;
7439 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7440 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7441 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7442 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7443 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7444 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7445 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007446
Evandro Menezes72f39832018-02-20 20:31:45 +00007447 DefBits = ~UndefBits;
7448 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7449 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7450 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7451 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007452 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007453
Evandro Menezescd855f72018-03-05 17:02:47 +00007454 return SDValue();
7455}
7456
7457SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7458 SelectionDAG &DAG) const {
7459 EVT VT = Op.getValueType();
7460
7461 // Try to build a simple constant vector.
7462 Op = NormalizeBuildVector(Op, DAG);
7463 if (VT.isInteger()) {
7464 // Certain vector constants, used to express things like logical NOT and
7465 // arithmetic NEG, are passed through unmodified. This allows special
7466 // patterns for these operations to match, which will lower these constants
7467 // to whatever is proven necessary.
7468 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7469 if (BVN->isConstant())
7470 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7471 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7472 APInt Val(BitSize,
7473 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7474 if (Val.isNullValue() || Val.isAllOnesValue())
7475 return Op;
7476 }
7477 }
7478
7479 if (SDValue V = ConstantBuildVector(Op, DAG))
7480 return V;
7481
Tim Northover3b0846e2014-05-24 12:50:23 +00007482 // Scan through the operands to find some interesting properties we can
7483 // exploit:
7484 // 1) If only one value is used, we can use a DUP, or
7485 // 2) if only the low element is not undef, we can just insert that, or
7486 // 3) if only one constant value is used (w/ some non-constant lanes),
7487 // we can splat the constant value into the whole vector then fill
7488 // in the non-constant lanes.
7489 // 4) FIXME: If different constant values are used, but we can intelligently
7490 // select the values we'll be overwriting for the non-constant
7491 // lanes such that we can directly materialize the vector
7492 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007493 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007494 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007495 unsigned NumElts = VT.getVectorNumElements();
7496 bool isOnlyLowElement = true;
7497 bool usesOnlyOneValue = true;
7498 bool usesOnlyOneConstantValue = true;
7499 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007500 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007501 unsigned NumConstantLanes = 0;
7502 SDValue Value;
7503 SDValue ConstantValue;
7504 for (unsigned i = 0; i < NumElts; ++i) {
7505 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007506 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7507 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007508 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007509 continue;
7510 if (i > 0)
7511 isOnlyLowElement = false;
7512 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7513 isConstant = false;
7514
7515 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7516 ++NumConstantLanes;
7517 if (!ConstantValue.getNode())
7518 ConstantValue = V;
7519 else if (ConstantValue != V)
7520 usesOnlyOneConstantValue = false;
7521 }
7522
7523 if (!Value.getNode())
7524 Value = V;
7525 else if (V != Value)
7526 usesOnlyOneValue = false;
7527 }
7528
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007529 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007530 LLVM_DEBUG(
7531 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007532 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007533 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007534
John Brawnd6e0ebe2018-11-22 11:45:23 +00007535 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7536 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7537 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7538 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007539 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7540 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007541 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007542 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007543
Sebastian Popc33af712018-03-01 15:47:39 +00007544 if (AllLanesExtractElt) {
7545 SDNode *Vector = nullptr;
7546 bool Even = false;
7547 bool Odd = false;
7548 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7549 // the Odd pattern <1,3,5,...>.
7550 for (unsigned i = 0; i < NumElts; ++i) {
7551 SDValue V = Op.getOperand(i);
7552 const SDNode *N = V.getNode();
7553 if (!isa<ConstantSDNode>(N->getOperand(1)))
7554 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007555 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007556
7557 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007558 if (!Vector) {
7559 Vector = N0.getNode();
7560 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7561 // BUILD_VECTOR.
7562 if (VT.getVectorElementType() !=
7563 N0.getValueType().getVectorElementType())
7564 break;
7565 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007566 Odd = false;
7567 Even = false;
7568 break;
7569 }
7570
7571 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7572 // indices <1,3,5,...>.
7573 uint64_t Val = N->getConstantOperandVal(1);
7574 if (Val == 2 * i) {
7575 Even = true;
7576 continue;
7577 }
7578 if (Val - 1 == 2 * i) {
7579 Odd = true;
7580 continue;
7581 }
7582
7583 // Something does not match: abort.
7584 Odd = false;
7585 Even = false;
7586 break;
7587 }
7588 if (Even || Odd) {
7589 SDValue LHS =
7590 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7591 DAG.getConstant(0, dl, MVT::i64));
7592 SDValue RHS =
7593 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7594 DAG.getConstant(NumElts, dl, MVT::i64));
7595
7596 if (Even && !Odd)
7597 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7598 RHS);
7599 if (Odd && !Even)
7600 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7601 RHS);
7602 }
7603 }
7604
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007605 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007606 // i32 and try again.
7607 if (usesOnlyOneValue) {
7608 if (!isConstant) {
7609 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007610 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007611 LLVM_DEBUG(
7612 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007613 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007614 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007615
7616 // This is actually a DUPLANExx operation, which keeps everything vectory.
7617
Tim Northover3b0846e2014-05-24 12:50:23 +00007618 SDValue Lane = Value.getOperand(1);
7619 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007620 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007621 LLVM_DEBUG(
7622 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7623 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007624 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007625 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007626
7627 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7628 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7629 }
7630
7631 if (VT.getVectorElementType().isFloatingPoint()) {
7632 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007633 EVT EltTy = VT.getVectorElementType();
7634 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7635 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007636 LLVM_DEBUG(
7637 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7638 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007639 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007640 for (unsigned i = 0; i < NumElts; ++i)
7641 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7642 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007643 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007644 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7645 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007646 Val = LowerBUILD_VECTOR(Val, DAG);
7647 if (Val.getNode())
7648 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7649 }
7650 }
7651
7652 // If there was only one constant value used and for more than one lane,
7653 // start by splatting that value, then replace the non-constant lanes. This
7654 // is better than the default, which will perform a separate initialization
7655 // for each lane.
7656 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007657 // Firstly, try to materialize the splat constant.
7658 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7659 Val = ConstantBuildVector(Vec, DAG);
7660 if (!Val) {
7661 // Otherwise, materialize the constant and splat it.
7662 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7663 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7664 }
7665
Tim Northover3b0846e2014-05-24 12:50:23 +00007666 // Now insert the non-constant lanes.
7667 for (unsigned i = 0; i < NumElts; ++i) {
7668 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007669 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007670 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007671 // Note that type legalization likely mucked about with the VT of the
7672 // source operand, so we may have to convert it here before inserting.
7673 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007674 }
7675 return Val;
7676 }
7677
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007678 // This will generate a load from the constant pool.
7679 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007680 LLVM_DEBUG(
7681 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7682 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007683 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007684 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007685
7686 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7687 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007688 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007689 return shuffle;
7690 }
7691
7692 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7693 // know the default expansion would otherwise fall back on something even
7694 // worse. For a vector with one or two non-undef values, that's
7695 // scalar_to_vector for the elements followed by a shuffle (provided the
7696 // shuffle is valid for the target) and materialization element by element
7697 // on the stack followed by a load for everything else.
7698 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007699 LLVM_DEBUG(
7700 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7701 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007702
Tim Northover3b0846e2014-05-24 12:50:23 +00007703 SDValue Vec = DAG.getUNDEF(VT);
7704 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007705 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007706
7707 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007708 // a) Avoid a RMW dependency on the full vector register, and
7709 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007710 // value is already in an S or D register, and we're forced to emit an
7711 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007712 //
7713 // We also allow types like i8 and i16 which are illegal scalar but legal
7714 // vector element types. After type-legalization the inserted value is
7715 // extended (i32) and it is safe to cast them to the vector type by ignoring
7716 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7717 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007718 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007719 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007720 ++i;
7721 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007722 LLVM_DEBUG(if (i < NumElts) dbgs()
7723 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007724 for (; i < NumElts; ++i) {
7725 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007726 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007727 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007728 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007729 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7730 }
7731 return Vec;
7732 }
7733
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007734 LLVM_DEBUG(
7735 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7736 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007737 return SDValue();
7738}
7739
7740SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7741 SelectionDAG &DAG) const {
7742 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7743
Tim Northovere4b8e132014-07-15 10:00:26 +00007744 // Check for non-constant or out of range lane.
7745 EVT VT = Op.getOperand(0).getValueType();
7746 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7747 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007748 return SDValue();
7749
Tim Northover3b0846e2014-05-24 12:50:23 +00007750
7751 // Insertion/extraction are legal for V128 types.
7752 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007753 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7754 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007755 return Op;
7756
7757 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007758 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007759 return SDValue();
7760
7761 // For V64 types, we perform insertion by expanding the value
7762 // to a V128 type and perform the insertion on that.
7763 SDLoc DL(Op);
7764 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7765 EVT WideTy = WideVec.getValueType();
7766
7767 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7768 Op.getOperand(1), Op.getOperand(2));
7769 // Re-narrow the resultant vector.
7770 return NarrowVector(Node, DAG);
7771}
7772
7773SDValue
7774AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7775 SelectionDAG &DAG) const {
7776 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7777
Tim Northovere4b8e132014-07-15 10:00:26 +00007778 // Check for non-constant or out of range lane.
7779 EVT VT = Op.getOperand(0).getValueType();
7780 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7781 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007782 return SDValue();
7783
Tim Northover3b0846e2014-05-24 12:50:23 +00007784
7785 // Insertion/extraction are legal for V128 types.
7786 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007787 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7788 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007789 return Op;
7790
7791 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007792 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007793 return SDValue();
7794
7795 // For V64 types, we perform extraction by expanding the value
7796 // to a V128 type and perform the extraction on that.
7797 SDLoc DL(Op);
7798 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7799 EVT WideTy = WideVec.getValueType();
7800
7801 EVT ExtrTy = WideTy.getVectorElementType();
7802 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7803 ExtrTy = MVT::i32;
7804
7805 // For extractions, we just return the result directly.
7806 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7807 Op.getOperand(1));
7808}
7809
7810SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7811 SelectionDAG &DAG) const {
7812 EVT VT = Op.getOperand(0).getValueType();
7813 SDLoc dl(Op);
7814 // Just in case...
7815 if (!VT.isVector())
7816 return SDValue();
7817
7818 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7819 if (!Cst)
7820 return SDValue();
7821 unsigned Val = Cst->getZExtValue();
7822
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007823 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007824
7825 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7826 if (Val == 0)
7827 return Op;
7828
Tim Northover3b0846e2014-05-24 12:50:23 +00007829 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7830 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007831 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007832 return Op;
7833
7834 return SDValue();
7835}
7836
Zvi Rackover1b736822017-07-26 08:06:58 +00007837bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007838 if (VT.getVectorNumElements() == 4 &&
7839 (VT.is128BitVector() || VT.is64BitVector())) {
7840 unsigned PFIndexes[4];
7841 for (unsigned i = 0; i != 4; ++i) {
7842 if (M[i] < 0)
7843 PFIndexes[i] = 8;
7844 else
7845 PFIndexes[i] = M[i];
7846 }
7847
7848 // Compute the index in the perfect shuffle table.
7849 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7850 PFIndexes[2] * 9 + PFIndexes[3];
7851 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7852 unsigned Cost = (PFEntry >> 30);
7853
7854 if (Cost <= 4)
7855 return true;
7856 }
7857
7858 bool DummyBool;
7859 int DummyInt;
7860 unsigned DummyUnsigned;
7861
7862 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7863 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7864 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7865 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7866 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7867 isZIPMask(M, VT, DummyUnsigned) ||
7868 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7869 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7870 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7871 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7872 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7873}
7874
7875/// getVShiftImm - Check if this is a valid build_vector for the immediate
7876/// operand of a vector shift operation, where all the elements of the
7877/// build_vector must have the same constant integer value.
7878static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7879 // Ignore bit_converts.
7880 while (Op.getOpcode() == ISD::BITCAST)
7881 Op = Op.getOperand(0);
7882 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7883 APInt SplatBits, SplatUndef;
7884 unsigned SplatBitSize;
7885 bool HasAnyUndefs;
7886 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7887 HasAnyUndefs, ElementBits) ||
7888 SplatBitSize > ElementBits)
7889 return false;
7890 Cnt = SplatBits.getSExtValue();
7891 return true;
7892}
7893
7894/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7895/// operand of a vector shift left operation. That value must be in the range:
7896/// 0 <= Value < ElementBits for a left shift; or
7897/// 0 <= Value <= ElementBits for a long left shift.
7898static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7899 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007900 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007901 if (!getVShiftImm(Op, ElementBits, Cnt))
7902 return false;
7903 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7904}
7905
7906/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007907/// operand of a vector shift right operation. The value must be in the range:
7908/// 1 <= Value <= ElementBits for a right shift; or
7909static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007910 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007911 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007912 if (!getVShiftImm(Op, ElementBits, Cnt))
7913 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007914 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7915}
7916
7917SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7918 SelectionDAG &DAG) const {
7919 EVT VT = Op.getValueType();
7920 SDLoc DL(Op);
7921 int64_t Cnt;
7922
7923 if (!Op.getOperand(1).getValueType().isVector())
7924 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007925 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007926
7927 switch (Op.getOpcode()) {
7928 default:
7929 llvm_unreachable("unexpected shift opcode");
7930
7931 case ISD::SHL:
7932 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007933 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7934 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007935 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007936 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7937 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007938 Op.getOperand(0), Op.getOperand(1));
7939 case ISD::SRA:
7940 case ISD::SRL:
7941 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007942 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007943 unsigned Opc =
7944 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007945 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7946 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007947 }
7948
7949 // Right shift register. Note, there is not a shift right register
7950 // instruction, but the shift left register instruction takes a signed
7951 // value, where negative numbers specify a right shift.
7952 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7953 : Intrinsic::aarch64_neon_ushl;
7954 // negate the shift amount
7955 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7956 SDValue NegShiftLeft =
7957 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007958 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7959 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007960 return NegShiftLeft;
7961 }
7962
7963 return SDValue();
7964}
7965
7966static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7967 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007968 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007969 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007970 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7971 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007972
7973 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7974 APInt CnstBits(VT.getSizeInBits(), 0);
7975 APInt UndefBits(VT.getSizeInBits(), 0);
7976 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7977 bool IsZero = IsCnst && (CnstBits == 0);
7978
7979 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7980 switch (CC) {
7981 default:
7982 return SDValue();
7983 case AArch64CC::NE: {
7984 SDValue Fcmeq;
7985 if (IsZero)
7986 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7987 else
7988 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7989 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7990 }
7991 case AArch64CC::EQ:
7992 if (IsZero)
7993 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7994 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7995 case AArch64CC::GE:
7996 if (IsZero)
7997 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7998 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7999 case AArch64CC::GT:
8000 if (IsZero)
8001 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8002 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8003 case AArch64CC::LS:
8004 if (IsZero)
8005 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8006 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8007 case AArch64CC::LT:
8008 if (!NoNans)
8009 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00008010 // If we ignore NaNs then we can use to the MI implementation.
8011 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00008012 case AArch64CC::MI:
8013 if (IsZero)
8014 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8015 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8016 }
8017 }
8018
8019 switch (CC) {
8020 default:
8021 return SDValue();
8022 case AArch64CC::NE: {
8023 SDValue Cmeq;
8024 if (IsZero)
8025 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8026 else
8027 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8028 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8029 }
8030 case AArch64CC::EQ:
8031 if (IsZero)
8032 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8033 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8034 case AArch64CC::GE:
8035 if (IsZero)
8036 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8037 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8038 case AArch64CC::GT:
8039 if (IsZero)
8040 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8041 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8042 case AArch64CC::LE:
8043 if (IsZero)
8044 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8045 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8046 case AArch64CC::LS:
8047 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8048 case AArch64CC::LO:
8049 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8050 case AArch64CC::LT:
8051 if (IsZero)
8052 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8053 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8054 case AArch64CC::HI:
8055 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8056 case AArch64CC::HS:
8057 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8058 }
8059}
8060
8061SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8062 SelectionDAG &DAG) const {
8063 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8064 SDValue LHS = Op.getOperand(0);
8065 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00008066 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00008067 SDLoc dl(Op);
8068
8069 if (LHS.getValueType().getVectorElementType().isInteger()) {
8070 assert(LHS.getValueType() == RHS.getValueType());
8071 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00008072 SDValue Cmp =
8073 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8074 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00008075 }
8076
Carey Williamsda15b5b2018-01-22 14:16:11 +00008077 const bool FullFP16 =
8078 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8079
8080 // Make v4f16 (only) fcmp operations utilise vector instructions
8081 // v8f16 support will be a litle more complicated
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00008082 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8083 if (LHS.getValueType().getVectorNumElements() == 4) {
Carey Williamsda15b5b2018-01-22 14:16:11 +00008084 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8085 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8086 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8087 DAG.ReplaceAllUsesWith(Op, NewSetcc);
8088 CmpVT = MVT::v4i32;
8089 } else
8090 return SDValue();
8091 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00008092
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00008093 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8094 LHS.getValueType().getVectorElementType() != MVT::f128);
Tim Northover3b0846e2014-05-24 12:50:23 +00008095
8096 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8097 // clean. Some of them require two branches to implement.
8098 AArch64CC::CondCode CC1, CC2;
8099 bool ShouldInvert;
8100 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8101
8102 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8103 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00008104 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008105 if (!Cmp.getNode())
8106 return SDValue();
8107
8108 if (CC2 != AArch64CC::AL) {
8109 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00008110 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008111 if (!Cmp2.getNode())
8112 return SDValue();
8113
Tim Northover45aa89c2015-02-08 00:50:47 +00008114 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008115 }
8116
Tim Northover45aa89c2015-02-08 00:50:47 +00008117 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8118
Tim Northover3b0846e2014-05-24 12:50:23 +00008119 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00008120 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00008121
8122 return Cmp;
8123}
8124
Amara Emersonc9916d72017-05-16 21:29:22 +00008125static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8126 SelectionDAG &DAG) {
8127 SDValue VecOp = ScalarOp.getOperand(0);
8128 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8129 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8130 DAG.getConstant(0, DL, MVT::i64));
8131}
8132
8133SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8134 SelectionDAG &DAG) const {
8135 SDLoc dl(Op);
8136 switch (Op.getOpcode()) {
8137 case ISD::VECREDUCE_ADD:
8138 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8139 case ISD::VECREDUCE_SMAX:
8140 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8141 case ISD::VECREDUCE_SMIN:
8142 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8143 case ISD::VECREDUCE_UMAX:
8144 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8145 case ISD::VECREDUCE_UMIN:
8146 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8147 case ISD::VECREDUCE_FMAX: {
8148 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8149 return DAG.getNode(
8150 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8151 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8152 Op.getOperand(0));
8153 }
8154 case ISD::VECREDUCE_FMIN: {
8155 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8156 return DAG.getNode(
8157 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8158 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8159 Op.getOperand(0));
8160 }
8161 default:
8162 llvm_unreachable("Unhandled reduction");
8163 }
8164}
8165
Oliver Stannard42699172018-02-12 14:22:03 +00008166SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8167 SelectionDAG &DAG) const {
8168 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8169 if (!Subtarget.hasLSE())
8170 return SDValue();
8171
8172 // LSE has an atomic load-add instruction, but not a load-sub.
8173 SDLoc dl(Op);
8174 MVT VT = Op.getSimpleValueType();
8175 SDValue RHS = Op.getOperand(2);
8176 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8177 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8178 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8179 Op.getOperand(0), Op.getOperand(1), RHS,
8180 AN->getMemOperand());
8181}
8182
Oliver Stannard02f08c92018-02-12 17:03:11 +00008183SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8184 SelectionDAG &DAG) const {
8185 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8186 if (!Subtarget.hasLSE())
8187 return SDValue();
8188
8189 // LSE has an atomic load-clear instruction, but not a load-and.
8190 SDLoc dl(Op);
8191 MVT VT = Op.getSimpleValueType();
8192 SDValue RHS = Op.getOperand(2);
8193 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8194 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8195 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8196 Op.getOperand(0), Op.getOperand(1), RHS,
8197 AN->getMemOperand());
8198}
8199
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008200SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8201 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8202 SDLoc dl(Op);
8203 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8204 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8205
Tri Vo6c47c622018-09-22 22:17:50 +00008206 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8207 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8208 if (Subtarget->hasCustomCallingConv())
8209 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008210
8211 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8212 DAG.getConstant(4, dl, MVT::i64));
8213 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8214 Chain =
8215 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8216 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8217 DAG.getRegisterMask(Mask), Chain.getValue(1));
8218 // To match the actual intent better, we should read the output from X15 here
8219 // again (instead of potentially spilling it to the stack), but rereading Size
8220 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8221 // here.
8222
8223 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8224 DAG.getConstant(4, dl, MVT::i64));
8225 return Chain;
8226}
8227
8228SDValue
8229AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8230 SelectionDAG &DAG) const {
8231 assert(Subtarget->isTargetWindows() &&
8232 "Only Windows alloca probing supported");
8233 SDLoc dl(Op);
8234 // Get the inputs.
8235 SDNode *Node = Op.getNode();
8236 SDValue Chain = Op.getOperand(0);
8237 SDValue Size = Op.getOperand(1);
8238 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8239 EVT VT = Node->getValueType(0);
8240
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00008241 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8242 "no-stack-arg-probe")) {
8243 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8244 Chain = SP.getValue(1);
8245 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8246 if (Align)
8247 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8248 DAG.getConstant(-(uint64_t)Align, dl, VT));
8249 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8250 SDValue Ops[2] = {SP, Chain};
8251 return DAG.getMergeValues(Ops, dl);
8252 }
8253
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008254 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8255
8256 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8257
8258 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8259 Chain = SP.getValue(1);
8260 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00008261 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008262 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8263 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00008264 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008265
8266 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8267 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8268
8269 SDValue Ops[2] = {SP, Chain};
8270 return DAG.getMergeValues(Ops, dl);
8271}
8272
Tim Northover3b0846e2014-05-24 12:50:23 +00008273/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8274/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8275/// specified in the intrinsic calls.
8276bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8277 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00008278 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00008279 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008280 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00008281 switch (Intrinsic) {
8282 case Intrinsic::aarch64_neon_ld2:
8283 case Intrinsic::aarch64_neon_ld3:
8284 case Intrinsic::aarch64_neon_ld4:
8285 case Intrinsic::aarch64_neon_ld1x2:
8286 case Intrinsic::aarch64_neon_ld1x3:
8287 case Intrinsic::aarch64_neon_ld1x4:
8288 case Intrinsic::aarch64_neon_ld2lane:
8289 case Intrinsic::aarch64_neon_ld3lane:
8290 case Intrinsic::aarch64_neon_ld4lane:
8291 case Intrinsic::aarch64_neon_ld2r:
8292 case Intrinsic::aarch64_neon_ld3r:
8293 case Intrinsic::aarch64_neon_ld4r: {
8294 Info.opc = ISD::INTRINSIC_W_CHAIN;
8295 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008296 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008297 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8298 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8299 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008300 Info.align.reset();
Matt Arsenault11171332017-12-14 21:39:51 +00008301 // volatile loads with NEON intrinsics not supported
8302 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008303 return true;
8304 }
8305 case Intrinsic::aarch64_neon_st2:
8306 case Intrinsic::aarch64_neon_st3:
8307 case Intrinsic::aarch64_neon_st4:
8308 case Intrinsic::aarch64_neon_st1x2:
8309 case Intrinsic::aarch64_neon_st1x3:
8310 case Intrinsic::aarch64_neon_st1x4:
8311 case Intrinsic::aarch64_neon_st2lane:
8312 case Intrinsic::aarch64_neon_st3lane:
8313 case Intrinsic::aarch64_neon_st4lane: {
8314 Info.opc = ISD::INTRINSIC_VOID;
8315 // Conservatively set memVT to the entire set of vectors stored.
8316 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008317 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008318 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8319 if (!ArgTy->isVectorTy())
8320 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008321 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008322 }
8323 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8324 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8325 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008326 Info.align.reset();
Matt Arsenault11171332017-12-14 21:39:51 +00008327 // volatile stores with NEON intrinsics not supported
8328 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008329 return true;
8330 }
8331 case Intrinsic::aarch64_ldaxr:
8332 case Intrinsic::aarch64_ldxr: {
8333 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8334 Info.opc = ISD::INTRINSIC_W_CHAIN;
8335 Info.memVT = MVT::getVT(PtrTy->getElementType());
8336 Info.ptrVal = I.getArgOperand(0);
8337 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008338 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
Matt Arsenault11171332017-12-14 21:39:51 +00008339 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008340 return true;
8341 }
8342 case Intrinsic::aarch64_stlxr:
8343 case Intrinsic::aarch64_stxr: {
8344 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8345 Info.opc = ISD::INTRINSIC_W_CHAIN;
8346 Info.memVT = MVT::getVT(PtrTy->getElementType());
8347 Info.ptrVal = I.getArgOperand(1);
8348 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008349 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
Matt Arsenault11171332017-12-14 21:39:51 +00008350 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008351 return true;
8352 }
8353 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008354 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008355 Info.opc = ISD::INTRINSIC_W_CHAIN;
8356 Info.memVT = MVT::i128;
8357 Info.ptrVal = I.getArgOperand(0);
8358 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008359 Info.align = Align(16);
Matt Arsenault11171332017-12-14 21:39:51 +00008360 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008361 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008362 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008363 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008364 Info.opc = ISD::INTRINSIC_W_CHAIN;
8365 Info.memVT = MVT::i128;
8366 Info.ptrVal = I.getArgOperand(2);
8367 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +00008368 Info.align = Align(16);
Matt Arsenault11171332017-12-14 21:39:51 +00008369 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008370 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008371 default:
8372 break;
8373 }
8374
8375 return false;
8376}
8377
John Brawne3b44f92018-03-23 14:47:07 +00008378bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8379 ISD::LoadExtType ExtTy,
8380 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008381 // TODO: This may be worth removing. Check regression tests for diffs.
8382 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8383 return false;
8384
John Brawne3b44f92018-03-23 14:47:07 +00008385 // If we're reducing the load width in order to avoid having to use an extra
8386 // instruction to do extension then it's probably a good idea.
8387 if (ExtTy != ISD::NON_EXTLOAD)
8388 return true;
8389 // Don't reduce load width if it would prevent us from combining a shift into
8390 // the offset.
8391 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8392 assert(Mem);
8393 const SDValue &Base = Mem->getBasePtr();
8394 if (Base.getOpcode() == ISD::ADD &&
8395 Base.getOperand(1).getOpcode() == ISD::SHL &&
8396 Base.getOperand(1).hasOneUse() &&
8397 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8398 // The shift can be combined if it matches the size of the value being
8399 // loaded (and so reducing the width would make it not match).
8400 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8401 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8402 if (ShiftAmount == Log2_32(LoadBytes))
8403 return false;
8404 }
8405 // We have no reason to disallow reducing the load width, so allow it.
8406 return true;
8407}
8408
Tim Northover3b0846e2014-05-24 12:50:23 +00008409// Truncations from 64-bit GPR to 32-bit GPR is free.
8410bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8411 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8412 return false;
8413 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8414 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008415 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008416}
8417bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008418 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008419 return false;
8420 unsigned NumBits1 = VT1.getSizeInBits();
8421 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008422 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008423}
8424
Chad Rosier54390052015-02-23 19:15:16 +00008425/// Check if it is profitable to hoist instruction in then/else to if.
8426/// Not profitable if I and it's user can form a FMA instruction
8427/// because we prefer FMSUB/FMADD.
8428bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8429 if (I->getOpcode() != Instruction::FMul)
8430 return true;
8431
Davide Italiano3e9986f2017-04-18 00:29:54 +00008432 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008433 return true;
8434
8435 Instruction *User = I->user_back();
8436
8437 if (User &&
8438 !(User->getOpcode() == Instruction::FSub ||
8439 User->getOpcode() == Instruction::FAdd))
8440 return true;
8441
8442 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008443 const DataLayout &DL = I->getModule()->getDataLayout();
8444 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008445
Eric Christopher114fa1c2016-02-29 22:50:49 +00008446 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8447 isOperationLegalOrCustom(ISD::FMA, VT) &&
8448 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8449 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008450}
8451
Tim Northover3b0846e2014-05-24 12:50:23 +00008452// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8453// 64-bit GPR.
8454bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8455 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8456 return false;
8457 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8458 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008459 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008460}
8461bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008462 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008463 return false;
8464 unsigned NumBits1 = VT1.getSizeInBits();
8465 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008466 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008467}
8468
8469bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8470 EVT VT1 = Val.getValueType();
8471 if (isZExtFree(VT1, VT2)) {
8472 return true;
8473 }
8474
8475 if (Val.getOpcode() != ISD::LOAD)
8476 return false;
8477
8478 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008479 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8480 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8481 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008482}
8483
Quentin Colombet6843ac42015-03-31 20:52:32 +00008484bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8485 if (isa<FPExtInst>(Ext))
8486 return false;
8487
Haicheng Wu50692a22017-08-01 21:26:45 +00008488 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008489 if (Ext->getType()->isVectorTy())
8490 return false;
8491
8492 for (const Use &U : Ext->uses()) {
8493 // The extension is free if we can fold it with a left shift in an
8494 // addressing mode or an arithmetic operation: add, sub, and cmp.
8495
8496 // Is there a shift?
8497 const Instruction *Instr = cast<Instruction>(U.getUser());
8498
8499 // Is this a constant shift?
8500 switch (Instr->getOpcode()) {
8501 case Instruction::Shl:
8502 if (!isa<ConstantInt>(Instr->getOperand(1)))
8503 return false;
8504 break;
8505 case Instruction::GetElementPtr: {
8506 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008507 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008508 std::advance(GTI, U.getOperandNo()-1);
8509 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008510 // This extension will end up with a shift because of the scaling factor.
8511 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8512 // Get the shift amount based on the scaling factor:
8513 // log2(sizeof(IdxTy)) - log2(8).
8514 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008515 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008516 // Is the constant foldable in the shift of the addressing mode?
8517 // I.e., shift amount is between 1 and 4 inclusive.
8518 if (ShiftAmt == 0 || ShiftAmt > 4)
8519 return false;
8520 break;
8521 }
8522 case Instruction::Trunc:
8523 // Check if this is a noop.
8524 // trunc(sext ty1 to ty2) to ty1.
8525 if (Instr->getType() == Ext->getOperand(0)->getType())
8526 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008527 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008528 default:
8529 return false;
8530 }
8531
8532 // At this point we can use the bfm family, so this extension is free
8533 // for that use.
8534 }
8535 return true;
8536}
8537
Florian Hahn3b251962019-02-05 10:27:40 +00008538/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8539/// or upper half of the vector elements.
8540static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8541 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8542 auto *FullVT = cast<VectorType>(FullV->getType());
8543 auto *HalfVT = cast<VectorType>(HalfV->getType());
8544 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8545 };
8546
8547 auto extractHalf = [](Value *FullV, Value *HalfV) {
8548 auto *FullVT = cast<VectorType>(FullV->getType());
8549 auto *HalfVT = cast<VectorType>(HalfV->getType());
8550 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8551 };
8552
8553 Constant *M1, *M2;
8554 Value *S1Op1, *S2Op1;
8555 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8556 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8557 return false;
8558
8559 // Check that the operands are half as wide as the result and we extract
8560 // half of the elements of the input vectors.
8561 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8562 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8563 return false;
8564
8565 // Check the mask extracts either the lower or upper half of vector
8566 // elements.
8567 int M1Start = -1;
8568 int M2Start = -1;
8569 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8570 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8571 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8572 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8573 return false;
8574
8575 return true;
8576}
8577
8578/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8579/// of the vector elements.
8580static bool areExtractExts(Value *Ext1, Value *Ext2) {
8581 auto areExtDoubled = [](Instruction *Ext) {
8582 return Ext->getType()->getScalarSizeInBits() ==
8583 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8584 };
8585
8586 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8587 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8588 !areExtDoubled(cast<Instruction>(Ext1)) ||
8589 !areExtDoubled(cast<Instruction>(Ext2)))
8590 return false;
8591
8592 return true;
8593}
8594
8595/// Check if sinking \p I's operands to I's basic block is profitable, because
8596/// the operands can be folded into a target instruction, e.g.
8597/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8598bool AArch64TargetLowering::shouldSinkOperands(
8599 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8600 if (!I->getType()->isVectorTy())
8601 return false;
8602
8603 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8604 switch (II->getIntrinsicID()) {
8605 case Intrinsic::aarch64_neon_umull:
8606 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8607 return false;
8608 Ops.push_back(&II->getOperandUse(0));
8609 Ops.push_back(&II->getOperandUse(1));
8610 return true;
8611 default:
8612 return false;
8613 }
8614 }
8615
8616 switch (I->getOpcode()) {
8617 case Instruction::Sub:
8618 case Instruction::Add: {
8619 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8620 return false;
8621
8622 // If the exts' operands extract either the lower or upper elements, we
8623 // can sink them too.
8624 auto Ext1 = cast<Instruction>(I->getOperand(0));
8625 auto Ext2 = cast<Instruction>(I->getOperand(1));
8626 if (areExtractShuffleVectors(Ext1, Ext2)) {
8627 Ops.push_back(&Ext1->getOperandUse(0));
8628 Ops.push_back(&Ext2->getOperandUse(0));
8629 }
8630
8631 Ops.push_back(&I->getOperandUse(0));
8632 Ops.push_back(&I->getOperandUse(1));
8633
8634 return true;
8635 }
8636 default:
8637 return false;
8638 }
8639 return false;
8640}
8641
Tim Northover3b0846e2014-05-24 12:50:23 +00008642bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8643 unsigned &RequiredAligment) const {
8644 if (!LoadedType.isSimple() ||
8645 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8646 return false;
8647 // Cyclone supports unaligned accesses.
8648 RequiredAligment = 0;
8649 unsigned NumBits = LoadedType.getSizeInBits();
8650 return NumBits == 32 || NumBits == 64;
8651}
8652
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008653/// A helper function for determining the number of interleaved accesses we
8654/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008655unsigned
8656AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8657 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008658 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8659}
8660
Geoff Berryb1e87142017-07-14 21:44:12 +00008661MachineMemOperand::Flags
8662AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8663 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8664 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8665 return MOStridedAccess;
8666 return MachineMemOperand::MONone;
8667}
8668
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008669bool AArch64TargetLowering::isLegalInterleavedAccessType(
8670 VectorType *VecTy, const DataLayout &DL) const {
8671
8672 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8673 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8674
8675 // Ensure the number of vector elements is greater than 1.
8676 if (VecTy->getNumElements() < 2)
8677 return false;
8678
8679 // Ensure the element type is legal.
8680 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8681 return false;
8682
8683 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8684 // 128 will be split into multiple interleaved accesses.
8685 return VecSize == 64 || VecSize % 128 == 0;
8686}
8687
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008688/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008689///
8690/// E.g. Lower an interleaved load (Factor = 2):
8691/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8692/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8693/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8694///
8695/// Into:
8696/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8697/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8698/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8699bool AArch64TargetLowering::lowerInterleavedLoad(
8700 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8701 ArrayRef<unsigned> Indices, unsigned Factor) const {
8702 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8703 "Invalid interleave factor");
8704 assert(!Shuffles.empty() && "Empty shufflevector input");
8705 assert(Shuffles.size() == Indices.size() &&
8706 "Unmatched number of shufflevectors and indices");
8707
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008708 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008709
8710 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008711
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008712 // Skip if we do not have NEON and skip illegal vector types. We can
8713 // "legalize" wide vector types into multiple interleaved accesses as long as
8714 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008715 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008716 return false;
8717
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008718 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8719
Hao Liu7ec8ee32015-06-26 02:32:07 +00008720 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8721 // load integer vectors first and then convert to pointer vectors.
8722 Type *EltTy = VecTy->getVectorElementType();
8723 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008724 VecTy =
8725 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008726
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008727 IRBuilder<> Builder(LI);
8728
8729 // The base address of the load.
8730 Value *BaseAddr = LI->getPointerOperand();
8731
8732 if (NumLoads > 1) {
8733 // If we're going to generate more than one load, reset the sub-vector type
8734 // to something legal.
8735 VecTy = VectorType::get(VecTy->getVectorElementType(),
8736 VecTy->getVectorNumElements() / NumLoads);
8737
8738 // We will compute the pointer operand of each load from the original base
8739 // address using GEPs. Cast the base address to a pointer to the scalar
8740 // element type.
8741 BaseAddr = Builder.CreateBitCast(
8742 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8743 LI->getPointerAddressSpace()));
8744 }
8745
Hao Liu7ec8ee32015-06-26 02:32:07 +00008746 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8747 Type *Tys[2] = {VecTy, PtrTy};
8748 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8749 Intrinsic::aarch64_neon_ld3,
8750 Intrinsic::aarch64_neon_ld4};
8751 Function *LdNFunc =
8752 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8753
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008754 // Holds sub-vectors extracted from the load intrinsic return values. The
8755 // sub-vectors are associated with the shufflevector instructions they will
8756 // replace.
8757 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008758
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008759 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008760
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008761 // If we're generating more than one load, compute the base address of
8762 // subsequent loads as an offset from the previous.
8763 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008764 BaseAddr =
8765 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8766 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008767
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008768 CallInst *LdN = Builder.CreateCall(
8769 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008770
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008771 // Extract and store the sub-vectors returned by the load intrinsic.
8772 for (unsigned i = 0; i < Shuffles.size(); i++) {
8773 ShuffleVectorInst *SVI = Shuffles[i];
8774 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008775
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008776 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8777
8778 // Convert the integer vector to pointer vector if the element is pointer.
8779 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008780 SubVec = Builder.CreateIntToPtr(
8781 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8782 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008783 SubVecs[SVI].push_back(SubVec);
8784 }
8785 }
8786
8787 // Replace uses of the shufflevector instructions with the sub-vectors
8788 // returned by the load intrinsic. If a shufflevector instruction is
8789 // associated with more than one sub-vector, those sub-vectors will be
8790 // concatenated into a single wide vector.
8791 for (ShuffleVectorInst *SVI : Shuffles) {
8792 auto &SubVec = SubVecs[SVI];
8793 auto *WideVec =
8794 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8795 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008796 }
8797
8798 return true;
8799}
8800
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008801/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008802///
8803/// E.g. Lower an interleaved store (Factor = 3):
8804/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008805/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008806/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8807///
8808/// Into:
8809/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8810/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8811/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8812/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8813///
8814/// Note that the new shufflevectors will be removed and we'll only generate one
8815/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008816///
8817/// Example for a more general valid mask (Factor 3). Lower:
8818/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8819/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8820/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8821///
8822/// Into:
8823/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8824/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8825/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8826/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008827bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8828 ShuffleVectorInst *SVI,
8829 unsigned Factor) const {
8830 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8831 "Invalid interleave factor");
8832
8833 VectorType *VecTy = SVI->getType();
8834 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8835 "Invalid interleaved store");
8836
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008837 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008838 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008839 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008840
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008841 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008842
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008843 // Skip if we do not have NEON and skip illegal vector types. We can
8844 // "legalize" wide vector types into multiple interleaved accesses as long as
8845 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008846 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008847 return false;
8848
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008849 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8850
Hao Liu7ec8ee32015-06-26 02:32:07 +00008851 Value *Op0 = SVI->getOperand(0);
8852 Value *Op1 = SVI->getOperand(1);
8853 IRBuilder<> Builder(SI);
8854
8855 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8856 // vectors to integer vectors.
8857 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008858 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008859 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008860
8861 // Convert to the corresponding integer vector.
8862 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8863 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8864 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8865
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008866 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008867 }
8868
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008869 // The base address of the store.
8870 Value *BaseAddr = SI->getPointerOperand();
8871
8872 if (NumStores > 1) {
8873 // If we're going to generate more than one store, reset the lane length
8874 // and sub-vector type to something legal.
8875 LaneLen /= NumStores;
8876 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8877
8878 // We will compute the pointer operand of each store from the original base
8879 // address using GEPs. Cast the base address to a pointer to the scalar
8880 // element type.
8881 BaseAddr = Builder.CreateBitCast(
8882 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8883 SI->getPointerAddressSpace()));
8884 }
8885
8886 auto Mask = SVI->getShuffleMask();
8887
Hao Liu7ec8ee32015-06-26 02:32:07 +00008888 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8889 Type *Tys[2] = {SubVecTy, PtrTy};
8890 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8891 Intrinsic::aarch64_neon_st3,
8892 Intrinsic::aarch64_neon_st4};
8893 Function *StNFunc =
8894 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8895
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008896 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008897
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008898 SmallVector<Value *, 5> Ops;
8899
8900 // Split the shufflevector operands into sub vectors for the new stN call.
8901 for (unsigned i = 0; i < Factor; i++) {
8902 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8903 if (Mask[IdxI] >= 0) {
8904 Ops.push_back(Builder.CreateShuffleVector(
8905 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8906 } else {
8907 unsigned StartMask = 0;
8908 for (unsigned j = 1; j < LaneLen; j++) {
8909 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8910 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8911 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8912 break;
8913 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008914 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008915 // Note: Filling undef gaps with random elements is ok, since
8916 // those elements were being written anyway (with undefs).
8917 // In the case of all undefs we're defaulting to using elems from 0
8918 // Note: StartMask cannot be negative, it's checked in
8919 // isReInterleaveMask
8920 Ops.push_back(Builder.CreateShuffleVector(
8921 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008922 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008923 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008924
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008925 // If we generating more than one store, we compute the base address of
8926 // subsequent stores as an offset from the previous.
8927 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008928 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8929 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008930
8931 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8932 Builder.CreateCall(StNFunc, Ops);
8933 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008934 return true;
8935}
8936
Tim Northover3b0846e2014-05-24 12:50:23 +00008937static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8938 unsigned AlignCheck) {
8939 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8940 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8941}
8942
Sjoerd Meijer180f1ae2019-04-30 08:38:12 +00008943EVT AArch64TargetLowering::getOptimalMemOpType(
8944 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8945 bool ZeroMemset, bool MemcpyStrSrc,
8946 const AttributeList &FuncAttributes) const {
8947 bool CanImplicitFloat =
8948 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
JF Bastien29200612018-09-06 16:03:32 +00008949 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8950 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8951 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8952 // taken one instruction to materialize the v2i64 zero and one store (with
8953 // restrictive addressing mode). Just do i64 stores.
8954 bool IsSmallMemset = IsMemset && Size < 32;
8955 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8956 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8957 return true;
8958 bool Fast;
Simon Pilgrim4e0648a2019-06-12 17:14:03 +00008959 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8960 &Fast) &&
8961 Fast;
JF Bastien29200612018-09-06 16:03:32 +00008962 };
8963
8964 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8965 AlignmentIsAcceptable(MVT::v2i64, 16))
8966 return MVT::v2i64;
8967 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008968 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008969 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008970 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008971 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008972 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008973 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008974}
8975
Amara Emerson13af1ed2019-07-24 22:17:31 +00008976LLT AArch64TargetLowering::getOptimalMemOpLLT(
8977 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8978 bool ZeroMemset, bool MemcpyStrSrc,
8979 const AttributeList &FuncAttributes) const {
8980 bool CanImplicitFloat =
8981 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8982 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8983 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8984 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8985 // taken one instruction to materialize the v2i64 zero and one store (with
8986 // restrictive addressing mode). Just do i64 stores.
8987 bool IsSmallMemset = IsMemset && Size < 32;
8988 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8989 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8990 return true;
8991 bool Fast;
8992 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8993 &Fast) &&
8994 Fast;
8995 };
8996
8997 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8998 AlignmentIsAcceptable(MVT::v2i64, 16))
8999 return LLT::vector(2, 64);
9000 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9001 return LLT::scalar(128);
9002 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9003 return LLT::scalar(64);
9004 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9005 return LLT::scalar(32);
9006 return LLT();
9007}
9008
Tim Northover3b0846e2014-05-24 12:50:23 +00009009// 12-bit optionally shifted immediates are legal for adds.
9010bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00009011 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009012 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9013 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00009014 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00009015 }
Geoff Berry486f49c2016-06-07 16:48:43 +00009016 // Same encoding for add/sub, just flip the sign.
9017 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00009018 bool IsLegal = ((Immed >> 12) == 0 ||
9019 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009020 LLVM_DEBUG(dbgs() << "Is " << Immed
9021 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00009022 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00009023}
9024
9025// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9026// immediates is the same as for an add or a sub.
9027bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00009028 return isLegalAddImmediate(Immed);
9029}
9030
9031/// isLegalAddressingMode - Return true if the addressing mode represented
9032/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00009033bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9034 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00009035 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00009036 // AArch64 has five basic addressing modes:
9037 // reg
9038 // reg + 9-bit signed offset
9039 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
9040 // reg1 + reg2
9041 // reg + SIZE_IN_BYTES * reg
9042
9043 // No global is ever allowed as a base.
9044 if (AM.BaseGV)
9045 return false;
9046
9047 // No reg+reg+imm addressing.
9048 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9049 return false;
9050
9051 // check reg + imm case:
9052 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9053 uint64_t NumBytes = 0;
9054 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00009055 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00009056 NumBytes = NumBits / 8;
9057 if (!isPowerOf2_64(NumBits))
9058 NumBytes = 0;
9059 }
9060
9061 if (!AM.Scale) {
9062 int64_t Offset = AM.BaseOffs;
9063
9064 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00009065 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00009066 return true;
9067
9068 // 12-bit unsigned offset
9069 unsigned shift = Log2_64(NumBytes);
9070 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9071 // Must be a multiple of NumBytes (NumBytes is a power of 2)
9072 (Offset >> shift) << shift == Offset)
9073 return true;
9074 return false;
9075 }
9076
9077 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9078
Haicheng Wu6bb0e392016-12-21 21:40:47 +00009079 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00009080}
9081
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00009082bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9083 // Consider splitting large offset of struct or array.
9084 return true;
9085}
9086
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00009087int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9088 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00009089 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00009090 // Scaling factors are not free at all.
9091 // Operands | Rt Latency
9092 // -------------------------------------------
9093 // Rt, [Xn, Xm] | 4
9094 // -------------------------------------------
9095 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
9096 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00009097 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009098 // Scale represents reg2 * scale, thus account for 1 if
9099 // it is not equal to 0 or 1.
9100 return AM.Scale != 0 && AM.Scale != 1;
9101 return -1;
9102}
9103
9104bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9105 VT = VT.getScalarType();
9106
9107 if (!VT.isSimple())
9108 return false;
9109
9110 switch (VT.getSimpleVT().SimpleTy) {
9111 case MVT::f32:
9112 case MVT::f64:
9113 return true;
9114 default:
9115 break;
9116 }
9117
9118 return false;
9119}
9120
9121const MCPhysReg *
9122AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9123 // LR is a callee-save register, but we must treat it as clobbered by any call
9124 // site. Hence we include LR in the scratch registers, which are in turn added
9125 // as implicit-defs for stackmaps and patchpoints.
9126 static const MCPhysReg ScratchRegs[] = {
9127 AArch64::X16, AArch64::X17, AArch64::LR, 0
9128 };
9129 return ScratchRegs;
9130}
9131
9132bool
Eli Friedman0d12e902018-08-14 22:10:25 +00009133AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9134 CombineLevel Level) const {
9135 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009136 EVT VT = N->getValueType(0);
9137 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9138 // it with shift to let it be lowered to UBFX.
9139 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9140 isa<ConstantSDNode>(N->getOperand(1))) {
9141 uint64_t TruncMask = N->getConstantOperandVal(1);
9142 if (isMask_64(TruncMask) &&
9143 N->getOperand(0).getOpcode() == ISD::SRL &&
9144 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9145 return false;
9146 }
9147 return true;
9148}
9149
9150bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9151 Type *Ty) const {
9152 assert(Ty->isIntegerTy());
9153
9154 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9155 if (BitSize == 0)
9156 return false;
9157
9158 int64_t Val = Imm.getSExtValue();
9159 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9160 return true;
9161
9162 if ((int64_t)Val < 0)
9163 Val = ~Val;
9164 if (BitSize == 32)
9165 Val &= (1LL << 32) - 1;
9166
9167 unsigned LZ = countLeadingZeros((uint64_t)Val);
9168 unsigned Shift = (63 - LZ) / 16;
9169 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00009170 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00009171}
9172
Sebastian Pop41073e82018-03-06 16:54:55 +00009173bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9174 unsigned Index) const {
9175 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9176 return false;
9177
9178 return (Index == 0 || Index == ResVT.getVectorNumElements());
9179}
9180
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00009181/// Turn vector tests of the signbit in the form of:
9182/// xor (sra X, elt_size(X)-1), -1
9183/// into:
9184/// cmge X, X, #0
9185static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9186 const AArch64Subtarget *Subtarget) {
9187 EVT VT = N->getValueType(0);
9188 if (!Subtarget->hasNEON() || !VT.isVector())
9189 return SDValue();
9190
9191 // There must be a shift right algebraic before the xor, and the xor must be a
9192 // 'not' operation.
9193 SDValue Shift = N->getOperand(0);
9194 SDValue Ones = N->getOperand(1);
9195 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9196 !ISD::isBuildVectorAllOnes(Ones.getNode()))
9197 return SDValue();
9198
9199 // The shift should be smearing the sign bit across each vector element.
9200 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9201 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9202 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9203 return SDValue();
9204
9205 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9206}
9207
Tim Northover3b0846e2014-05-24 12:50:23 +00009208// Generate SUBS and CSEL for integer abs.
9209static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9210 EVT VT = N->getValueType(0);
9211
9212 SDValue N0 = N->getOperand(0);
9213 SDValue N1 = N->getOperand(1);
9214 SDLoc DL(N);
9215
9216 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9217 // and change it to SUB and CSEL.
9218 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9219 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9220 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9221 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9222 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009223 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00009224 N0.getOperand(0));
9225 // Generate SUBS & CSEL.
9226 SDValue Cmp =
9227 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009228 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009229 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009230 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00009231 SDValue(Cmp.getNode(), 1));
9232 }
9233 return SDValue();
9234}
9235
Tim Northover3b0846e2014-05-24 12:50:23 +00009236static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9237 TargetLowering::DAGCombinerInfo &DCI,
9238 const AArch64Subtarget *Subtarget) {
9239 if (DCI.isBeforeLegalizeOps())
9240 return SDValue();
9241
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00009242 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9243 return Cmp;
9244
Tim Northover3b0846e2014-05-24 12:50:23 +00009245 return performIntegerAbsCombine(N, DAG);
9246}
9247
Chad Rosier17020f92014-07-23 14:57:52 +00009248SDValue
9249AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9250 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00009251 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00009252 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00009253 if (isIntDivCheap(N->getValueType(0), Attr))
9254 return SDValue(N,0); // Lower SDIV as SDIV
9255
Chad Rosier17020f92014-07-23 14:57:52 +00009256 // fold (sdiv X, pow2)
9257 EVT VT = N->getValueType(0);
9258 if ((VT != MVT::i32 && VT != MVT::i64) ||
9259 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9260 return SDValue();
9261
9262 SDLoc DL(N);
9263 SDValue N0 = N->getOperand(0);
9264 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009265 SDValue Zero = DAG.getConstant(0, DL, VT);
9266 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00009267
9268 // Add (N0 < 0) ? Pow2 - 1 : 0;
9269 SDValue CCVal;
9270 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9271 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9272 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9273
Craig Toppera568a272018-07-30 21:04:34 +00009274 Created.push_back(Cmp.getNode());
9275 Created.push_back(Add.getNode());
9276 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00009277
9278 // Divide by pow2.
9279 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009280 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00009281
9282 // If we're dividing by a positive value, we're done. Otherwise, we must
9283 // negate the result.
9284 if (Divisor.isNonNegative())
9285 return SRA;
9286
Craig Toppera568a272018-07-30 21:04:34 +00009287 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009288 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00009289}
9290
Tim Northover3b0846e2014-05-24 12:50:23 +00009291static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9292 TargetLowering::DAGCombinerInfo &DCI,
9293 const AArch64Subtarget *Subtarget) {
9294 if (DCI.isBeforeLegalizeOps())
9295 return SDValue();
9296
Chad Rosier31ee8132016-11-11 17:07:37 +00009297 // The below optimizations require a constant RHS.
9298 if (!isa<ConstantSDNode>(N->getOperand(1)))
9299 return SDValue();
9300
9301 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9302 const APInt &ConstValue = C->getAPIntValue();
9303
Tim Northover3b0846e2014-05-24 12:50:23 +00009304 // Multiplication of a power of two plus/minus one can be done more
9305 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9306 // future CPUs have a cheaper MADD instruction, this may need to be
9307 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9308 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009309 // More aggressively, some multiplications N0 * C can be lowered to
9310 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9311 // e.g. 6=3*2=(2+1)*2.
9312 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9313 // which equals to (1+2)*16-(1+2).
9314 SDValue N0 = N->getOperand(0);
9315 // TrailingZeroes is used to test if the mul can be lowered to
9316 // shift+add+shift.
9317 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9318 if (TrailingZeroes) {
9319 // Conservatively do not lower to shift+add+shift if the mul might be
9320 // folded into smul or umul.
9321 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9322 isZeroExtended(N0.getNode(), DAG)))
9323 return SDValue();
9324 // Conservatively do not lower to shift+add+shift if the mul might be
9325 // folded into madd or msub.
9326 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9327 N->use_begin()->getOpcode() == ISD::SUB))
9328 return SDValue();
9329 }
9330 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9331 // and shift+add+shift.
9332 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9333
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009334 unsigned ShiftAmt, AddSubOpc;
9335 // Is the shifted value the LHS operand of the add/sub?
9336 bool ShiftValUseIsN0 = true;
9337 // Do we need to negate the result?
9338 bool NegateResult = false;
9339
Chad Rosier31ee8132016-11-11 17:07:37 +00009340 if (ConstValue.isNonNegative()) {
9341 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00009342 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00009343 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9344 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009345 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00009346 if (SCVMinus1.isPowerOf2()) {
9347 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009348 AddSubOpc = ISD::ADD;
9349 } else if (CVPlus1.isPowerOf2()) {
9350 ShiftAmt = CVPlus1.logBase2();
9351 AddSubOpc = ISD::SUB;
9352 } else
9353 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00009354 } else {
9355 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00009356 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009357 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009358 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009359 if (CVNegPlus1.isPowerOf2()) {
9360 ShiftAmt = CVNegPlus1.logBase2();
9361 AddSubOpc = ISD::SUB;
9362 ShiftValUseIsN0 = false;
9363 } else if (CVNegMinus1.isPowerOf2()) {
9364 ShiftAmt = CVNegMinus1.logBase2();
9365 AddSubOpc = ISD::ADD;
9366 NegateResult = true;
9367 } else
9368 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009369 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009370
9371 SDLoc DL(N);
9372 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009373 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009374 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9375
9376 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9377 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9378 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009379 assert(!(NegateResult && TrailingZeroes) &&
9380 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009381 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009382 if (NegateResult)
9383 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9384 // Shift the result.
9385 if (TrailingZeroes)
9386 return DAG.getNode(ISD::SHL, DL, VT, Res,
9387 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9388 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00009389}
9390
Jim Grosbachf7502c42014-07-18 00:40:52 +00009391static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9392 SelectionDAG &DAG) {
9393 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9394 // optimize away operation when it's from a constant.
9395 //
9396 // The general transformation is:
9397 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9398 // AND(VECTOR_CMP(x,y), constant2)
9399 // constant2 = UNARYOP(constant)
9400
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009401 // Early exit if this isn't a vector operation, the operand of the
9402 // unary operation isn't a bitwise AND, or if the sizes of the operations
9403 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009404 EVT VT = N->getValueType(0);
9405 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009406 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9407 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009408 return SDValue();
9409
Jim Grosbach724e4382014-07-23 20:41:43 +00009410 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009411 // make the transformation for non-constant splats as well, but it's unclear
9412 // that would be a benefit as it would not eliminate any operations, just
9413 // perform one more step in scalar code before moving to the vector unit.
9414 if (BuildVectorSDNode *BV =
9415 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009416 // Bail out if the vector isn't a constant.
9417 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009418 return SDValue();
9419
9420 // Everything checks out. Build up the new and improved node.
9421 SDLoc DL(N);
9422 EVT IntVT = BV->getValueType(0);
9423 // Create a new constant of the appropriate type for the transformed
9424 // DAG.
9425 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9426 // The AND node needs bitcasts to/from an integer vector type around it.
9427 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9428 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9429 N->getOperand(0)->getOperand(0), MaskConst);
9430 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9431 return Res;
9432 }
9433
9434 return SDValue();
9435}
9436
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009437static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9438 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009439 // First try to optimize away the conversion when it's conditionally from
9440 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009441 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009442 return Res;
9443
Tim Northover3b0846e2014-05-24 12:50:23 +00009444 EVT VT = N->getValueType(0);
9445 if (VT != MVT::f32 && VT != MVT::f64)
9446 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009447
Tim Northover3b0846e2014-05-24 12:50:23 +00009448 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009449 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009450 return SDValue();
9451
9452 // If the result of an integer load is only used by an integer-to-float
9453 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009454 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009455 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009456 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009457 // Do not change the width of a volatile load.
9458 !cast<LoadSDNode>(N0)->isVolatile()) {
9459 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9460 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009461 LN0->getPointerInfo(), LN0->getAlignment(),
9462 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009463
9464 // Make sure successors of the original load stay after it by updating them
9465 // to use the new Chain.
9466 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9467
9468 unsigned Opcode =
9469 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9470 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9471 }
9472
9473 return SDValue();
9474}
9475
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009476/// Fold a floating-point multiply by power of two into floating-point to
9477/// fixed-point conversion.
9478static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009479 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009480 const AArch64Subtarget *Subtarget) {
9481 if (!Subtarget->hasNEON())
9482 return SDValue();
9483
Sam Parkera0bd6f82019-06-03 08:49:17 +00009484 if (!N->getValueType(0).isSimple())
9485 return SDValue();
9486
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009487 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009488 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9489 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009490 return SDValue();
9491
9492 SDValue ConstVec = Op->getOperand(1);
9493 if (!isa<BuildVectorSDNode>(ConstVec))
9494 return SDValue();
9495
9496 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9497 uint32_t FloatBits = FloatTy.getSizeInBits();
9498 if (FloatBits != 32 && FloatBits != 64)
9499 return SDValue();
9500
9501 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9502 uint32_t IntBits = IntTy.getSizeInBits();
9503 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9504 return SDValue();
9505
9506 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9507 if (IntBits > FloatBits)
9508 return SDValue();
9509
9510 BitVector UndefElements;
9511 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9512 int32_t Bits = IntBits == 64 ? 64 : 32;
9513 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9514 if (C == -1 || C == 0 || C > Bits)
9515 return SDValue();
9516
9517 MVT ResTy;
9518 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9519 switch (NumLanes) {
9520 default:
9521 return SDValue();
9522 case 2:
9523 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9524 break;
9525 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009526 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009527 break;
9528 }
9529
Silviu Barangafa00ba32016-08-08 13:13:57 +00009530 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9531 return SDValue();
9532
9533 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9534 "Illegal vector type after legalization");
9535
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009536 SDLoc DL(N);
9537 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9538 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9539 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9540 SDValue FixConv =
9541 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9542 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9543 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9544 // We can handle smaller integers by generating an extra trunc.
9545 if (IntBits < FloatBits)
9546 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9547
9548 return FixConv;
9549}
9550
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009551/// Fold a floating-point divide by power of two into fixed-point to
9552/// floating-point conversion.
9553static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009554 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009555 const AArch64Subtarget *Subtarget) {
9556 if (!Subtarget->hasNEON())
9557 return SDValue();
9558
9559 SDValue Op = N->getOperand(0);
9560 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009561 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9562 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009563 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9564 return SDValue();
9565
9566 SDValue ConstVec = N->getOperand(1);
9567 if (!isa<BuildVectorSDNode>(ConstVec))
9568 return SDValue();
9569
9570 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9571 int32_t IntBits = IntTy.getSizeInBits();
9572 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9573 return SDValue();
9574
9575 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9576 int32_t FloatBits = FloatTy.getSizeInBits();
9577 if (FloatBits != 32 && FloatBits != 64)
9578 return SDValue();
9579
9580 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9581 if (IntBits > FloatBits)
9582 return SDValue();
9583
9584 BitVector UndefElements;
9585 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9586 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9587 if (C == -1 || C == 0 || C > FloatBits)
9588 return SDValue();
9589
9590 MVT ResTy;
9591 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9592 switch (NumLanes) {
9593 default:
9594 return SDValue();
9595 case 2:
9596 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9597 break;
9598 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009599 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009600 break;
9601 }
9602
Tim Northover85cf5642016-08-26 18:52:31 +00009603 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9604 return SDValue();
9605
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009606 SDLoc DL(N);
9607 SDValue ConvInput = Op.getOperand(0);
9608 bool IsSigned = Opc == ISD::SINT_TO_FP;
9609 if (IntBits < FloatBits)
9610 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9611 ResTy, ConvInput);
9612
9613 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9614 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9615 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9616 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9617 DAG.getConstant(C, DL, MVT::i32));
9618}
9619
Tim Northover3b0846e2014-05-24 12:50:23 +00009620/// An EXTR instruction is made up of two shifts, ORed together. This helper
9621/// searches for and classifies those shifts.
9622static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9623 bool &FromHi) {
9624 if (N.getOpcode() == ISD::SHL)
9625 FromHi = false;
9626 else if (N.getOpcode() == ISD::SRL)
9627 FromHi = true;
9628 else
9629 return false;
9630
9631 if (!isa<ConstantSDNode>(N.getOperand(1)))
9632 return false;
9633
9634 ShiftAmount = N->getConstantOperandVal(1);
9635 Src = N->getOperand(0);
9636 return true;
9637}
9638
9639/// EXTR instruction extracts a contiguous chunk of bits from two existing
9640/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009641/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9642/// with an EXTR. Can't quite be done in TableGen because the two immediates
9643/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009644static SDValue tryCombineToEXTR(SDNode *N,
9645 TargetLowering::DAGCombinerInfo &DCI) {
9646 SelectionDAG &DAG = DCI.DAG;
9647 SDLoc DL(N);
9648 EVT VT = N->getValueType(0);
9649
9650 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9651
9652 if (VT != MVT::i32 && VT != MVT::i64)
9653 return SDValue();
9654
9655 SDValue LHS;
9656 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009657 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009658 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9659 return SDValue();
9660
9661 SDValue RHS;
9662 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009663 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009664 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9665 return SDValue();
9666
9667 // If they're both trying to come from the high part of the register, they're
9668 // not really an EXTR.
9669 if (LHSFromHi == RHSFromHi)
9670 return SDValue();
9671
9672 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9673 return SDValue();
9674
9675 if (LHSFromHi) {
9676 std::swap(LHS, RHS);
9677 std::swap(ShiftLHS, ShiftRHS);
9678 }
9679
9680 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009681 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009682}
9683
9684static SDValue tryCombineToBSL(SDNode *N,
9685 TargetLowering::DAGCombinerInfo &DCI) {
9686 EVT VT = N->getValueType(0);
9687 SelectionDAG &DAG = DCI.DAG;
9688 SDLoc DL(N);
9689
9690 if (!VT.isVector())
9691 return SDValue();
9692
9693 SDValue N0 = N->getOperand(0);
9694 if (N0.getOpcode() != ISD::AND)
9695 return SDValue();
9696
9697 SDValue N1 = N->getOperand(1);
9698 if (N1.getOpcode() != ISD::AND)
9699 return SDValue();
9700
9701 // We only have to look for constant vectors here since the general, variable
9702 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009703 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009704 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9705 for (int i = 1; i >= 0; --i)
9706 for (int j = 1; j >= 0; --j) {
9707 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9708 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9709 if (!BVN0 || !BVN1)
9710 continue;
9711
9712 bool FoundMatch = true;
9713 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9714 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9715 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9716 if (!CN0 || !CN1 ||
9717 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9718 FoundMatch = false;
9719 break;
9720 }
9721 }
9722
9723 if (FoundMatch)
9724 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9725 N0->getOperand(1 - i), N1->getOperand(1 - j));
9726 }
9727
9728 return SDValue();
9729}
9730
9731static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9732 const AArch64Subtarget *Subtarget) {
9733 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009734 SelectionDAG &DAG = DCI.DAG;
9735 EVT VT = N->getValueType(0);
9736
9737 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9738 return SDValue();
9739
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009740 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009741 return Res;
9742
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009743 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009744 return Res;
9745
9746 return SDValue();
9747}
9748
Nikita Popov1a261442019-03-15 21:04:34 +00009749static SDValue performANDCombine(SDNode *N,
9750 TargetLowering::DAGCombinerInfo &DCI) {
9751 SelectionDAG &DAG = DCI.DAG;
9752 SDValue LHS = N->getOperand(0);
9753 EVT VT = N->getValueType(0);
9754 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9755 return SDValue();
9756
9757 BuildVectorSDNode *BVN =
9758 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9759 if (!BVN)
9760 return SDValue();
9761
9762 // AND does not accept an immediate, so check if we can use a BIC immediate
9763 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9764 // pattern in isel, because some immediates may be lowered to the preferred
9765 // (and x, (movi imm)) form, even though an mvni representation also exists.
9766 APInt DefBits(VT.getSizeInBits(), 0);
9767 APInt UndefBits(VT.getSizeInBits(), 0);
9768 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9769 SDValue NewOp;
9770
9771 DefBits = ~DefBits;
9772 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9773 DefBits, &LHS)) ||
9774 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9775 DefBits, &LHS)))
9776 return NewOp;
9777
9778 UndefBits = ~UndefBits;
9779 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9780 UndefBits, &LHS)) ||
9781 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9782 UndefBits, &LHS)))
9783 return NewOp;
9784 }
9785
9786 return SDValue();
9787}
9788
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009789static SDValue performSRLCombine(SDNode *N,
9790 TargetLowering::DAGCombinerInfo &DCI) {
9791 SelectionDAG &DAG = DCI.DAG;
9792 EVT VT = N->getValueType(0);
9793 if (VT != MVT::i32 && VT != MVT::i64)
9794 return SDValue();
9795
9796 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9797 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9798 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9799 SDValue N0 = N->getOperand(0);
9800 if (N0.getOpcode() == ISD::BSWAP) {
9801 SDLoc DL(N);
9802 SDValue N1 = N->getOperand(1);
9803 SDValue N00 = N0.getOperand(0);
9804 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9805 uint64_t ShiftAmt = C->getZExtValue();
9806 if (VT == MVT::i32 && ShiftAmt == 16 &&
9807 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9808 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9809 if (VT == MVT::i64 && ShiftAmt == 32 &&
9810 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9811 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9812 }
9813 }
9814 return SDValue();
9815}
9816
Tim Northover3b0846e2014-05-24 12:50:23 +00009817static SDValue performBitcastCombine(SDNode *N,
9818 TargetLowering::DAGCombinerInfo &DCI,
9819 SelectionDAG &DAG) {
9820 // Wait 'til after everything is legalized to try this. That way we have
9821 // legal vector types and such.
9822 if (DCI.isBeforeLegalizeOps())
9823 return SDValue();
9824
9825 // Remove extraneous bitcasts around an extract_subvector.
9826 // For example,
9827 // (v4i16 (bitconvert
9828 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9829 // becomes
9830 // (extract_subvector ((v8i16 ...), (i64 4)))
9831
9832 // Only interested in 64-bit vectors as the ultimate result.
9833 EVT VT = N->getValueType(0);
9834 if (!VT.isVector())
9835 return SDValue();
9836 if (VT.getSimpleVT().getSizeInBits() != 64)
9837 return SDValue();
9838 // Is the operand an extract_subvector starting at the beginning or halfway
9839 // point of the vector? A low half may also come through as an
9840 // EXTRACT_SUBREG, so look for that, too.
9841 SDValue Op0 = N->getOperand(0);
9842 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9843 !(Op0->isMachineOpcode() &&
9844 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9845 return SDValue();
9846 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9847 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9848 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9849 return SDValue();
9850 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9851 if (idx != AArch64::dsub)
9852 return SDValue();
9853 // The dsub reference is equivalent to a lane zero subvector reference.
9854 idx = 0;
9855 }
9856 // Look through the bitcast of the input to the extract.
9857 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9858 return SDValue();
9859 SDValue Source = Op0->getOperand(0)->getOperand(0);
9860 // If the source type has twice the number of elements as our destination
9861 // type, we know this is an extract of the high or low half of the vector.
9862 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009863 if (!SVT.isVector() ||
9864 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009865 return SDValue();
9866
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009867 LLVM_DEBUG(
9868 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009869
9870 // Create the simplified form to just extract the low or high half of the
9871 // vector directly rather than bothering with the bitcasts.
9872 SDLoc dl(N);
9873 unsigned NumElements = VT.getVectorNumElements();
9874 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009875 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009876 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9877 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009878 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009879 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9880 Source, SubReg),
9881 0);
9882 }
9883}
9884
9885static SDValue performConcatVectorsCombine(SDNode *N,
9886 TargetLowering::DAGCombinerInfo &DCI,
9887 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009888 SDLoc dl(N);
9889 EVT VT = N->getValueType(0);
9890 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9891
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009892 // Optimize concat_vectors of truncated vectors, where the intermediate
9893 // type is illegal, to avoid said illegality, e.g.,
9894 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9895 // (v2i16 (truncate (v2i64)))))
9896 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009897 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9898 // (v4i32 (bitcast (v2i64))),
9899 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009900 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9901 // on both input and result type, so we might generate worse code.
9902 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9903 if (N->getNumOperands() == 2 &&
9904 N0->getOpcode() == ISD::TRUNCATE &&
9905 N1->getOpcode() == ISD::TRUNCATE) {
9906 SDValue N00 = N0->getOperand(0);
9907 SDValue N10 = N1->getOperand(0);
9908 EVT N00VT = N00.getValueType();
9909
9910 if (N00VT == N10.getValueType() &&
9911 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9912 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009913 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9914 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9915 for (size_t i = 0; i < Mask.size(); ++i)
9916 Mask[i] = i * 2;
9917 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9918 DAG.getVectorShuffle(
9919 MidVT, dl,
9920 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9921 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009922 }
9923 }
9924
Tim Northover3b0846e2014-05-24 12:50:23 +00009925 // Wait 'til after everything is legalized to try this. That way we have
9926 // legal vector types and such.
9927 if (DCI.isBeforeLegalizeOps())
9928 return SDValue();
9929
Tim Northover3b0846e2014-05-24 12:50:23 +00009930 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9931 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9932 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009933 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009934 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009935 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009936 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009937 }
9938
9939 // Canonicalise concat_vectors so that the right-hand vector has as few
9940 // bit-casts as possible before its real operation. The primary matching
9941 // destination for these operations will be the narrowing "2" instructions,
9942 // which depend on the operation being performed on this right-hand vector.
9943 // For example,
9944 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9945 // becomes
9946 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9947
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009948 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009949 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009950 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009951 MVT RHSTy = RHS.getValueType().getSimpleVT();
9952 // If the RHS is not a vector, this is not the pattern we're looking for.
9953 if (!RHSTy.isVector())
9954 return SDValue();
9955
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009956 LLVM_DEBUG(
9957 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009958
9959 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9960 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009961 return DAG.getNode(ISD::BITCAST, dl, VT,
9962 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9963 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9964 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009965}
9966
9967static SDValue tryCombineFixedPointConvert(SDNode *N,
9968 TargetLowering::DAGCombinerInfo &DCI,
9969 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009970 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009971 // legal vector types and such.
9972 if (DCI.isBeforeLegalizeOps())
9973 return SDValue();
9974 // Transform a scalar conversion of a value from a lane extract into a
9975 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9976 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9977 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9978 //
9979 // The second form interacts better with instruction selection and the
9980 // register allocator to avoid cross-class register copies that aren't
9981 // coalescable due to a lane reference.
9982
9983 // Check the operand and see if it originates from a lane extract.
9984 SDValue Op1 = N->getOperand(1);
9985 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9986 // Yep, no additional predication needed. Perform the transform.
9987 SDValue IID = N->getOperand(0);
9988 SDValue Shift = N->getOperand(2);
9989 SDValue Vec = Op1.getOperand(0);
9990 SDValue Lane = Op1.getOperand(1);
9991 EVT ResTy = N->getValueType(0);
9992 EVT VecResTy;
9993 SDLoc DL(N);
9994
9995 // The vector width should be 128 bits by the time we get here, even
9996 // if it started as 64 bits (the extract_vector handling will have
9997 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009998 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009999 "unexpected vector size on extract_vector_elt!");
10000 if (Vec.getValueType() == MVT::v4i32)
10001 VecResTy = MVT::v4f32;
10002 else if (Vec.getValueType() == MVT::v2i64)
10003 VecResTy = MVT::v2f64;
10004 else
Craig Topper2a30d782014-06-18 05:05:13 +000010005 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +000010006
10007 SDValue Convert =
10008 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10009 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10010 }
10011 return SDValue();
10012}
10013
10014// AArch64 high-vector "long" operations are formed by performing the non-high
10015// version on an extract_subvector of each operand which gets the high half:
10016//
10017// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10018//
10019// However, there are cases which don't have an extract_high explicitly, but
10020// have another operation that can be made compatible with one for free. For
10021// example:
10022//
10023// (dupv64 scalar) --> (extract_high (dup128 scalar))
10024//
10025// This routine does the actual conversion of such DUPs, once outer routines
10026// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010027// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10028// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +000010029static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010030 switch (N.getOpcode()) {
10031 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +000010032 case AArch64ISD::DUPLANE8:
10033 case AArch64ISD::DUPLANE16:
10034 case AArch64ISD::DUPLANE32:
10035 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010036 case AArch64ISD::MOVI:
10037 case AArch64ISD::MOVIshift:
10038 case AArch64ISD::MOVIedit:
10039 case AArch64ISD::MOVImsl:
10040 case AArch64ISD::MVNIshift:
10041 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +000010042 break;
10043 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010044 // FMOV could be supported, but isn't very useful, as it would only occur
10045 // if you passed a bitcast' floating point immediate to an eligible long
10046 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +000010047 return SDValue();
10048 }
10049
10050 MVT NarrowTy = N.getSimpleValueType();
10051 if (!NarrowTy.is64BitVector())
10052 return SDValue();
10053
10054 MVT ElementTy = NarrowTy.getVectorElementType();
10055 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010056 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +000010057
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010058 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010059 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10060 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010061 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010062}
10063
Eli Friedman29c06092019-02-08 00:23:35 +000010064static bool isEssentiallyExtractHighSubvector(SDValue N) {
10065 if (N.getOpcode() == ISD::BITCAST)
10066 N = N.getOperand(0);
10067 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10068 return false;
10069 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10070 N.getOperand(0).getValueType().getVectorNumElements() / 2;
Tim Northover3b0846e2014-05-24 12:50:23 +000010071}
10072
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010073/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +000010074struct GenericSetCCInfo {
10075 const SDValue *Opnd0;
10076 const SDValue *Opnd1;
10077 ISD::CondCode CC;
10078};
10079
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010080/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +000010081struct AArch64SetCCInfo {
10082 const SDValue *Cmp;
10083 AArch64CC::CondCode CC;
10084};
10085
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010086/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +000010087union SetCCInfo {
10088 GenericSetCCInfo Generic;
10089 AArch64SetCCInfo AArch64;
10090};
10091
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010092/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +000010093/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10094/// GenericSetCCInfo.
10095struct SetCCInfoAndKind {
10096 SetCCInfo Info;
10097 bool IsAArch64;
10098};
10099
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010100/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +000010101/// an
10102/// AArch64 lowered one.
10103/// \p SetCCInfo is filled accordingly.
10104/// \post SetCCInfo is meanginfull only when this function returns true.
10105/// \return True when Op is a kind of SET_CC operation.
10106static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10107 // If this is a setcc, this is straight forward.
10108 if (Op.getOpcode() == ISD::SETCC) {
10109 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10110 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10111 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10112 SetCCInfo.IsAArch64 = false;
10113 return true;
10114 }
10115 // Otherwise, check if this is a matching csel instruction.
10116 // In other words:
10117 // - csel 1, 0, cc
10118 // - csel 0, 1, !cc
10119 if (Op.getOpcode() != AArch64ISD::CSEL)
10120 return false;
10121 // Set the information about the operands.
10122 // TODO: we want the operands of the Cmp not the csel
10123 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10124 SetCCInfo.IsAArch64 = true;
10125 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10126 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10127
10128 // Check that the operands matches the constraints:
10129 // (1) Both operands must be constants.
10130 // (2) One must be 1 and the other must be 0.
10131 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10132 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10133
10134 // Check (1).
10135 if (!TValue || !FValue)
10136 return false;
10137
10138 // Check (2).
10139 if (!TValue->isOne()) {
10140 // Update the comparison when we are interested in !cc.
10141 std::swap(TValue, FValue);
10142 SetCCInfo.Info.AArch64.CC =
10143 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10144 }
10145 return TValue->isOne() && FValue->isNullValue();
10146}
10147
10148// Returns true if Op is setcc or zext of setcc.
10149static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10150 if (isSetCC(Op, Info))
10151 return true;
10152 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10153 isSetCC(Op->getOperand(0), Info));
10154}
10155
10156// The folding we want to perform is:
10157// (add x, [zext] (setcc cc ...) )
10158// -->
10159// (csel x, (add x, 1), !cc ...)
10160//
10161// The latter will get matched to a CSINC instruction.
10162static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10163 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10164 SDValue LHS = Op->getOperand(0);
10165 SDValue RHS = Op->getOperand(1);
10166 SetCCInfoAndKind InfoAndKind;
10167
10168 // If neither operand is a SET_CC, give up.
10169 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10170 std::swap(LHS, RHS);
10171 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10172 return SDValue();
10173 }
10174
10175 // FIXME: This could be generatized to work for FP comparisons.
10176 EVT CmpVT = InfoAndKind.IsAArch64
10177 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10178 : InfoAndKind.Info.Generic.Opnd0->getValueType();
10179 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10180 return SDValue();
10181
10182 SDValue CCVal;
10183 SDValue Cmp;
10184 SDLoc dl(Op);
10185 if (InfoAndKind.IsAArch64) {
10186 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010187 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10188 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +000010189 Cmp = *InfoAndKind.Info.AArch64.Cmp;
10190 } else
10191 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
10192 *InfoAndKind.Info.Generic.Opnd1,
10193 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
10194 CCVal, DAG, dl);
10195
10196 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010197 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +000010198 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10199}
10200
10201// The basic add/sub long vector instructions have variants with "2" on the end
10202// which act on the high-half of their inputs. They are normally matched by
10203// patterns like:
10204//
10205// (add (zeroext (extract_high LHS)),
10206// (zeroext (extract_high RHS)))
10207// -> uaddl2 vD, vN, vM
10208//
10209// However, if one of the extracts is something like a duplicate, this
10210// instruction can still be used profitably. This function puts the DAG into a
10211// more appropriate form for those patterns to trigger.
10212static SDValue performAddSubLongCombine(SDNode *N,
10213 TargetLowering::DAGCombinerInfo &DCI,
10214 SelectionDAG &DAG) {
10215 if (DCI.isBeforeLegalizeOps())
10216 return SDValue();
10217
10218 MVT VT = N->getSimpleValueType(0);
10219 if (!VT.is128BitVector()) {
10220 if (N->getOpcode() == ISD::ADD)
10221 return performSetccAddFolding(N, DAG);
10222 return SDValue();
10223 }
10224
10225 // Make sure both branches are extended in the same way.
10226 SDValue LHS = N->getOperand(0);
10227 SDValue RHS = N->getOperand(1);
10228 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10229 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10230 LHS.getOpcode() != RHS.getOpcode())
10231 return SDValue();
10232
10233 unsigned ExtType = LHS.getOpcode();
10234
10235 // It's not worth doing if at least one of the inputs isn't already an
10236 // extract, but we don't know which it'll be so we have to try both.
Eli Friedman29c06092019-02-08 00:23:35 +000010237 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010238 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10239 if (!RHS.getNode())
10240 return SDValue();
10241
10242 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
Eli Friedman29c06092019-02-08 00:23:35 +000010243 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010244 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10245 if (!LHS.getNode())
10246 return SDValue();
10247
10248 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10249 }
10250
10251 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10252}
10253
10254// Massage DAGs which we can use the high-half "long" operations on into
10255// something isel will recognize better. E.g.
10256//
10257// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10258// (aarch64_neon_umull (extract_high (v2i64 vec)))
10259// (extract_high (v2i64 (dup128 scalar)))))
10260//
Hal Finkelcd8664c2015-12-11 23:11:52 +000010261static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +000010262 TargetLowering::DAGCombinerInfo &DCI,
10263 SelectionDAG &DAG) {
10264 if (DCI.isBeforeLegalizeOps())
10265 return SDValue();
10266
Hal Finkelcd8664c2015-12-11 23:11:52 +000010267 SDValue LHS = N->getOperand(1);
10268 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +000010269 assert(LHS.getValueType().is64BitVector() &&
10270 RHS.getValueType().is64BitVector() &&
10271 "unexpected shape for long operation");
10272
10273 // Either node could be a DUP, but it's not worth doing both of them (you'd
10274 // just as well use the non-high version) so look for a corresponding extract
10275 // operation on the other "wing".
Eli Friedman29c06092019-02-08 00:23:35 +000010276 if (isEssentiallyExtractHighSubvector(LHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010277 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10278 if (!RHS.getNode())
10279 return SDValue();
Eli Friedman29c06092019-02-08 00:23:35 +000010280 } else if (isEssentiallyExtractHighSubvector(RHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010281 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10282 if (!LHS.getNode())
10283 return SDValue();
10284 }
10285
Hal Finkelcd8664c2015-12-11 23:11:52 +000010286 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10287 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +000010288}
10289
10290static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10291 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10292 unsigned ElemBits = ElemTy.getSizeInBits();
10293
10294 int64_t ShiftAmount;
10295 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10296 APInt SplatValue, SplatUndef;
10297 unsigned SplatBitSize;
10298 bool HasAnyUndefs;
10299 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10300 HasAnyUndefs, ElemBits) ||
10301 SplatBitSize != ElemBits)
10302 return SDValue();
10303
10304 ShiftAmount = SplatValue.getSExtValue();
10305 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10306 ShiftAmount = CVN->getSExtValue();
10307 } else
10308 return SDValue();
10309
10310 unsigned Opcode;
10311 bool IsRightShift;
10312 switch (IID) {
10313 default:
10314 llvm_unreachable("Unknown shift intrinsic");
10315 case Intrinsic::aarch64_neon_sqshl:
10316 Opcode = AArch64ISD::SQSHL_I;
10317 IsRightShift = false;
10318 break;
10319 case Intrinsic::aarch64_neon_uqshl:
10320 Opcode = AArch64ISD::UQSHL_I;
10321 IsRightShift = false;
10322 break;
10323 case Intrinsic::aarch64_neon_srshl:
10324 Opcode = AArch64ISD::SRSHR_I;
10325 IsRightShift = true;
10326 break;
10327 case Intrinsic::aarch64_neon_urshl:
10328 Opcode = AArch64ISD::URSHR_I;
10329 IsRightShift = true;
10330 break;
10331 case Intrinsic::aarch64_neon_sqshlu:
10332 Opcode = AArch64ISD::SQSHLU_I;
10333 IsRightShift = false;
10334 break;
10335 }
10336
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010337 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10338 SDLoc dl(N);
10339 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10340 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10341 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10342 SDLoc dl(N);
10343 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10344 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10345 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010346
10347 return SDValue();
10348}
10349
10350// The CRC32[BH] instructions ignore the high bits of their data operand. Since
10351// the intrinsics must be legal and take an i32, this means there's almost
10352// certainly going to be a zext in the DAG which we can eliminate.
10353static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10354 SDValue AndN = N->getOperand(2);
10355 if (AndN.getOpcode() != ISD::AND)
10356 return SDValue();
10357
10358 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10359 if (!CMask || CMask->getZExtValue() != Mask)
10360 return SDValue();
10361
10362 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10363 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10364}
10365
Ahmed Bougachafab58922015-03-10 20:45:38 +000010366static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10367 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010368 SDLoc dl(N);
10369 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10370 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +000010371 N->getOperand(1).getSimpleValueType(),
10372 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010373 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +000010374}
10375
Tim Northover3b0846e2014-05-24 12:50:23 +000010376static SDValue performIntrinsicCombine(SDNode *N,
10377 TargetLowering::DAGCombinerInfo &DCI,
10378 const AArch64Subtarget *Subtarget) {
10379 SelectionDAG &DAG = DCI.DAG;
10380 unsigned IID = getIntrinsicID(N);
10381 switch (IID) {
10382 default:
10383 break;
10384 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10385 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10386 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +000010387 case Intrinsic::aarch64_neon_saddv:
10388 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10389 case Intrinsic::aarch64_neon_uaddv:
10390 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10391 case Intrinsic::aarch64_neon_sminv:
10392 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10393 case Intrinsic::aarch64_neon_uminv:
10394 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10395 case Intrinsic::aarch64_neon_smaxv:
10396 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10397 case Intrinsic::aarch64_neon_umaxv:
10398 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010399 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +000010400 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010401 N->getOperand(1), N->getOperand(2));
10402 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +000010403 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010404 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +000010405 case Intrinsic::aarch64_neon_fmaxnm:
10406 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10407 N->getOperand(1), N->getOperand(2));
10408 case Intrinsic::aarch64_neon_fminnm:
10409 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10410 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010411 case Intrinsic::aarch64_neon_smull:
10412 case Intrinsic::aarch64_neon_umull:
10413 case Intrinsic::aarch64_neon_pmull:
10414 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +000010415 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010416 case Intrinsic::aarch64_neon_sqshl:
10417 case Intrinsic::aarch64_neon_uqshl:
10418 case Intrinsic::aarch64_neon_sqshlu:
10419 case Intrinsic::aarch64_neon_srshl:
10420 case Intrinsic::aarch64_neon_urshl:
10421 return tryCombineShiftImm(IID, N, DAG);
10422 case Intrinsic::aarch64_crc32b:
10423 case Intrinsic::aarch64_crc32cb:
10424 return tryCombineCRC32(0xff, N, DAG);
10425 case Intrinsic::aarch64_crc32h:
10426 case Intrinsic::aarch64_crc32ch:
10427 return tryCombineCRC32(0xffff, N, DAG);
10428 }
10429 return SDValue();
10430}
10431
10432static SDValue performExtendCombine(SDNode *N,
10433 TargetLowering::DAGCombinerInfo &DCI,
10434 SelectionDAG &DAG) {
10435 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10436 // we can convert that DUP into another extract_high (of a bigger DUP), which
10437 // helps the backend to decide that an sabdl2 would be useful, saving a real
10438 // extract_high operation.
10439 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +000010440 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010441 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010442 unsigned IID = getIntrinsicID(ABDNode);
10443 if (IID == Intrinsic::aarch64_neon_sabd ||
10444 IID == Intrinsic::aarch64_neon_uabd) {
10445 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10446 if (!NewABD.getNode())
10447 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010448
Hal Finkelcd8664c2015-12-11 23:11:52 +000010449 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10450 NewABD);
10451 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010452 }
10453
10454 // This is effectively a custom type legalization for AArch64.
10455 //
10456 // Type legalization will split an extend of a small, legal, type to a larger
10457 // illegal type by first splitting the destination type, often creating
10458 // illegal source types, which then get legalized in isel-confusing ways,
10459 // leading to really terrible codegen. E.g.,
10460 // %result = v8i32 sext v8i8 %value
10461 // becomes
10462 // %losrc = extract_subreg %value, ...
10463 // %hisrc = extract_subreg %value, ...
10464 // %lo = v4i32 sext v4i8 %losrc
10465 // %hi = v4i32 sext v4i8 %hisrc
10466 // Things go rapidly downhill from there.
10467 //
10468 // For AArch64, the [sz]ext vector instructions can only go up one element
10469 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10470 // take two instructions.
10471 //
10472 // This implies that the most efficient way to do the extend from v8i8
10473 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10474 // the normal splitting to happen for the v8i16->v8i32.
10475
10476 // This is pre-legalization to catch some cases where the default
10477 // type legalization will create ill-tempered code.
10478 if (!DCI.isBeforeLegalizeOps())
10479 return SDValue();
10480
10481 // We're only interested in cleaning things up for non-legal vector types
10482 // here. If both the source and destination are legal, things will just
10483 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010484 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010485 EVT ResVT = N->getValueType(0);
10486 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10487 return SDValue();
10488 // If the vector type isn't a simple VT, it's beyond the scope of what
10489 // we're worried about here. Let legalization do its thing and hope for
10490 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010491 SDValue Src = N->getOperand(0);
10492 EVT SrcVT = Src->getValueType(0);
10493 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010494 return SDValue();
10495
Tim Northover3b0846e2014-05-24 12:50:23 +000010496 // If the source VT is a 64-bit vector, we can play games and get the
10497 // better results we want.
10498 if (SrcVT.getSizeInBits() != 64)
10499 return SDValue();
10500
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010501 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010502 unsigned ElementCount = SrcVT.getVectorNumElements();
10503 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10504 SDLoc DL(N);
10505 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10506
10507 // Now split the rest of the operation into two halves, each with a 64
10508 // bit source.
10509 EVT LoVT, HiVT;
10510 SDValue Lo, Hi;
10511 unsigned NumElements = ResVT.getVectorNumElements();
10512 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10513 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10514 ResVT.getVectorElementType(), NumElements / 2);
10515
10516 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10517 LoVT.getVectorNumElements());
10518 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010519 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010520 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010521 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010522 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10523 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10524
10525 // Now combine the parts back together so we still have a single result
10526 // like the combiner expects.
10527 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10528}
10529
Geoff Berry8301c642016-11-16 19:35:19 +000010530static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10531 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010532 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010533 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010534 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010535
10536 // Create scalar stores. This is at least as good as the code sequence for a
10537 // split unaligned store which is a dup.s, ext.b, and two stores.
10538 // Most of the time the three stores should be replaced by store pair
10539 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010540 SDLoc DL(&St);
10541 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010542 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010543
John Brawn3a9c8422017-02-06 18:07:20 +000010544 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010545 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010546 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010547 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010548
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010549 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010550 if (BasePtr->getOpcode() == ISD::ADD &&
10551 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10552 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10553 BasePtr = BasePtr->getOperand(0);
10554 }
10555
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010556 unsigned Offset = EltOffset;
10557 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010558 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010559 SDValue OffsetPtr =
10560 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10561 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010562 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010563 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010564 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010565 Offset += EltOffset;
10566 }
10567 return NewST1;
10568}
10569
Geoff Berry526c5052016-11-14 19:39:04 +000010570/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10571/// load store optimizer pass will merge them to store pair stores. This should
10572/// be better than a movi to create the vector zero followed by a vector store
10573/// if the zero constant is not re-used, since one instructions and one register
10574/// live range will be removed.
10575///
10576/// For example, the final generated code should be:
10577///
10578/// stp xzr, xzr, [x0]
10579///
10580/// instead of:
10581///
10582/// movi v0.2d, #0
10583/// str q0, [x0]
10584///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010585static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10586 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010587 EVT VT = StVal.getValueType();
10588
Geoff Berry8301c642016-11-16 19:35:19 +000010589 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10590 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010591 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010592 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10593 VT.getVectorElementType().getSizeInBits() == 64) ||
10594 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10595 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010596 return SDValue();
10597
10598 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10599 return SDValue();
10600
10601 // If the zero constant has more than one use then the vector store could be
10602 // better since the constant mov will be amortized and stp q instructions
10603 // should be able to be formed.
10604 if (!StVal.hasOneUse())
10605 return SDValue();
10606
Tim Northover964eea72019-01-08 13:30:27 +000010607 // If the store is truncating then it's going down to i16 or smaller, which
10608 // means it can be implemented in a single store anyway.
10609 if (St.isTruncatingStore())
10610 return SDValue();
10611
Geoff Berry526c5052016-11-14 19:39:04 +000010612 // If the immediate offset of the address operand is too large for the stp
10613 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010614 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10615 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010616 if (Offset < -512 || Offset > 504)
10617 return SDValue();
10618 }
10619
10620 for (int I = 0; I < NumVecElts; ++I) {
10621 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010622 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010623 return SDValue();
10624 }
Geoff Berry8301c642016-11-16 19:35:19 +000010625
Geoff Berrybb23df92017-09-21 21:10:06 +000010626 // Use a CopyFromReg WZR/XZR here to prevent
10627 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10628 SDLoc DL(&St);
10629 unsigned ZeroReg;
10630 EVT ZeroVT;
10631 if (VT.getVectorElementType().getSizeInBits() == 32) {
10632 ZeroReg = AArch64::WZR;
10633 ZeroVT = MVT::i32;
10634 } else {
10635 ZeroReg = AArch64::XZR;
10636 ZeroVT = MVT::i64;
10637 }
10638 SDValue SplatVal =
10639 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010640 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010641}
10642
Tim Northover3b0846e2014-05-24 12:50:23 +000010643/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10644/// value. The load store optimizer pass will merge them to store pair stores.
10645/// This has better performance than a splat of the scalar followed by a split
10646/// vector store. Even if the stores are not merged it is four stores vs a dup,
10647/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010648static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10649 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010650 EVT VT = StVal.getValueType();
10651
10652 // Don't replace floating point stores, they possibly won't be transformed to
10653 // stp because of the store pair suppress pass.
10654 if (VT.isFloatingPoint())
10655 return SDValue();
10656
Tim Northover3b0846e2014-05-24 12:50:23 +000010657 // We can express a splat as store pair(s) for 2 or 4 elements.
10658 unsigned NumVecElts = VT.getVectorNumElements();
10659 if (NumVecElts != 4 && NumVecElts != 2)
10660 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010661
Tim Northover964eea72019-01-08 13:30:27 +000010662 // If the store is truncating then it's going down to i16 or smaller, which
10663 // means it can be implemented in a single store anyway.
10664 if (St.isTruncatingStore())
10665 return SDValue();
10666
Tim Northover3b0846e2014-05-24 12:50:23 +000010667 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010668 // Make sure that each of the relevant vector element locations are inserted
10669 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10670 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10671 SDValue SplatVal;
10672 for (unsigned I = 0; I < NumVecElts; ++I) {
10673 // Check for insert vector elements.
10674 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010675 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010676
10677 // Check that same value is inserted at each vector element.
10678 if (I == 0)
10679 SplatVal = StVal.getOperand(1);
10680 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010681 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010682
10683 // Check insert element index.
10684 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10685 if (!CIndex)
10686 return SDValue();
10687 uint64_t IndexVal = CIndex->getZExtValue();
10688 if (IndexVal >= NumVecElts)
10689 return SDValue();
10690 IndexNotInserted.reset(IndexVal);
10691
10692 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010693 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010694 // Check that all vector element locations were inserted to.
10695 if (IndexNotInserted.any())
10696 return SDValue();
10697
Geoff Berry8301c642016-11-16 19:35:19 +000010698 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010699}
10700
Geoff Berry8301c642016-11-16 19:35:19 +000010701static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10702 SelectionDAG &DAG,
10703 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010704
10705 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010706 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010707 return SDValue();
10708
Geoff Berry526c5052016-11-14 19:39:04 +000010709 SDValue StVal = S->getValue();
10710 EVT VT = StVal.getValueType();
10711 if (!VT.isVector())
10712 return SDValue();
10713
10714 // If we get a splat of zeros, convert this vector store to a store of
10715 // scalars. They will be merged into store pairs of xzr thereby removing one
10716 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010717 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010718 return ReplacedZeroSplat;
10719
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010720 // FIXME: The logic for deciding if an unaligned store should be split should
10721 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10722 // a call to that function here.
10723
Matthias Braun651cff42016-06-02 18:03:53 +000010724 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010725 return SDValue();
10726
Sanjay Patel924879a2015-08-04 15:49:57 +000010727 // Don't split at -Oz.
Evandro Menezes85bd3972019-04-04 22:40:06 +000010728 if (DAG.getMachineFunction().getFunction().hasMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010729 return SDValue();
10730
Tim Northover3b0846e2014-05-24 12:50:23 +000010731 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10732 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010733 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010734 return SDValue();
10735
10736 // Split unaligned 16B stores. They are terrible for performance.
10737 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10738 // extensions can use this to mark that it does not want splitting to happen
10739 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10740 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10741 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10742 S->getAlignment() <= 2)
10743 return SDValue();
10744
10745 // If we get a splat of a scalar convert this vector store to a store of
10746 // scalars. They will be merged into store pairs thereby removing two
10747 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010748 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010749 return ReplacedSplat;
10750
10751 SDLoc DL(S);
Simon Pilgrimc88408c2019-08-23 12:37:09 +000010752
Tim Northover3b0846e2014-05-24 12:50:23 +000010753 // Split VT into two.
Simon Pilgrimc88408c2019-08-23 12:37:09 +000010754 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
10755 unsigned NumElts = HalfVT.getVectorNumElements();
Tim Northover3b0846e2014-05-24 12:50:23 +000010756 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010757 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010758 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010759 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010760 SDValue BasePtr = S->getBasePtr();
10761 SDValue NewST1 =
10762 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010763 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010764 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010765 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010766 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010767 S->getPointerInfo(), S->getAlignment(),
10768 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010769}
10770
10771/// Target-specific DAG combine function for post-increment LD1 (lane) and
10772/// post-increment LD1R.
10773static SDValue performPostLD1Combine(SDNode *N,
10774 TargetLowering::DAGCombinerInfo &DCI,
10775 bool IsLaneOp) {
10776 if (DCI.isBeforeLegalizeOps())
10777 return SDValue();
10778
10779 SelectionDAG &DAG = DCI.DAG;
10780 EVT VT = N->getValueType(0);
10781
10782 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10783 SDNode *LD = N->getOperand(LoadIdx).getNode();
10784 // If it is not LOAD, can not do such combine.
10785 if (LD->getOpcode() != ISD::LOAD)
10786 return SDValue();
10787
Geoff Berry60460262018-05-11 16:25:06 +000010788 // The vector lane must be a constant in the LD1LANE opcode.
10789 SDValue Lane;
10790 if (IsLaneOp) {
10791 Lane = N->getOperand(2);
10792 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10793 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10794 return SDValue();
10795 }
10796
Tim Northover3b0846e2014-05-24 12:50:23 +000010797 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10798 EVT MemVT = LoadSDN->getMemoryVT();
10799 // Check if memory operand is the same type as the vector element.
10800 if (MemVT != VT.getVectorElementType())
10801 return SDValue();
10802
10803 // Check if there are other uses. If so, do not combine as it will introduce
10804 // an extra load.
10805 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10806 ++UI) {
10807 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10808 continue;
10809 if (*UI != N)
10810 return SDValue();
10811 }
10812
10813 SDValue Addr = LD->getOperand(1);
10814 SDValue Vector = N->getOperand(0);
10815 // Search for a use of the address operand that is an increment.
10816 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10817 Addr.getNode()->use_end(); UI != UE; ++UI) {
10818 SDNode *User = *UI;
10819 if (User->getOpcode() != ISD::ADD
10820 || UI.getUse().getResNo() != Addr.getResNo())
10821 continue;
10822
Tim Northover3b0846e2014-05-24 12:50:23 +000010823 // If the increment is a constant, it must match the memory ref size.
10824 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10825 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10826 uint32_t IncVal = CInc->getZExtValue();
10827 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10828 if (IncVal != NumBytes)
10829 continue;
10830 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10831 }
10832
Nirav Davee40e2bb2018-09-25 15:30:22 +000010833 // To avoid cycle construction make sure that neither the load nor the add
10834 // are predecessors to each other or the Vector.
10835 SmallPtrSet<const SDNode *, 32> Visited;
10836 SmallVector<const SDNode *, 16> Worklist;
Tim Northovera7f226f2019-08-27 10:21:11 +000010837 Visited.insert(Addr.getNode());
Nirav Davee40e2bb2018-09-25 15:30:22 +000010838 Worklist.push_back(User);
10839 Worklist.push_back(LD);
10840 Worklist.push_back(Vector.getNode());
10841 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10842 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010843 continue;
10844
Tim Northover3b0846e2014-05-24 12:50:23 +000010845 SmallVector<SDValue, 8> Ops;
10846 Ops.push_back(LD->getOperand(0)); // Chain
10847 if (IsLaneOp) {
10848 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010849 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010850 }
10851 Ops.push_back(Addr);
10852 Ops.push_back(Inc);
10853
10854 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010855 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010856 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10857 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10858 MemVT,
10859 LoadSDN->getMemOperand());
10860
10861 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010862 SDValue NewResults[] = {
10863 SDValue(LD, 0), // The result of load
10864 SDValue(UpdN.getNode(), 2) // Chain
10865 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010866 DCI.CombineTo(LD, NewResults);
10867 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10868 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10869
10870 break;
10871 }
10872 return SDValue();
10873}
10874
Joel Jones7466ccf2017-07-10 22:11:50 +000010875/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010876/// address translation.
10877static bool performTBISimplification(SDValue Addr,
10878 TargetLowering::DAGCombinerInfo &DCI,
10879 SelectionDAG &DAG) {
10880 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010881 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010882 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10883 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010885 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010886 DCI.CommitTargetLoweringOpt(TLO);
10887 return true;
10888 }
10889 return false;
10890}
10891
10892static SDValue performSTORECombine(SDNode *N,
10893 TargetLowering::DAGCombinerInfo &DCI,
10894 SelectionDAG &DAG,
10895 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010896 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010897 return Split;
10898
10899 if (Subtarget->supportsAddressTopByteIgnored() &&
10900 performTBISimplification(N->getOperand(2), DCI, DAG))
10901 return SDValue(N, 0);
10902
10903 return SDValue();
10904}
10905
Chad Rosier6c36eff2015-09-03 18:13:57 +000010906
Tim Northover3b0846e2014-05-24 12:50:23 +000010907/// Target-specific DAG combine function for NEON load/store intrinsics
10908/// to merge base address updates.
10909static SDValue performNEONPostLDSTCombine(SDNode *N,
10910 TargetLowering::DAGCombinerInfo &DCI,
10911 SelectionDAG &DAG) {
10912 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10913 return SDValue();
10914
10915 unsigned AddrOpIdx = N->getNumOperands() - 1;
10916 SDValue Addr = N->getOperand(AddrOpIdx);
10917
10918 // Search for a use of the address operand that is an increment.
10919 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10920 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10921 SDNode *User = *UI;
10922 if (User->getOpcode() != ISD::ADD ||
10923 UI.getUse().getResNo() != Addr.getResNo())
10924 continue;
10925
10926 // Check that the add is independent of the load/store. Otherwise, folding
10927 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010928 SmallPtrSet<const SDNode *, 32> Visited;
10929 SmallVector<const SDNode *, 16> Worklist;
10930 Visited.insert(Addr.getNode());
10931 Worklist.push_back(N);
10932 Worklist.push_back(User);
10933 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10934 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010935 continue;
10936
10937 // Find the new opcode for the updating load/store.
10938 bool IsStore = false;
10939 bool IsLaneOp = false;
10940 bool IsDupOp = false;
10941 unsigned NewOpc = 0;
10942 unsigned NumVecs = 0;
10943 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10944 switch (IntNo) {
10945 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10946 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10947 NumVecs = 2; break;
10948 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10949 NumVecs = 3; break;
10950 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10951 NumVecs = 4; break;
10952 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10953 NumVecs = 2; IsStore = true; break;
10954 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10955 NumVecs = 3; IsStore = true; break;
10956 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10957 NumVecs = 4; IsStore = true; break;
10958 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10959 NumVecs = 2; break;
10960 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10961 NumVecs = 3; break;
10962 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10963 NumVecs = 4; break;
10964 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10965 NumVecs = 2; IsStore = true; break;
10966 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10967 NumVecs = 3; IsStore = true; break;
10968 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10969 NumVecs = 4; IsStore = true; break;
10970 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10971 NumVecs = 2; IsDupOp = true; break;
10972 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10973 NumVecs = 3; IsDupOp = true; break;
10974 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10975 NumVecs = 4; IsDupOp = true; break;
10976 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10977 NumVecs = 2; IsLaneOp = true; break;
10978 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10979 NumVecs = 3; IsLaneOp = true; break;
10980 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10981 NumVecs = 4; IsLaneOp = true; break;
10982 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10983 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10984 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10985 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10986 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10987 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10988 }
10989
10990 EVT VecTy;
10991 if (IsStore)
10992 VecTy = N->getOperand(2).getValueType();
10993 else
10994 VecTy = N->getValueType(0);
10995
10996 // If the increment is a constant, it must match the memory ref size.
10997 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10998 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10999 uint32_t IncVal = CInc->getZExtValue();
11000 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11001 if (IsLaneOp || IsDupOp)
11002 NumBytes /= VecTy.getVectorNumElements();
11003 if (IncVal != NumBytes)
11004 continue;
11005 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11006 }
11007 SmallVector<SDValue, 8> Ops;
11008 Ops.push_back(N->getOperand(0)); // Incoming chain
11009 // Load lane and store have vector list as input.
11010 if (IsLaneOp || IsStore)
11011 for (unsigned i = 2; i < AddrOpIdx; ++i)
11012 Ops.push_back(N->getOperand(i));
11013 Ops.push_back(Addr); // Base register
11014 Ops.push_back(Inc);
11015
11016 // Return Types.
11017 EVT Tys[6];
11018 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
11019 unsigned n;
11020 for (n = 0; n < NumResultVecs; ++n)
11021 Tys[n] = VecTy;
11022 Tys[n++] = MVT::i64; // Type of write back register
11023 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000011024 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000011025
11026 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
11027 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
11028 MemInt->getMemoryVT(),
11029 MemInt->getMemOperand());
11030
11031 // Update the uses.
11032 std::vector<SDValue> NewResults;
11033 for (unsigned i = 0; i < NumResultVecs; ++i) {
11034 NewResults.push_back(SDValue(UpdN.getNode(), i));
11035 }
11036 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
11037 DCI.CombineTo(N, NewResults);
11038 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11039
11040 break;
11041 }
11042 return SDValue();
11043}
11044
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011045// Checks to see if the value is the prescribed width and returns information
11046// about its extension mode.
11047static
11048bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
11049 ExtType = ISD::NON_EXTLOAD;
11050 switch(V.getNode()->getOpcode()) {
11051 default:
11052 return false;
11053 case ISD::LOAD: {
11054 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
11055 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
11056 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
11057 ExtType = LoadNode->getExtensionType();
11058 return true;
11059 }
11060 return false;
11061 }
11062 case ISD::AssertSext: {
11063 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11064 if ((TypeNode->getVT() == MVT::i8 && width == 8)
11065 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11066 ExtType = ISD::SEXTLOAD;
11067 return true;
11068 }
11069 return false;
11070 }
11071 case ISD::AssertZext: {
11072 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11073 if ((TypeNode->getVT() == MVT::i8 && width == 8)
11074 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11075 ExtType = ISD::ZEXTLOAD;
11076 return true;
11077 }
11078 return false;
11079 }
11080 case ISD::Constant:
11081 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011082 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
11083 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011084 }
11085 }
11086
11087 return true;
11088}
11089
11090// This function does a whole lot of voodoo to determine if the tests are
11091// equivalent without and with a mask. Essentially what happens is that given a
11092// DAG resembling:
11093//
11094// +-------------+ +-------------+ +-------------+ +-------------+
11095// | Input | | AddConstant | | CompConstant| | CC |
11096// +-------------+ +-------------+ +-------------+ +-------------+
11097// | | | |
11098// V V | +----------+
11099// +-------------+ +----+ | |
11100// | ADD | |0xff| | |
11101// +-------------+ +----+ | |
11102// | | | |
11103// V V | |
11104// +-------------+ | |
11105// | AND | | |
11106// +-------------+ | |
11107// | | |
11108// +-----+ | |
11109// | | |
11110// V V V
11111// +-------------+
11112// | CMP |
11113// +-------------+
11114//
11115// The AND node may be safely removed for some combinations of inputs. In
11116// particular we need to take into account the extension type of the Input,
11117// the exact values of AddConstant, CompConstant, and CC, along with the nominal
11118// width of the input (this can work for any width inputs, the above graph is
11119// specific to 8 bits.
11120//
11121// The specific equations were worked out by generating output tables for each
11122// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
11123// problem was simplified by working with 4 bit inputs, which means we only
11124// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
11125// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
11126// patterns present in both extensions (0,7). For every distinct set of
11127// AddConstant and CompConstants bit patterns we can consider the masked and
11128// unmasked versions to be equivalent if the result of this function is true for
11129// all 16 distinct bit patterns of for the current extension type of Input (w0).
11130//
11131// sub w8, w0, w1
11132// and w10, w8, #0x0f
11133// cmp w8, w2
11134// cset w9, AArch64CC
11135// cmp w10, w2
11136// cset w11, AArch64CC
11137// cmp w9, w11
11138// cset w0, eq
11139// ret
11140//
11141// Since the above function shows when the outputs are equivalent it defines
11142// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11143// would be expensive to run during compiles. The equations below were written
11144// in a test harness that confirmed they gave equivalent outputs to the above
11145// for all inputs function, so they can be used determine if the removal is
11146// legal instead.
11147//
11148// isEquivalentMaskless() is the code for testing if the AND can be removed
11149// factored out of the DAG recognition as the DAG can take several forms.
11150
David Majnemere61e4bf2016-06-21 05:10:24 +000011151static bool isEquivalentMaskless(unsigned CC, unsigned width,
11152 ISD::LoadExtType ExtType, int AddConstant,
11153 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011154 // By being careful about our equations and only writing the in term
11155 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11156 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000011157 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011158
11159 // For the purposes of these comparisons sign extending the type is
11160 // equivalent to zero extending the add and displacing it by half the integer
11161 // width. Provided we are careful and make sure our equations are valid over
11162 // the whole range we can just adjust the input and avoid writing equations
11163 // for sign extended inputs.
11164 if (ExtType == ISD::SEXTLOAD)
11165 AddConstant -= (1 << (width-1));
11166
11167 switch(CC) {
11168 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011169 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011170 if ((AddConstant == 0) ||
11171 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11172 (AddConstant >= 0 && CompConstant < 0) ||
11173 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11174 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011175 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011176 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011177 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011178 if ((AddConstant == 0) ||
11179 (AddConstant >= 0 && CompConstant <= 0) ||
11180 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11181 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011182 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011183 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011184 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011185 if ((AddConstant >= 0 && CompConstant < 0) ||
11186 (AddConstant <= 0 && CompConstant >= -1 &&
11187 CompConstant < AddConstant + MaxUInt))
11188 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011189 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011190 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011191 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011192 if ((AddConstant == 0) ||
11193 (AddConstant > 0 && CompConstant <= 0) ||
11194 (AddConstant < 0 && CompConstant <= AddConstant))
11195 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011196 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011197 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011198 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011199 if ((AddConstant >= 0 && CompConstant <= 0) ||
11200 (AddConstant <= 0 && CompConstant >= 0 &&
11201 CompConstant <= AddConstant + MaxUInt))
11202 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011203 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011204 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000011205 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011206 if ((AddConstant > 0 && CompConstant < 0) ||
11207 (AddConstant < 0 && CompConstant >= 0 &&
11208 CompConstant < AddConstant + MaxUInt) ||
11209 (AddConstant >= 0 && CompConstant >= 0 &&
11210 CompConstant >= AddConstant) ||
11211 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011212 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011213 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011214 case AArch64CC::VS:
11215 case AArch64CC::VC:
11216 case AArch64CC::AL:
11217 case AArch64CC::NV:
11218 return true;
11219 case AArch64CC::Invalid:
11220 break;
11221 }
11222
11223 return false;
11224}
11225
11226static
11227SDValue performCONDCombine(SDNode *N,
11228 TargetLowering::DAGCombinerInfo &DCI,
11229 SelectionDAG &DAG, unsigned CCIndex,
11230 unsigned CmpIndex) {
11231 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11232 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11233 unsigned CondOpcode = SubsNode->getOpcode();
11234
11235 if (CondOpcode != AArch64ISD::SUBS)
11236 return SDValue();
11237
11238 // There is a SUBS feeding this condition. Is it fed by a mask we can
11239 // use?
11240
11241 SDNode *AndNode = SubsNode->getOperand(0).getNode();
11242 unsigned MaskBits = 0;
11243
11244 if (AndNode->getOpcode() != ISD::AND)
11245 return SDValue();
11246
11247 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11248 uint32_t CNV = CN->getZExtValue();
11249 if (CNV == 255)
11250 MaskBits = 8;
11251 else if (CNV == 65535)
11252 MaskBits = 16;
11253 }
11254
11255 if (!MaskBits)
11256 return SDValue();
11257
11258 SDValue AddValue = AndNode->getOperand(0);
11259
11260 if (AddValue.getOpcode() != ISD::ADD)
11261 return SDValue();
11262
11263 // The basic dag structure is correct, grab the inputs and validate them.
11264
11265 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11266 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11267 SDValue SubsInputValue = SubsNode->getOperand(1);
11268
11269 // The mask is present and the provenance of all the values is a smaller type,
11270 // lets see if the mask is superfluous.
11271
11272 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11273 !isa<ConstantSDNode>(SubsInputValue.getNode()))
11274 return SDValue();
11275
11276 ISD::LoadExtType ExtType;
11277
11278 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11279 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11280 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11281 return SDValue();
11282
11283 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11284 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11285 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11286 return SDValue();
11287
11288 // The AND is not necessary, remove it.
11289
11290 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11291 SubsNode->getValueType(1));
11292 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11293
11294 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11295 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11296
11297 return SDValue(N, 0);
11298}
11299
Tim Northover3b0846e2014-05-24 12:50:23 +000011300// Optimize compare with zero and branch.
11301static SDValue performBRCONDCombine(SDNode *N,
11302 TargetLowering::DAGCombinerInfo &DCI,
11303 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000011304 MachineFunction &MF = DAG.getMachineFunction();
11305 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11306 // will not be produced, as they are conditional branch instructions that do
11307 // not set flags.
11308 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11309 return SDValue();
11310
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000011311 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011312 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000011313 SDValue Chain = N->getOperand(0);
11314 SDValue Dest = N->getOperand(1);
11315 SDValue CCVal = N->getOperand(2);
11316 SDValue Cmp = N->getOperand(3);
11317
11318 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11319 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11320 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11321 return SDValue();
11322
11323 unsigned CmpOpc = Cmp.getOpcode();
11324 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11325 return SDValue();
11326
11327 // Only attempt folding if there is only one use of the flag and no use of the
11328 // value.
11329 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11330 return SDValue();
11331
11332 SDValue LHS = Cmp.getOperand(0);
11333 SDValue RHS = Cmp.getOperand(1);
11334
11335 assert(LHS.getValueType() == RHS.getValueType() &&
11336 "Expected the value type to be the same for both operands!");
11337 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11338 return SDValue();
11339
Artyom Skrobov314ee042015-11-25 19:41:11 +000011340 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011341 std::swap(LHS, RHS);
11342
Artyom Skrobov314ee042015-11-25 19:41:11 +000011343 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011344 return SDValue();
11345
11346 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11347 LHS.getOpcode() == ISD::SRL)
11348 return SDValue();
11349
11350 // Fold the compare into the branch instruction.
11351 SDValue BR;
11352 if (CC == AArch64CC::EQ)
11353 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11354 else
11355 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11356
11357 // Do not add new nodes to DAG combiner worklist.
11358 DCI.CombineTo(N, BR, false);
11359
11360 return SDValue();
11361}
11362
Geoff Berry9e934b02016-01-04 18:55:47 +000011363// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11364// as well as whether the test should be inverted. This code is required to
11365// catch these cases (as opposed to standard dag combines) because
11366// AArch64ISD::TBZ is matched during legalization.
11367static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11368 SelectionDAG &DAG) {
11369
11370 if (!Op->hasOneUse())
11371 return Op;
11372
11373 // We don't handle undef/constant-fold cases below, as they should have
11374 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11375 // etc.)
11376
11377 // (tbz (trunc x), b) -> (tbz x, b)
11378 // This case is just here to enable more of the below cases to be caught.
11379 if (Op->getOpcode() == ISD::TRUNCATE &&
11380 Bit < Op->getValueType(0).getSizeInBits()) {
11381 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11382 }
11383
Craig Topper35fe0792019-04-10 17:27:29 +000011384 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11385 if (Op->getOpcode() == ISD::ANY_EXTEND &&
11386 Bit < Op->getOperand(0).getValueSizeInBits()) {
11387 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11388 }
11389
Geoff Berry9e934b02016-01-04 18:55:47 +000011390 if (Op->getNumOperands() != 2)
11391 return Op;
11392
11393 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11394 if (!C)
11395 return Op;
11396
11397 switch (Op->getOpcode()) {
11398 default:
11399 return Op;
11400
11401 // (tbz (and x, m), b) -> (tbz x, b)
11402 case ISD::AND:
11403 if ((C->getZExtValue() >> Bit) & 1)
11404 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11405 return Op;
11406
11407 // (tbz (shl x, c), b) -> (tbz x, b-c)
11408 case ISD::SHL:
11409 if (C->getZExtValue() <= Bit &&
11410 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11411 Bit = Bit - C->getZExtValue();
11412 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11413 }
11414 return Op;
11415
11416 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11417 case ISD::SRA:
11418 Bit = Bit + C->getZExtValue();
11419 if (Bit >= Op->getValueType(0).getSizeInBits())
11420 Bit = Op->getValueType(0).getSizeInBits() - 1;
11421 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11422
11423 // (tbz (srl x, c), b) -> (tbz x, b+c)
11424 case ISD::SRL:
11425 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11426 Bit = Bit + C->getZExtValue();
11427 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11428 }
11429 return Op;
11430
11431 // (tbz (xor x, -1), b) -> (tbnz x, b)
11432 case ISD::XOR:
11433 if ((C->getZExtValue() >> Bit) & 1)
11434 Invert = !Invert;
11435 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11436 }
11437}
11438
11439// Optimize test single bit zero/non-zero and branch.
11440static SDValue performTBZCombine(SDNode *N,
11441 TargetLowering::DAGCombinerInfo &DCI,
11442 SelectionDAG &DAG) {
11443 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11444 bool Invert = false;
11445 SDValue TestSrc = N->getOperand(1);
11446 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11447
11448 if (TestSrc == NewTestSrc)
11449 return SDValue();
11450
11451 unsigned NewOpc = N->getOpcode();
11452 if (Invert) {
11453 if (NewOpc == AArch64ISD::TBZ)
11454 NewOpc = AArch64ISD::TBNZ;
11455 else {
11456 assert(NewOpc == AArch64ISD::TBNZ);
11457 NewOpc = AArch64ISD::TBZ;
11458 }
11459 }
11460
11461 SDLoc DL(N);
11462 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11463 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11464}
11465
Tim Northover3b0846e2014-05-24 12:50:23 +000011466// vselect (v1i1 setcc) ->
11467// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11468// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11469// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11470// such VSELECT.
11471static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11472 SDValue N0 = N->getOperand(0);
11473 EVT CCVT = N0.getValueType();
11474
11475 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11476 CCVT.getVectorElementType() != MVT::i1)
11477 return SDValue();
11478
11479 EVT ResVT = N->getValueType(0);
11480 EVT CmpVT = N0.getOperand(0).getValueType();
11481 // Only combine when the result type is of the same size as the compared
11482 // operands.
11483 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11484 return SDValue();
11485
11486 SDValue IfTrue = N->getOperand(1);
11487 SDValue IfFalse = N->getOperand(2);
11488 SDValue SetCC =
11489 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11490 N0.getOperand(0), N0.getOperand(1),
11491 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11492 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11493 IfTrue, IfFalse);
11494}
11495
11496/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11497/// the compare-mask instructions rather than going via NZCV, even if LHS and
11498/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11499/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011500static SDValue performSelectCombine(SDNode *N,
11501 TargetLowering::DAGCombinerInfo &DCI) {
11502 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011503 SDValue N0 = N->getOperand(0);
11504 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011505
Ahmed Bougachac004c602015-04-27 21:43:12 +000011506 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011507 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011508
Ahmed Bougachac004c602015-04-27 21:43:12 +000011509 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11510 // scalar SetCCResultType. We also don't expect vectors, because we assume
11511 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11512 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11513 "Scalar-SETCC feeding SELECT has unexpected result type!");
11514
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011515 // If NumMaskElts == 0, the comparison is larger than select result. The
11516 // largest real NEON comparison is 64-bits per lane, which means the result is
11517 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011518 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011519
11520 // Don't try to do this optimization when the setcc itself has i1 operands.
11521 // There are no legal vectors of i1, so this would be pointless.
11522 if (SrcVT == MVT::i1)
11523 return SDValue();
11524
Tim Northover3c0915e2014-08-29 15:34:58 +000011525 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011526 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011527 return SDValue();
11528
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011529 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011530 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11531
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011532 // Also bail out if the vector CCVT isn't the same size as ResVT.
11533 // This can happen if the SETCC operand size doesn't divide the ResVT size
11534 // (e.g., f64 vs v3f32).
11535 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11536 return SDValue();
11537
Ahmed Bougachac004c602015-04-27 21:43:12 +000011538 // Make sure we didn't create illegal types, if we're not supposed to.
11539 assert(DCI.isBeforeLegalize() ||
11540 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11541
Tim Northover3b0846e2014-05-24 12:50:23 +000011542 // First perform a vector comparison, where lane 0 is the one we're interested
11543 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011544 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011545 SDValue LHS =
11546 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11547 SDValue RHS =
11548 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11549 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11550
11551 // Now duplicate the comparison mask we want across all other lanes.
11552 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011553 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011554 Mask = DAG.getNode(ISD::BITCAST, DL,
11555 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011556
11557 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11558}
11559
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011560/// Get rid of unnecessary NVCASTs (that don't change the type).
11561static SDValue performNVCASTCombine(SDNode *N) {
11562 if (N->getValueType(0) == N->getOperand(0).getValueType())
11563 return N->getOperand(0);
11564
11565 return SDValue();
11566}
11567
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011568// If all users of the globaladdr are of the form (globaladdr + constant), find
11569// the smallest constant, fold it into the globaladdr's offset and rewrite the
11570// globaladdr as (globaladdr + constant) - constant.
11571static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11572 const AArch64Subtarget *Subtarget,
11573 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011574 auto *GN = cast<GlobalAddressSDNode>(N);
11575 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11576 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011577 return SDValue();
11578
11579 uint64_t MinOffset = -1ull;
11580 for (SDNode *N : GN->uses()) {
11581 if (N->getOpcode() != ISD::ADD)
11582 return SDValue();
11583 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11584 if (!C)
11585 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11586 if (!C)
11587 return SDValue();
11588 MinOffset = std::min(MinOffset, C->getZExtValue());
11589 }
11590 uint64_t Offset = MinOffset + GN->getOffset();
11591
11592 // Require that the new offset is larger than the existing one. Otherwise, we
11593 // can end up oscillating between two possible DAGs, for example,
11594 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11595 if (Offset <= uint64_t(GN->getOffset()))
11596 return SDValue();
11597
11598 // Check whether folding this offset is legal. It must not go out of bounds of
11599 // the referenced object to avoid violating the code model, and must be
11600 // smaller than 2^21 because this is the largest offset expressible in all
11601 // object formats.
11602 //
11603 // This check also prevents us from folding negative offsets, which will end
11604 // up being treated in the same way as large positive ones. They could also
11605 // cause code model violations, and aren't really common enough to matter.
11606 if (Offset >= (1 << 21))
11607 return SDValue();
11608
11609 const GlobalValue *GV = GN->getGlobal();
11610 Type *T = GV->getValueType();
11611 if (!T->isSized() ||
11612 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11613 return SDValue();
11614
11615 SDLoc DL(GN);
11616 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11617 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11618 DAG.getConstant(MinOffset, DL, MVT::i64));
11619}
11620
Tim Northover3b0846e2014-05-24 12:50:23 +000011621SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11622 DAGCombinerInfo &DCI) const {
11623 SelectionDAG &DAG = DCI.DAG;
11624 switch (N->getOpcode()) {
11625 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011626 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011627 break;
11628 case ISD::ADD:
11629 case ISD::SUB:
11630 return performAddSubLongCombine(N, DCI, DAG);
11631 case ISD::XOR:
11632 return performXorCombine(N, DAG, DCI, Subtarget);
11633 case ISD::MUL:
11634 return performMulCombine(N, DAG, DCI, Subtarget);
11635 case ISD::SINT_TO_FP:
11636 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011637 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011638 case ISD::FP_TO_SINT:
11639 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011640 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011641 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011642 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011643 case ISD::OR:
11644 return performORCombine(N, DCI, Subtarget);
Nikita Popov1a261442019-03-15 21:04:34 +000011645 case ISD::AND:
11646 return performANDCombine(N, DCI);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011647 case ISD::SRL:
11648 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011649 case ISD::INTRINSIC_WO_CHAIN:
11650 return performIntrinsicCombine(N, DCI, Subtarget);
11651 case ISD::ANY_EXTEND:
11652 case ISD::ZERO_EXTEND:
11653 case ISD::SIGN_EXTEND:
11654 return performExtendCombine(N, DCI, DAG);
11655 case ISD::BITCAST:
11656 return performBitcastCombine(N, DCI, DAG);
11657 case ISD::CONCAT_VECTORS:
11658 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011659 case ISD::SELECT:
11660 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011661 case ISD::VSELECT:
11662 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011663 case ISD::LOAD:
11664 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11665 return SDValue(N, 0);
11666 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011667 case ISD::STORE:
11668 return performSTORECombine(N, DCI, DAG, Subtarget);
11669 case AArch64ISD::BRCOND:
11670 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011671 case AArch64ISD::TBNZ:
11672 case AArch64ISD::TBZ:
11673 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011674 case AArch64ISD::CSEL:
11675 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011676 case AArch64ISD::DUP:
11677 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011678 case AArch64ISD::NVCAST:
11679 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011680 case ISD::INSERT_VECTOR_ELT:
11681 return performPostLD1Combine(N, DCI, true);
11682 case ISD::INTRINSIC_VOID:
11683 case ISD::INTRINSIC_W_CHAIN:
11684 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11685 case Intrinsic::aarch64_neon_ld2:
11686 case Intrinsic::aarch64_neon_ld3:
11687 case Intrinsic::aarch64_neon_ld4:
11688 case Intrinsic::aarch64_neon_ld1x2:
11689 case Intrinsic::aarch64_neon_ld1x3:
11690 case Intrinsic::aarch64_neon_ld1x4:
11691 case Intrinsic::aarch64_neon_ld2lane:
11692 case Intrinsic::aarch64_neon_ld3lane:
11693 case Intrinsic::aarch64_neon_ld4lane:
11694 case Intrinsic::aarch64_neon_ld2r:
11695 case Intrinsic::aarch64_neon_ld3r:
11696 case Intrinsic::aarch64_neon_ld4r:
11697 case Intrinsic::aarch64_neon_st2:
11698 case Intrinsic::aarch64_neon_st3:
11699 case Intrinsic::aarch64_neon_st4:
11700 case Intrinsic::aarch64_neon_st1x2:
11701 case Intrinsic::aarch64_neon_st1x3:
11702 case Intrinsic::aarch64_neon_st1x4:
11703 case Intrinsic::aarch64_neon_st2lane:
11704 case Intrinsic::aarch64_neon_st3lane:
11705 case Intrinsic::aarch64_neon_st4lane:
11706 return performNEONPostLDSTCombine(N, DCI, DAG);
11707 default:
11708 break;
11709 }
Reid Klecknereb568942018-11-01 18:02:27 +000011710 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011711 case ISD::GlobalAddress:
11712 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011713 }
11714 return SDValue();
11715}
11716
11717// Check if the return value is used as only a return value, as otherwise
11718// we can't perform a tail-call. In particular, we need to check for
11719// target ISD nodes that are returns and any other "odd" constructs
11720// that the generic analysis code won't necessarily catch.
11721bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11722 SDValue &Chain) const {
11723 if (N->getNumValues() != 1)
11724 return false;
11725 if (!N->hasNUsesOfValue(1, 0))
11726 return false;
11727
11728 SDValue TCChain = Chain;
11729 SDNode *Copy = *N->use_begin();
11730 if (Copy->getOpcode() == ISD::CopyToReg) {
11731 // If the copy has a glue operand, we conservatively assume it isn't safe to
11732 // perform a tail call.
11733 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11734 MVT::Glue)
11735 return false;
11736 TCChain = Copy->getOperand(0);
11737 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11738 return false;
11739
11740 bool HasRet = false;
11741 for (SDNode *Node : Copy->uses()) {
11742 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11743 return false;
11744 HasRet = true;
11745 }
11746
11747 if (!HasRet)
11748 return false;
11749
11750 Chain = TCChain;
11751 return true;
11752}
11753
11754// Return whether the an instruction can potentially be optimized to a tail
11755// call. This will cause the optimizers to attempt to move, or duplicate,
11756// return instructions to help enable tail call optimizations for this
11757// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011758bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011759 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011760}
11761
11762bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11763 SDValue &Offset,
11764 ISD::MemIndexedMode &AM,
11765 bool &IsInc,
11766 SelectionDAG &DAG) const {
11767 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11768 return false;
11769
11770 Base = Op->getOperand(0);
11771 // All of the indexed addressing mode instructions take a signed
11772 // 9 bit immediate offset.
11773 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011774 int64_t RHSC = RHS->getSExtValue();
11775 if (Op->getOpcode() == ISD::SUB)
11776 RHSC = -(uint64_t)RHSC;
11777 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011778 return false;
11779 IsInc = (Op->getOpcode() == ISD::ADD);
11780 Offset = Op->getOperand(1);
11781 return true;
11782 }
11783 return false;
11784}
11785
11786bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11787 SDValue &Offset,
11788 ISD::MemIndexedMode &AM,
11789 SelectionDAG &DAG) const {
11790 EVT VT;
11791 SDValue Ptr;
11792 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11793 VT = LD->getMemoryVT();
11794 Ptr = LD->getBasePtr();
11795 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11796 VT = ST->getMemoryVT();
11797 Ptr = ST->getBasePtr();
11798 } else
11799 return false;
11800
11801 bool IsInc;
11802 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11803 return false;
11804 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11805 return true;
11806}
11807
11808bool AArch64TargetLowering::getPostIndexedAddressParts(
11809 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11810 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11811 EVT VT;
11812 SDValue Ptr;
11813 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11814 VT = LD->getMemoryVT();
11815 Ptr = LD->getBasePtr();
11816 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11817 VT = ST->getMemoryVT();
11818 Ptr = ST->getBasePtr();
11819 } else
11820 return false;
11821
11822 bool IsInc;
11823 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11824 return false;
11825 // Post-indexing updates the base, so it's not a valid transform
11826 // if that's not the same as the load's pointer.
11827 if (Ptr != Base)
11828 return false;
11829 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11830 return true;
11831}
11832
Tim Northoverf8bfe212014-07-18 13:07:05 +000011833static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11834 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011835 SDLoc DL(N);
11836 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011837
11838 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11839 return;
11840
Tim Northoverf8bfe212014-07-18 13:07:05 +000011841 Op = SDValue(
11842 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11843 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011844 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011845 0);
11846 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11847 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11848}
11849
Charlie Turner434d4592015-10-16 15:38:25 +000011850static void ReplaceReductionResults(SDNode *N,
11851 SmallVectorImpl<SDValue> &Results,
11852 SelectionDAG &DAG, unsigned InterOp,
11853 unsigned AcrossOp) {
11854 EVT LoVT, HiVT;
11855 SDValue Lo, Hi;
11856 SDLoc dl(N);
11857 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11858 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11859 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11860 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11861 Results.push_back(SplitVal);
11862}
11863
Tim Northover2f32e7f2016-08-04 19:32:28 +000011864static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11865 SDLoc DL(N);
11866 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11867 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11868 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11869 DAG.getConstant(64, DL, MVT::i64)));
11870 return std::make_pair(Lo, Hi);
11871}
11872
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011873// Create an even/odd pair of X registers holding integer value V.
11874static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11875 SDLoc dl(V.getNode());
11876 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11877 SDValue VHi = DAG.getAnyExtOrTrunc(
11878 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11879 dl, MVT::i64);
11880 if (DAG.getDataLayout().isBigEndian())
11881 std::swap (VLo, VHi);
11882 SDValue RegClass =
11883 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11884 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11885 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11886 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11887 return SDValue(
11888 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11889}
11890
Tim Northovercdf15292016-04-14 17:03:29 +000011891static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011892 SmallVectorImpl<SDValue> &Results,
11893 SelectionDAG &DAG,
11894 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011895 assert(N->getValueType(0) == MVT::i128 &&
11896 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011897
11898 if (Subtarget->hasLSE()) {
11899 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11900 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11901 SDValue Ops[] = {
11902 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11903 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11904 N->getOperand(1), // Ptr
11905 N->getOperand(0), // Chain in
11906 };
11907
Chandler Carruth66654b72018-08-14 23:30:32 +000011908 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011909
11910 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011911 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011912 case AtomicOrdering::Monotonic:
11913 Opcode = AArch64::CASPX;
11914 break;
11915 case AtomicOrdering::Acquire:
11916 Opcode = AArch64::CASPAX;
11917 break;
11918 case AtomicOrdering::Release:
11919 Opcode = AArch64::CASPLX;
11920 break;
11921 case AtomicOrdering::AcquireRelease:
11922 case AtomicOrdering::SequentiallyConsistent:
11923 Opcode = AArch64::CASPALX;
11924 break;
11925 default:
11926 llvm_unreachable("Unexpected ordering!");
11927 }
11928
11929 MachineSDNode *CmpSwap = DAG.getMachineNode(
11930 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011931 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011932
11933 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11934 if (DAG.getDataLayout().isBigEndian())
11935 std::swap(SubReg1, SubReg2);
11936 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11937 SDValue(CmpSwap, 0)));
11938 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11939 SDValue(CmpSwap, 0)));
11940 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11941 return;
11942 }
11943
Tim Northover2f32e7f2016-08-04 19:32:28 +000011944 auto Desired = splitInt128(N->getOperand(2), DAG);
11945 auto New = splitInt128(N->getOperand(3), DAG);
11946 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11947 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011948 SDNode *CmpSwap = DAG.getMachineNode(
11949 AArch64::CMP_SWAP_128, SDLoc(N),
11950 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11951
Chandler Carruth66654b72018-08-14 23:30:32 +000011952 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11953 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011954
11955 Results.push_back(SDValue(CmpSwap, 0));
11956 Results.push_back(SDValue(CmpSwap, 1));
11957 Results.push_back(SDValue(CmpSwap, 3));
11958}
11959
Tim Northover3b0846e2014-05-24 12:50:23 +000011960void AArch64TargetLowering::ReplaceNodeResults(
11961 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11962 switch (N->getOpcode()) {
11963 default:
11964 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011965 case ISD::BITCAST:
11966 ReplaceBITCASTResults(N, Results, DAG);
11967 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011968 case ISD::VECREDUCE_ADD:
11969 case ISD::VECREDUCE_SMAX:
11970 case ISD::VECREDUCE_SMIN:
11971 case ISD::VECREDUCE_UMAX:
11972 case ISD::VECREDUCE_UMIN:
11973 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11974 return;
11975
Charlie Turner434d4592015-10-16 15:38:25 +000011976 case AArch64ISD::SADDV:
11977 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11978 return;
11979 case AArch64ISD::UADDV:
11980 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11981 return;
11982 case AArch64ISD::SMINV:
11983 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11984 return;
11985 case AArch64ISD::UMINV:
11986 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11987 return;
11988 case AArch64ISD::SMAXV:
11989 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11990 return;
11991 case AArch64ISD::UMAXV:
11992 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11993 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011994 case ISD::FP_TO_UINT:
11995 case ISD::FP_TO_SINT:
11996 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11997 // Let normal code take care of it by not adding anything to Results.
11998 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011999 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000012000 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000012001 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000012002 }
12003}
12004
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000012005bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000012006 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
12007 return TargetLowering::useLoadStackGuardNode();
12008 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000012009}
12010
Sanjay Patel1dd15592015-07-28 23:05:48 +000012011unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000012012 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12013 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000012014 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000012015}
12016
Chandler Carruth9d010ff2014-07-03 00:23:43 +000012017TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000012018AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000012019 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
12020 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000012021 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
12022 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000012023 return TypeWidenVector;
12024
12025 return TargetLoweringBase::getPreferredVectorAction(VT);
12026}
12027
Robin Morisseted3d48f2014-09-03 21:29:59 +000012028// Loads and stores less than 128-bits are already atomic; ones above that
12029// are doomed anyway, so defer to the default libcall and blame the OS when
12030// things go wrong.
12031bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12032 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12033 return Size == 128;
12034}
12035
12036// Loads and stores less than 128-bits are already atomic; ones above that
12037// are doomed anyway, so defer to the default libcall and blame the OS when
12038// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000012039TargetLowering::AtomicExpansionKind
12040AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000012041 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000012042 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000012043}
12044
12045// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000012046TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000012047AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000012048 if (AI->isFloatingPointOperation())
12049 return AtomicExpansionKind::CmpXChg;
12050
Robin Morisseted3d48f2014-09-03 21:29:59 +000012051 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000012052 if (Size > 128) return AtomicExpansionKind::None;
12053 // Nand not supported in LSE.
12054 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000012055 // Leave 128 bits to LLSC.
12056 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000012057}
12058
Alex Bradbury79518b02018-09-19 14:51:42 +000012059TargetLowering::AtomicExpansionKind
12060AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000012061 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000012062 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000012063 if (Subtarget->hasLSE())
12064 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000012065 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
12066 // implement cmpxchg without spilling. If the address being exchanged is also
12067 // on the stack and close enough to the spill slot, this can lead to a
12068 // situation where the monitor always gets cleared and the atomic operation
12069 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000012070 if (getTargetMachine().getOptLevel() == 0)
12071 return AtomicExpansionKind::None;
12072 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000012073}
12074
Tim Northover3b0846e2014-05-24 12:50:23 +000012075Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12076 AtomicOrdering Ord) const {
12077 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12078 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000012079 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000012080
12081 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
12082 // intrinsic must return {i64, i64} and we have to recombine them into a
12083 // single i128 here.
12084 if (ValTy->getPrimitiveSizeInBits() == 128) {
12085 Intrinsic::ID Int =
12086 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000012087 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000012088
12089 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12090 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
12091
12092 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12093 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12094 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12095 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12096 return Builder.CreateOr(
12097 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
12098 }
12099
12100 Type *Tys[] = { Addr->getType() };
12101 Intrinsic::ID Int =
12102 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000012103 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000012104
Matt Arsenault0cb08e42019-01-17 10:49:01 +000012105 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
12106
12107 const DataLayout &DL = M->getDataLayout();
12108 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
12109 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
12110
12111 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000012112}
12113
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000012114void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12115 IRBuilder<> &Builder) const {
12116 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000012117 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000012118}
12119
Tim Northover3b0846e2014-05-24 12:50:23 +000012120Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
12121 Value *Val, Value *Addr,
12122 AtomicOrdering Ord) const {
12123 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000012124 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000012125
12126 // Since the intrinsics must have legal type, the i128 intrinsics take two
12127 // parameters: "i64, i64". We must marshal Val into the appropriate form
12128 // before the call.
12129 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
12130 Intrinsic::ID Int =
12131 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
12132 Function *Stxr = Intrinsic::getDeclaration(M, Int);
12133 Type *Int64Ty = Type::getInt64Ty(M->getContext());
12134
12135 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
12136 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
12137 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000012138 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000012139 }
12140
12141 Intrinsic::ID Int =
12142 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
12143 Type *Tys[] = { Addr->getType() };
12144 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
12145
Matt Arsenault0cb08e42019-01-17 10:49:01 +000012146 const DataLayout &DL = M->getDataLayout();
12147 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
12148 Val = Builder.CreateBitCast(Val, IntValTy);
12149
David Blaikieff6409d2015-05-18 22:13:54 +000012150 return Builder.CreateCall(Stxr,
12151 {Builder.CreateZExtOrBitCast(
12152 Val, Stxr->getFunctionType()->getParamType(0)),
12153 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000012154}
Tim Northover3c55cca2014-11-27 21:02:42 +000012155
12156bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
12157 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12158 return Ty->isArrayTy();
12159}
Matthias Braunaf7d7702015-07-16 20:02:37 +000012160
12161bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
12162 EVT) const {
12163 return false;
12164}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012165
Petr Hoseka7d59162017-02-24 03:10:10 +000012166static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000012167 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
12168 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000012169 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000012170 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000012171 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
12172 Offset),
12173 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000012174}
12175
Petr Hoseka7d59162017-02-24 03:10:10 +000012176Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
12177 // Android provides a fixed TLS slot for the stack cookie. See the definition
12178 // of TLS_SLOT_STACK_GUARD in
12179 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12180 if (Subtarget->isTargetAndroid())
12181 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012182
Petr Hoseka7d59162017-02-24 03:10:10 +000012183 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000012184 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000012185 if (Subtarget->isTargetFuchsia())
12186 return UseTlsOffset(IRB, -0x10);
12187
12188 return TargetLowering::getIRStackGuard(IRB);
12189}
12190
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012191void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
12192 // MSVC CRT provides functionalities for stack protection.
12193 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
12194 // MSVC CRT has a global variable holding security cookie.
12195 M.getOrInsertGlobal("__security_cookie",
12196 Type::getInt8PtrTy(M.getContext()));
12197
12198 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000012199 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
12200 "__security_check_cookie", Type::getVoidTy(M.getContext()),
12201 Type::getInt8PtrTy(M.getContext()));
12202 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
12203 F->setCallingConv(CallingConv::Win64);
12204 F->addAttribute(1, Attribute::AttrKind::InReg);
12205 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012206 return;
12207 }
12208 TargetLowering::insertSSPDeclarations(M);
12209}
12210
12211Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12212 // MSVC CRT has a global variable holding security cookie.
12213 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12214 return M.getGlobalVariable("__security_cookie");
12215 return TargetLowering::getSDagStackGuard(M);
12216}
12217
James Y Knight7976eb52019-02-01 20:43:25 +000012218Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000012219 // MSVC CRT has a function to validate security cookie.
12220 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12221 return M.getFunction("__security_check_cookie");
12222 return TargetLowering::getSSPStackGuardCheck(M);
12223}
12224
Petr Hoseka7d59162017-02-24 03:10:10 +000012225Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012226 // Android provides a fixed TLS slot for the SafeStack pointer. See the
12227 // definition of TLS_SLOT_SAFESTACK in
12228 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000012229 if (Subtarget->isTargetAndroid())
12230 return UseTlsOffset(IRB, 0x48);
12231
12232 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000012233 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000012234 if (Subtarget->isTargetFuchsia())
12235 return UseTlsOffset(IRB, -0x8);
12236
12237 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000012238}
Manman Rencbe4f942015-12-16 21:04:19 +000012239
Geoff Berry5d534b62017-02-21 18:53:14 +000012240bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12241 const Instruction &AndI) const {
12242 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12243 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
12244 // may be beneficial to sink in other cases, but we would have to check that
12245 // the cmp would not get folded into the br to form a cbz for these to be
12246 // beneficial.
12247 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12248 if (!Mask)
12249 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000012250 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000012251}
12252
Roman Lebedev017e2722019-07-24 22:57:22 +000012253bool AArch64TargetLowering::
12254 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12255 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
12256 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
12257 SelectionDAG &DAG) const {
12258 // Does baseline recommend not to perform the fold by default?
12259 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12260 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
12261 return false;
12262 // Else, if this is a vector shift, prefer 'shl'.
12263 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
12264}
12265
Hans Wennborgcff90f02019-08-28 13:55:10 +000012266bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
12267 SDNode *N) const {
12268 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
12269 !Subtarget->isTargetWindows())
12270 return false;
12271 return true;
12272}
12273
Manman Rencbe4f942015-12-16 21:04:19 +000012274void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12275 // Update IsSplitCSR in AArch64unctionInfo.
12276 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12277 AFI->setIsSplitCSR(true);
12278}
12279
12280void AArch64TargetLowering::insertCopiesSplitCSR(
12281 MachineBasicBlock *Entry,
12282 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12283 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12284 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12285 if (!IStart)
12286 return;
12287
12288 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12289 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000012290 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000012291 for (const MCPhysReg *I = IStart; *I; ++I) {
12292 const TargetRegisterClass *RC = nullptr;
12293 if (AArch64::GPR64RegClass.contains(*I))
12294 RC = &AArch64::GPR64RegClass;
12295 else if (AArch64::FPR64RegClass.contains(*I))
12296 RC = &AArch64::FPR64RegClass;
12297 else
12298 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12299
Daniel Sanders5ae66e52019-08-12 22:40:53 +000012300 Register NewVR = MRI->createVirtualRegister(RC);
Manman Rencbe4f942015-12-16 21:04:19 +000012301 // Create copy from CSR to a virtual register.
12302 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12303 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12304 // nounwind. If we want to generalize this later, we may need to emit
12305 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000012306 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000012307 Attribute::NoUnwind) &&
12308 "Function should be nounwind in insertCopiesSplitCSR!");
12309 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000012310 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000012311 .addReg(*I);
12312
Manman Ren4632e8e2016-01-15 20:13:28 +000012313 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000012314 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000012315 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12316 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000012317 .addReg(NewVR);
12318 }
12319}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012320
Reid Klecknerb5180542017-03-21 16:57:19 +000012321bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012322 // Integer division on AArch64 is expensive. However, when aggressively
12323 // optimizing for code size, we prefer to use a div instruction, as it is
12324 // usually smaller than the alternative sequence.
12325 // The exception to this is vector division. Since AArch64 doesn't have vector
12326 // integer division, leaving the division as-is is a loss even in terms of
12327 // size, because it will have to be scalarized, while the alternative code
12328 // sequence can be performed in vector form.
12329 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000012330 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000012331 return OptSize && !VT.isVector();
12332}
Tim Northoverf19d4672017-02-08 17:57:20 +000012333
Roman Lebedevc4b83a62019-07-03 09:41:35 +000012334bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12335 // We want inc-of-add for scalars and sub-of-not for vectors.
12336 return VT.isScalarInteger();
12337}
12338
Joel Jones07150922018-01-25 21:55:39 +000012339bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12340 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12341}
12342
Tim Northoverf19d4672017-02-08 17:57:20 +000012343unsigned
12344AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000012345 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000012346 return getPointerTy(DL).getSizeInBits();
12347
12348 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12349}
Matthias Braun5c290dc2018-01-19 03:16:36 +000012350
12351void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12352 MF.getFrameInfo().computeMaxCallFrameSize(MF);
12353 TargetLoweringBase::finalizeLowering(MF);
12354}
Eli Friedmanad1151c2018-11-09 23:33:30 +000012355
12356// Unlike X86, we let frame lowering assign offsets to all catch objects.
12357bool AArch64TargetLowering::needsFixedCatchObjects() const {
12358 return false;
12359}