blob: 56c562ab3899005dad0a95eb1235dff00d657100 [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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000013#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000014#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000015#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000016#include "AArch64PerfectShuffle.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000017#include "AArch64RegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000018#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "MCTargetDesc/AArch64AddressingModes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000020#include "Utils/AArch64BaseInfo.h"
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/ArrayRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/ADT/STLExtras.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000025#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000026#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000027#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/StringSwitch.h"
29#include "llvm/ADT/Triple.h"
30#include "llvm/ADT/Twine.h"
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +000031#include "llvm/Analysis/VectorUtils.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000032#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000033#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000034#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000035#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000037#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000038#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000039#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000040#include "llvm/CodeGen/RuntimeLibcalls.h"
41#include "llvm/CodeGen/SelectionDAG.h"
42#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000043#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000044#include "llvm/CodeGen/TargetInstrInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000045#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000046#include "llvm/IR/Attributes.h"
47#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000051#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000052#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000053#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000054#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000055#include "llvm/IR/Instruction.h"
56#include "llvm/IR/Instructions.h"
Florian Hahn3b251962019-02-05 10:27:40 +000057#include "llvm/IR/IntrinsicInst.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000058#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000059#include "llvm/IR/Module.h"
60#include "llvm/IR/OperandTraits.h"
Florian Hahn3b251962019-02-05 10:27:40 +000061#include "llvm/IR/PatternMatch.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000062#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000063#include "llvm/IR/Use.h"
64#include "llvm/IR/Value.h"
65#include "llvm/MC/MCRegisterInfo.h"
66#include "llvm/Support/Casting.h"
67#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000068#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000069#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000070#include "llvm/Support/Debug.h"
71#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000072#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000073#include "llvm/Support/MachineValueType.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000074#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000075#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000076#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000077#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000078#include <algorithm>
79#include <bitset>
80#include <cassert>
81#include <cctype>
82#include <cstdint>
83#include <cstdlib>
84#include <iterator>
85#include <limits>
86#include <tuple>
87#include <utility>
88#include <vector>
89
Tim Northover3b0846e2014-05-24 12:50:23 +000090using namespace llvm;
Florian Hahn3b251962019-02-05 10:27:40 +000091using namespace llvm::PatternMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +000092
93#define DEBUG_TYPE "aarch64-lower"
94
95STATISTIC(NumTailCalls, "Number of tail calls");
96STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000097STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +000098
Tim Northover3b0846e2014-05-24 12:50:23 +000099static cl::opt<bool>
100EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +0000101 cl::desc("Allow AArch64 SLI/SRI formation"),
102 cl::init(false));
103
104// FIXME: The necessary dtprel relocations don't seem to be supported
105// well in the GNU bfd and gold linkers at the moment. Therefore, by
106// default, for now, fall back to GeneralDynamic code generation.
107cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
108 "aarch64-elf-ldtls-generation", cl::Hidden,
109 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
110 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000111
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000112static cl::opt<bool>
113EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
114 cl::desc("Enable AArch64 logical imm instruction "
115 "optimization"),
116 cl::init(true));
117
Matthias Braunaf7d7702015-07-16 20:02:37 +0000118/// Value type used for condition codes.
119static const MVT MVT_CC = MVT::i32;
120
Eric Christopher905f12d2015-01-29 00:19:42 +0000121AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
122 const AArch64Subtarget &STI)
123 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000124 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
125 // we have to make something up. Arbitrarily, choose ZeroOrOne.
126 setBooleanContents(ZeroOrOneBooleanContent);
127 // When comparing vectors the result sets the different elements in the
128 // vector to all-one or all-zero.
129 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
130
131 // Set up the register classes.
132 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
133 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
134
135 if (Subtarget->hasFPARMv8()) {
136 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
137 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
138 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
139 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
140 }
141
142 if (Subtarget->hasNEON()) {
143 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
144 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
145 // Someone set us up the NEON.
146 addDRTypeForNEON(MVT::v2f32);
147 addDRTypeForNEON(MVT::v8i8);
148 addDRTypeForNEON(MVT::v4i16);
149 addDRTypeForNEON(MVT::v2i32);
150 addDRTypeForNEON(MVT::v1i64);
151 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000152 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000153
154 addQRTypeForNEON(MVT::v4f32);
155 addQRTypeForNEON(MVT::v2f64);
156 addQRTypeForNEON(MVT::v16i8);
157 addQRTypeForNEON(MVT::v8i16);
158 addQRTypeForNEON(MVT::v4i32);
159 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000160 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000161 }
162
163 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000164 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000165
166 // Provide all sorts of operation actions
167 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
168 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
169 setOperationAction(ISD::SETCC, MVT::i32, Custom);
170 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000171 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 setOperationAction(ISD::SETCC, MVT::f32, Custom);
173 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000174 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
175 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000176 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
177 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
178 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000179 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000180 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
181 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
182 setOperationAction(ISD::SELECT, MVT::i32, Custom);
183 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000184 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000185 setOperationAction(ISD::SELECT, MVT::f32, Custom);
186 setOperationAction(ISD::SELECT, MVT::f64, Custom);
187 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
188 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000189 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
191 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
Tim Northover1c353412018-10-24 20:19:09 +0000192 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
194
195 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
196 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
197 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
198
199 setOperationAction(ISD::FREM, MVT::f32, Expand);
200 setOperationAction(ISD::FREM, MVT::f64, Expand);
201 setOperationAction(ISD::FREM, MVT::f80, Expand);
202
Amara Emersone27d5012018-04-10 19:01:58 +0000203 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
204
Tim Northover3b0846e2014-05-24 12:50:23 +0000205 // Custom lowering hooks are needed for XOR
206 // to fold it into CSINC/CSINV.
207 setOperationAction(ISD::XOR, MVT::i32, Custom);
208 setOperationAction(ISD::XOR, MVT::i64, Custom);
209
210 // Virtually no operation on f128 is legal, but LLVM can't expand them when
211 // there's a valid register class, so we need custom operations in most cases.
212 setOperationAction(ISD::FABS, MVT::f128, Expand);
213 setOperationAction(ISD::FADD, MVT::f128, Custom);
214 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
215 setOperationAction(ISD::FCOS, MVT::f128, Expand);
216 setOperationAction(ISD::FDIV, MVT::f128, Custom);
217 setOperationAction(ISD::FMA, MVT::f128, Expand);
218 setOperationAction(ISD::FMUL, MVT::f128, Custom);
219 setOperationAction(ISD::FNEG, MVT::f128, Expand);
220 setOperationAction(ISD::FPOW, MVT::f128, Expand);
221 setOperationAction(ISD::FREM, MVT::f128, Expand);
222 setOperationAction(ISD::FRINT, MVT::f128, Expand);
223 setOperationAction(ISD::FSIN, MVT::f128, Expand);
224 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
225 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
226 setOperationAction(ISD::FSUB, MVT::f128, Custom);
227 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
228 setOperationAction(ISD::SETCC, MVT::f128, Custom);
229 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
230 setOperationAction(ISD::SELECT, MVT::f128, Custom);
231 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
232 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
233
234 // Lowering for many of the conversions is actually specified by the non-f128
235 // type. The LowerXXX function will be trivial when f128 isn't involved.
236 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
237 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
238 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
239 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
240 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
241 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
242 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
243 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
244 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
245 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
246 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
247 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
248 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
249 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
250
251 // Variable arguments.
252 setOperationAction(ISD::VASTART, MVT::Other, Custom);
253 setOperationAction(ISD::VAARG, MVT::Other, Custom);
254 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
255 setOperationAction(ISD::VAEND, MVT::Other, Expand);
256
257 // Variable-sized objects.
258 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
259 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000260
261 if (Subtarget->isTargetWindows())
262 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
263 else
264 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000265
Tim Northover3b0846e2014-05-24 12:50:23 +0000266 // Constant pool entries
267 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
268
269 // BlockAddress
270 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
271
272 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
273 setOperationAction(ISD::ADDC, MVT::i32, Custom);
274 setOperationAction(ISD::ADDE, MVT::i32, Custom);
275 setOperationAction(ISD::SUBC, MVT::i32, Custom);
276 setOperationAction(ISD::SUBE, MVT::i32, Custom);
277 setOperationAction(ISD::ADDC, MVT::i64, Custom);
278 setOperationAction(ISD::ADDE, MVT::i64, Custom);
279 setOperationAction(ISD::SUBC, MVT::i64, Custom);
280 setOperationAction(ISD::SUBE, MVT::i64, Custom);
281
282 // AArch64 lacks both left-rotate and popcount instructions.
283 setOperationAction(ISD::ROTL, MVT::i32, Expand);
284 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000285 for (MVT VT : MVT::vector_valuetypes()) {
286 setOperationAction(ISD::ROTL, VT, Expand);
287 setOperationAction(ISD::ROTR, VT, Expand);
288 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000289
290 // AArch64 doesn't have {U|S}MUL_LOHI.
291 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
292 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
293
Tim Northover3b0846e2014-05-24 12:50:23 +0000294 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
295 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
296
297 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
298 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000299 for (MVT VT : MVT::vector_valuetypes()) {
300 setOperationAction(ISD::SDIVREM, VT, Expand);
301 setOperationAction(ISD::UDIVREM, VT, Expand);
302 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000303 setOperationAction(ISD::SREM, MVT::i32, Expand);
304 setOperationAction(ISD::SREM, MVT::i64, Expand);
305 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
306 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
307 setOperationAction(ISD::UREM, MVT::i32, Expand);
308 setOperationAction(ISD::UREM, MVT::i64, Expand);
309
310 // Custom lower Add/Sub/Mul with overflow.
311 setOperationAction(ISD::SADDO, MVT::i32, Custom);
312 setOperationAction(ISD::SADDO, MVT::i64, Custom);
313 setOperationAction(ISD::UADDO, MVT::i32, Custom);
314 setOperationAction(ISD::UADDO, MVT::i64, Custom);
315 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
316 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
317 setOperationAction(ISD::USUBO, MVT::i32, Custom);
318 setOperationAction(ISD::USUBO, MVT::i64, Custom);
319 setOperationAction(ISD::SMULO, MVT::i32, Custom);
320 setOperationAction(ISD::SMULO, MVT::i64, Custom);
321 setOperationAction(ISD::UMULO, MVT::i32, Custom);
322 setOperationAction(ISD::UMULO, MVT::i64, Custom);
323
324 setOperationAction(ISD::FSIN, MVT::f32, Expand);
325 setOperationAction(ISD::FSIN, MVT::f64, Expand);
326 setOperationAction(ISD::FCOS, MVT::f32, Expand);
327 setOperationAction(ISD::FCOS, MVT::f64, Expand);
328 setOperationAction(ISD::FPOW, MVT::f32, Expand);
329 setOperationAction(ISD::FPOW, MVT::f64, Expand);
330 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
331 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000332 if (Subtarget->hasFullFP16())
333 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
334 else
335 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000336
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000337 setOperationAction(ISD::FREM, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000338 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
339 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000340 setOperationAction(ISD::FPOW, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000341 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
342 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000343 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000344 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
345 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000346 setOperationAction(ISD::FCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000347 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
348 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000349 setOperationAction(ISD::FSIN, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000350 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
351 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000352 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000353 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
354 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000355 setOperationAction(ISD::FEXP, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000356 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
357 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000358 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000359 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
360 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000361 setOperationAction(ISD::FLOG, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000362 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
363 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000364 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000365 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
366 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000367 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
Bryan Chan7ce57752019-01-10 15:02:37 +0000368 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
369 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000370
371 if (!Subtarget->hasFullFP16()) {
372 setOperationAction(ISD::SELECT, MVT::f16, Promote);
373 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
374 setOperationAction(ISD::SETCC, MVT::f16, Promote);
375 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
376 setOperationAction(ISD::FADD, MVT::f16, Promote);
377 setOperationAction(ISD::FSUB, MVT::f16, Promote);
378 setOperationAction(ISD::FMUL, MVT::f16, Promote);
379 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000380 setOperationAction(ISD::FMA, MVT::f16, Promote);
381 setOperationAction(ISD::FNEG, MVT::f16, Promote);
382 setOperationAction(ISD::FABS, MVT::f16, Promote);
383 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
384 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000385 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
386 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
387 setOperationAction(ISD::FRINT, MVT::f16, Promote);
388 setOperationAction(ISD::FROUND, MVT::f16, Promote);
389 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
390 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
391 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Thomas Lively30f1d692018-10-24 22:49:55 +0000392 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
393 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000394
395 // promote v4f16 to v4f32 when that is known to be safe.
396 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
397 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
398 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
399 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
400 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
401 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
402 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
403 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
404 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
405 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
406 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
407 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
408
409 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
410 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
411 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
412 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
413 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
414 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
415 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
416 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
417 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
418 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
419 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
420 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
421 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
422 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
423 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000424
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000425 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
426 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
427 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
428 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
429 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
430 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
431 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
432 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
433 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
434 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
435 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
436 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
437 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
438 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
439 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
440 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
441 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
442 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
443 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
444 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
445 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000446
Tim Northover3b0846e2014-05-24 12:50:23 +0000447 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000448 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 setOperationAction(ISD::FFLOOR, Ty, Legal);
450 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
451 setOperationAction(ISD::FCEIL, Ty, Legal);
452 setOperationAction(ISD::FRINT, Ty, Legal);
453 setOperationAction(ISD::FTRUNC, Ty, Legal);
454 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000455 setOperationAction(ISD::FMINNUM, Ty, Legal);
456 setOperationAction(ISD::FMAXNUM, Ty, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000457 setOperationAction(ISD::FMINIMUM, Ty, Legal);
458 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000459 }
460
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000461 if (Subtarget->hasFullFP16()) {
462 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
463 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
464 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
465 setOperationAction(ISD::FRINT, MVT::f16, Legal);
466 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
467 setOperationAction(ISD::FROUND, MVT::f16, Legal);
468 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
469 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000470 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
471 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000472 }
473
Tim Northover3b0846e2014-05-24 12:50:23 +0000474 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
475
Tim Northover70666e72018-06-20 12:09:01 +0000476 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
477
Tim Northovercdf15292016-04-14 17:03:29 +0000478 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000479 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
480 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000481 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
482 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000483
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000484 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
485 // This requires the Performance Monitors extension.
486 if (Subtarget->hasPerfMon())
487 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
488
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000489 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
490 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
491 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000492 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
493 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
494 } else {
495 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
496 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
497 }
498
Juergen Ributzka23266502014-12-10 19:43:32 +0000499 // Make floating-point constants legal for the large code model, so they don't
500 // become loads from the constant pool.
501 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
502 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
503 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
504 }
505
Tim Northover3b0846e2014-05-24 12:50:23 +0000506 // AArch64 does not have floating-point extending loads, i1 sign-extending
507 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000508 for (MVT VT : MVT::fp_valuetypes()) {
509 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
510 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
511 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
512 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
513 }
514 for (MVT VT : MVT::integer_valuetypes())
515 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
516
Tim Northover3b0846e2014-05-24 12:50:23 +0000517 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
518 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
519 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
520 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
521 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
522 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
523 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000524
525 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
526 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
527
Tim Northover3b0846e2014-05-24 12:50:23 +0000528 // Indexed loads and stores are supported.
529 for (unsigned im = (unsigned)ISD::PRE_INC;
530 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
531 setIndexedLoadAction(im, MVT::i8, Legal);
532 setIndexedLoadAction(im, MVT::i16, Legal);
533 setIndexedLoadAction(im, MVT::i32, Legal);
534 setIndexedLoadAction(im, MVT::i64, Legal);
535 setIndexedLoadAction(im, MVT::f64, Legal);
536 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000537 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000538 setIndexedStoreAction(im, MVT::i8, Legal);
539 setIndexedStoreAction(im, MVT::i16, Legal);
540 setIndexedStoreAction(im, MVT::i32, Legal);
541 setIndexedStoreAction(im, MVT::i64, Legal);
542 setIndexedStoreAction(im, MVT::f64, Legal);
543 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000544 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000545 }
546
547 // Trap.
548 setOperationAction(ISD::TRAP, MVT::Other, Legal);
549
550 // We combine OR nodes for bitfield operations.
551 setTargetDAGCombine(ISD::OR);
552
553 // Vector add and sub nodes may conceal a high-half opportunity.
554 // Also, try to fold ADD into CSINC/CSINV..
555 setTargetDAGCombine(ISD::ADD);
556 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000557 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000558 setTargetDAGCombine(ISD::XOR);
559 setTargetDAGCombine(ISD::SINT_TO_FP);
560 setTargetDAGCombine(ISD::UINT_TO_FP);
561
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000562 setTargetDAGCombine(ISD::FP_TO_SINT);
563 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000564 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000565
Tim Northover3b0846e2014-05-24 12:50:23 +0000566 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
567
568 setTargetDAGCombine(ISD::ANY_EXTEND);
569 setTargetDAGCombine(ISD::ZERO_EXTEND);
570 setTargetDAGCombine(ISD::SIGN_EXTEND);
571 setTargetDAGCombine(ISD::BITCAST);
572 setTargetDAGCombine(ISD::CONCAT_VECTORS);
573 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000574 if (Subtarget->supportsAddressTopByteIgnored())
575 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000576
577 setTargetDAGCombine(ISD::MUL);
578
579 setTargetDAGCombine(ISD::SELECT);
580 setTargetDAGCombine(ISD::VSELECT);
581
582 setTargetDAGCombine(ISD::INTRINSIC_VOID);
583 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
584 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
585
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000586 setTargetDAGCombine(ISD::GlobalAddress);
587
Evandro Menezesf8425342018-05-29 15:58:50 +0000588 // In case of strict alignment, avoid an excessive number of byte wide stores.
589 MaxStoresPerMemsetOptSize = 8;
590 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
591 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000592
Evandro Menezesf8425342018-05-29 15:58:50 +0000593 MaxGluedStoresPerMemcpy = 4;
594 MaxStoresPerMemcpyOptSize = 4;
595 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
596 ? MaxStoresPerMemcpyOptSize : 16;
597
598 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000599
600 setStackPointerRegisterToSaveRestore(AArch64::SP);
601
602 setSchedulingPreference(Sched::Hybrid);
603
Quentin Colombet6843ac42015-03-31 20:52:32 +0000604 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000605
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000606 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000607 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000608 // Set preferred alignments.
609 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
610 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000611
Evandro Menezese45de8a2016-09-26 15:32:33 +0000612 // Only change the limit for entries in a jump table if specified by
613 // the subtarget, but not at the command line.
614 unsigned MaxJT = STI.getMaximumJumpTableSize();
615 if (MaxJT && getMaximumJumpTableSize() == 0)
616 setMaximumJumpTableSize(MaxJT);
617
Tim Northover3b0846e2014-05-24 12:50:23 +0000618 setHasExtractBitsInsn(true);
619
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000620 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
621
Tim Northover3b0846e2014-05-24 12:50:23 +0000622 if (Subtarget->hasNEON()) {
623 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
624 // silliness like this:
625 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
626 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
627 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
628 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
629 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
630 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
631 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
632 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
633 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
634 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
635 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
636 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
637 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
638 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
639 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
640 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
641 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
642 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
643 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
644 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
645 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
646 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
647 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
648 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
649 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
650
651 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
652 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
653 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
654 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
655 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
656
657 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
658
659 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
660 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000661 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
662 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000663 // i8 vector elements also need promotion to i32 for v8i8
Craig Toppera4f99972018-01-01 19:21:35 +0000664 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
665 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000666 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
667 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
668 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
669 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
670 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000671 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
672 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
673 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
674 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000675
Abderrazek Zaafraniabfd1082019-02-28 20:21:46 +0000676 if (Subtarget->hasFullFP16()) {
677 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
678 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
679 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
680 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
681 } else {
682 // when AArch64 doesn't have fullfp16 support, promote the input
683 // to i32 first.
684 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
685 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
686 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
687 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
688 }
689
Craig Topperc5551bf2016-04-26 05:26:51 +0000690 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
691 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
692
Tim Northover3b0846e2014-05-24 12:50:23 +0000693 // AArch64 doesn't have MUL.2d:
694 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000695 // Custom handling for some quad-vector types to detect MULL.
696 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
697 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
698 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
699
Amara Emersonc9916d72017-05-16 21:29:22 +0000700 // Vector reductions
701 for (MVT VT : MVT::integer_valuetypes()) {
702 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
703 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
704 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
705 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
706 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
707 }
708 for (MVT VT : MVT::fp_valuetypes()) {
709 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
710 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
711 }
712
Tim Northover3b0846e2014-05-24 12:50:23 +0000713 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
714 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
715 // Likewise, narrowing and extending vector loads/stores aren't handled
716 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000717 for (MVT VT : MVT::vector_valuetypes()) {
718 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000719
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000720 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
Craig Topper129d5292018-11-29 19:36:17 +0000721 setOperationAction(ISD::MULHS, VT, Legal);
722 setOperationAction(ISD::MULHU, VT, Legal);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000723 } else {
724 setOperationAction(ISD::MULHS, VT, Expand);
725 setOperationAction(ISD::MULHU, VT, Expand);
726 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000727 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000728 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000729
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000730 setOperationAction(ISD::BSWAP, VT, Expand);
Nikita Popova3be17e2019-02-12 18:55:53 +0000731 setOperationAction(ISD::CTTZ, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000732
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000733 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000734 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000735 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
736 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
737 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
738 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000739 }
740
741 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000742 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000743 setOperationAction(ISD::FFLOOR, Ty, Legal);
744 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
745 setOperationAction(ISD::FCEIL, Ty, Legal);
746 setOperationAction(ISD::FRINT, Ty, Legal);
747 setOperationAction(ISD::FTRUNC, Ty, Legal);
748 setOperationAction(ISD::FROUND, Ty, Legal);
749 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000750
751 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000752 }
James Molloyf089ab72014-08-06 10:42:18 +0000753
Matthias Braun651cff42016-06-02 18:03:53 +0000754 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000755}
756
Craig Topper18e69f42016-04-15 06:20:21 +0000757void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000758 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000759
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000760 if (VT.isFloatingPoint()) {
761 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
762 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
763 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000764 }
765
766 // Mark vector float intrinsics as expand.
767 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000768 setOperationAction(ISD::FSIN, VT, Expand);
769 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000770 setOperationAction(ISD::FPOW, VT, Expand);
771 setOperationAction(ISD::FLOG, VT, Expand);
772 setOperationAction(ISD::FLOG2, VT, Expand);
773 setOperationAction(ISD::FLOG10, VT, Expand);
774 setOperationAction(ISD::FEXP, VT, Expand);
775 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000776
777 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000778 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000779 }
780
Craig Topper18e69f42016-04-15 06:20:21 +0000781 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
782 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
783 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
784 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
785 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
786 setOperationAction(ISD::SRA, VT, Custom);
787 setOperationAction(ISD::SRL, VT, Custom);
788 setOperationAction(ISD::SHL, VT, Custom);
789 setOperationAction(ISD::AND, VT, Custom);
790 setOperationAction(ISD::OR, VT, Custom);
791 setOperationAction(ISD::SETCC, VT, Custom);
792 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000793
Craig Topper18e69f42016-04-15 06:20:21 +0000794 setOperationAction(ISD::SELECT, VT, Expand);
795 setOperationAction(ISD::SELECT_CC, VT, Expand);
796 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000797 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000798 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000799
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000800 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000801 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000802 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000803
Craig Topper18e69f42016-04-15 06:20:21 +0000804 setOperationAction(ISD::UDIV, VT, Expand);
805 setOperationAction(ISD::SDIV, VT, Expand);
806 setOperationAction(ISD::UREM, VT, Expand);
807 setOperationAction(ISD::SREM, VT, Expand);
808 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000809
Craig Topper18e69f42016-04-15 06:20:21 +0000810 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
811 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000812
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000813 if (!VT.isFloatingPoint())
814 setOperationAction(ISD::ABS, VT, Legal);
815
Hal Finkelcd8664c2015-12-11 23:11:52 +0000816 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000817 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000818 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000819 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000820
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000821 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
822 if (VT.isFloatingPoint() &&
823 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000824 for (unsigned Opcode :
825 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000826 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000827
Tim Northover3b0846e2014-05-24 12:50:23 +0000828 if (Subtarget->isLittleEndian()) {
829 for (unsigned im = (unsigned)ISD::PRE_INC;
830 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000831 setIndexedLoadAction(im, VT, Legal);
832 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000833 }
834 }
835}
836
837void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
838 addRegisterClass(VT, &AArch64::FPR64RegClass);
839 addTypeForNEON(VT, MVT::v2i32);
840}
841
842void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
843 addRegisterClass(VT, &AArch64::FPR128RegClass);
844 addTypeForNEON(VT, MVT::v4i32);
845}
846
Mehdi Amini44ede332015-07-09 02:09:04 +0000847EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
848 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000849 if (!VT.isVector())
850 return MVT::i32;
851 return VT.changeVectorElementTypeToInteger();
852}
853
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000854static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
855 const APInt &Demanded,
856 TargetLowering::TargetLoweringOpt &TLO,
857 unsigned NewOpc) {
858 uint64_t OldImm = Imm, NewImm, Enc;
859 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
860
861 // Return if the immediate is already all zeros, all ones, a bimm32 or a
862 // bimm64.
863 if (Imm == 0 || Imm == Mask ||
864 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
865 return false;
866
867 unsigned EltSize = Size;
868 uint64_t DemandedBits = Demanded.getZExtValue();
869
870 // Clear bits that are not demanded.
871 Imm &= DemandedBits;
872
873 while (true) {
874 // The goal here is to set the non-demanded bits in a way that minimizes
875 // the number of switching between 0 and 1. In order to achieve this goal,
876 // we set the non-demanded bits to the value of the preceding demanded bits.
877 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
878 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
879 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
880 // The final result is 0b11000011.
881 uint64_t NonDemandedBits = ~DemandedBits;
882 uint64_t InvertedImm = ~Imm & DemandedBits;
883 uint64_t RotatedImm =
884 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
885 NonDemandedBits;
886 uint64_t Sum = RotatedImm + NonDemandedBits;
887 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
888 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
889 NewImm = (Imm | Ones) & Mask;
890
891 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
892 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
893 // we halve the element size and continue the search.
894 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
895 break;
896
897 // We cannot shrink the element size any further if it is 2-bits.
898 if (EltSize == 2)
899 return false;
900
901 EltSize /= 2;
902 Mask >>= EltSize;
903 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
904
905 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
906 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
907 return false;
908
909 // Merge the upper and lower halves of Imm and DemandedBits.
910 Imm |= Hi;
911 DemandedBits |= DemandedBitsHi;
912 }
913
914 ++NumOptimizedImms;
915
916 // Replicate the element across the register width.
917 while (EltSize < Size) {
918 NewImm |= NewImm << EltSize;
919 EltSize *= 2;
920 }
921
922 (void)OldImm;
923 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
924 "demanded bits should never be altered");
925 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
926
927 // Create the new constant immediate node.
928 EVT VT = Op.getValueType();
929 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000930 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000931
932 // If the new constant immediate is all-zeros or all-ones, let the target
933 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000934 if (NewImm == 0 || NewImm == OrigMask) {
935 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
936 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000937 // Otherwise, create a machine node so that target independent DAG combine
938 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000939 } else {
940 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
941 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
942 New = SDValue(
943 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
944 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000945
946 return TLO.CombineTo(Op, New);
947}
948
949bool AArch64TargetLowering::targetShrinkDemandedConstant(
950 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
951 // Delay this optimization to as late as possible.
952 if (!TLO.LegalOps)
953 return false;
954
955 if (!EnableOptimizeLogicalImm)
956 return false;
957
958 EVT VT = Op.getValueType();
959 if (VT.isVector())
960 return false;
961
962 unsigned Size = VT.getSizeInBits();
963 assert((Size == 32 || Size == 64) &&
964 "i32 or i64 is expected after legalization.");
965
966 // Exit early if we demand all bits.
967 if (Demanded.countPopulation() == Size)
968 return false;
969
970 unsigned NewOpc;
971 switch (Op.getOpcode()) {
972 default:
973 return false;
974 case ISD::AND:
975 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
976 break;
977 case ISD::OR:
978 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
979 break;
980 case ISD::XOR:
981 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
982 break;
983 }
984 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
985 if (!C)
986 return false;
987 uint64_t Imm = C->getZExtValue();
988 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
989}
990
Tim Northover3b0846e2014-05-24 12:50:23 +0000991/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000992/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000993void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000994 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000995 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000996 switch (Op.getOpcode()) {
997 default:
998 break;
999 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001000 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +00001001 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1002 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +00001003 Known.Zero &= Known2.Zero;
1004 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001005 break;
1006 }
1007 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001008 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001009 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1010 switch (IntID) {
1011 default: return;
1012 case Intrinsic::aarch64_ldaxr:
1013 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001014 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001015 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001016 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001017 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001018 return;
1019 }
1020 }
1021 break;
1022 }
1023 case ISD::INTRINSIC_WO_CHAIN:
1024 case ISD::INTRINSIC_VOID: {
1025 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1026 switch (IntNo) {
1027 default:
1028 break;
1029 case Intrinsic::aarch64_neon_umaxv:
1030 case Intrinsic::aarch64_neon_uminv: {
1031 // Figure out the datatype of the vector operand. The UMINV instruction
1032 // will zero extend the result, so we can mark as known zero all the
1033 // bits larger than the element datatype. 32-bit or larget doesn't need
1034 // this as those are legal types and will be handled by isel directly.
1035 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001036 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001037 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1038 assert(BitWidth >= 8 && "Unexpected width!");
1039 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001040 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001041 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1042 assert(BitWidth >= 16 && "Unexpected width!");
1043 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001044 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001045 }
1046 break;
1047 } break;
1048 }
1049 }
1050 }
1051}
1052
Mehdi Aminieaabc512015-07-09 15:12:23 +00001053MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1054 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001055 return MVT::i64;
1056}
1057
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001058bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1059 unsigned AddrSpace,
1060 unsigned Align,
1061 bool *Fast) const {
1062 if (Subtarget->requiresStrictAlign())
1063 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001064
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001065 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001066 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1067 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001068 // See comments in performSTORECombine() for more details about
1069 // these conditions.
1070
1071 // Code that uses clang vector extensions can mark that it
1072 // wants unaligned accesses to be treated as fast by
1073 // underspecifying alignment to be 1 or 2.
1074 Align <= 2 ||
1075
1076 // Disregard v2i64. Memcpy lowering produces those and splitting
1077 // them regresses performance on micro-benchmarks and olden/bh.
1078 VT == MVT::v2i64;
1079 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001080 return true;
1081}
1082
Tim Northover3b0846e2014-05-24 12:50:23 +00001083FastISel *
1084AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1085 const TargetLibraryInfo *libInfo) const {
1086 return AArch64::createFastISel(funcInfo, libInfo);
1087}
1088
1089const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001090 switch ((AArch64ISD::NodeType)Opcode) {
1091 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001092 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1093 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001094 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001095 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1096 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1097 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1098 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1099 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1100 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1101 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1102 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1103 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1104 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001105 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001106 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1107 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1108 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1109 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1110 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1111 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1112 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001113 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1114 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1115 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001116 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001117 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1118 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1119 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1120 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1121 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1122 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1123 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1124 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1125 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1126 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1127 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1128 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1129 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1130 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1131 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1132 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1133 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1134 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1135 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1136 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1137 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1138 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1139 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1140 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1141 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1142 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1143 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1144 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1145 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1146 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1147 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1148 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1149 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1150 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1151 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1152 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1153 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1154 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1155 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1156 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1157 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1158 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1159 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1160 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1161 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1162 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1163 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1164 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001165 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1166 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1167 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1168 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1169 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1170 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001171 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1172 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1173 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1174 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1175 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1176 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1177 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001178 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001179 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1180 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001181 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001182 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1183 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1184 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1185 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1186 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1187 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1188 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1189 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1190 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1191 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1192 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1193 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1194 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1195 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1196 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1197 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1198 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1199 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1200 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1201 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1202 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1203 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1204 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1205 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1206 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1207 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1208 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1209 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1210 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001211 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1212 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001213 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001214 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1215 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1216 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001217 }
Matthias Braund04893f2015-05-07 21:33:59 +00001218 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001219}
1220
1221MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001222AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001223 MachineBasicBlock *MBB) const {
1224 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1225 // phi node:
1226
1227 // OrigBB:
1228 // [... previous instrs leading to comparison ...]
1229 // b.ne TrueBB
1230 // b EndBB
1231 // TrueBB:
1232 // ; Fallthrough
1233 // EndBB:
1234 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1235
Tim Northover3b0846e2014-05-24 12:50:23 +00001236 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001237 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001238 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001239 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001240 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001241
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001242 unsigned DestReg = MI.getOperand(0).getReg();
1243 unsigned IfTrueReg = MI.getOperand(1).getReg();
1244 unsigned IfFalseReg = MI.getOperand(2).getReg();
1245 unsigned CondCode = MI.getOperand(3).getImm();
1246 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001247
1248 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1249 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1250 MF->insert(It, TrueBB);
1251 MF->insert(It, EndBB);
1252
1253 // Transfer rest of current basic-block to EndBB
1254 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1255 MBB->end());
1256 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1257
1258 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1259 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1260 MBB->addSuccessor(TrueBB);
1261 MBB->addSuccessor(EndBB);
1262
1263 // TrueBB falls through to the end.
1264 TrueBB->addSuccessor(EndBB);
1265
1266 if (!NZCVKilled) {
1267 TrueBB->addLiveIn(AArch64::NZCV);
1268 EndBB->addLiveIn(AArch64::NZCV);
1269 }
1270
1271 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1272 .addReg(IfTrueReg)
1273 .addMBB(TrueBB)
1274 .addReg(IfFalseReg)
1275 .addMBB(MBB);
1276
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001277 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001278 return EndBB;
1279}
1280
Eli Friedmanad1151c2018-11-09 23:33:30 +00001281MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1282 MachineInstr &MI, MachineBasicBlock *BB) const {
1283 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1284 BB->getParent()->getFunction().getPersonalityFn())) &&
1285 "SEH does not use catchret!");
1286 return BB;
1287}
1288
1289MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1290 MachineInstr &MI, MachineBasicBlock *BB) const {
1291 MI.eraseFromParent();
1292 return BB;
1293}
1294
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001295MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1296 MachineInstr &MI, MachineBasicBlock *BB) const {
1297 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001298 default:
1299#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001300 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001301#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001302 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001303
1304 case AArch64::F128CSEL:
1305 return EmitF128CSEL(MI, BB);
1306
1307 case TargetOpcode::STACKMAP:
1308 case TargetOpcode::PATCHPOINT:
1309 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001310
1311 case AArch64::CATCHRET:
1312 return EmitLoweredCatchRet(MI, BB);
1313 case AArch64::CATCHPAD:
1314 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001315 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001316}
1317
1318//===----------------------------------------------------------------------===//
1319// AArch64 Lowering private implementation.
1320//===----------------------------------------------------------------------===//
1321
1322//===----------------------------------------------------------------------===//
1323// Lowering Code
1324//===----------------------------------------------------------------------===//
1325
1326/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1327/// CC
1328static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1329 switch (CC) {
1330 default:
1331 llvm_unreachable("Unknown condition code!");
1332 case ISD::SETNE:
1333 return AArch64CC::NE;
1334 case ISD::SETEQ:
1335 return AArch64CC::EQ;
1336 case ISD::SETGT:
1337 return AArch64CC::GT;
1338 case ISD::SETGE:
1339 return AArch64CC::GE;
1340 case ISD::SETLT:
1341 return AArch64CC::LT;
1342 case ISD::SETLE:
1343 return AArch64CC::LE;
1344 case ISD::SETUGT:
1345 return AArch64CC::HI;
1346 case ISD::SETUGE:
1347 return AArch64CC::HS;
1348 case ISD::SETULT:
1349 return AArch64CC::LO;
1350 case ISD::SETULE:
1351 return AArch64CC::LS;
1352 }
1353}
1354
1355/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1356static void changeFPCCToAArch64CC(ISD::CondCode CC,
1357 AArch64CC::CondCode &CondCode,
1358 AArch64CC::CondCode &CondCode2) {
1359 CondCode2 = AArch64CC::AL;
1360 switch (CC) {
1361 default:
1362 llvm_unreachable("Unknown FP condition!");
1363 case ISD::SETEQ:
1364 case ISD::SETOEQ:
1365 CondCode = AArch64CC::EQ;
1366 break;
1367 case ISD::SETGT:
1368 case ISD::SETOGT:
1369 CondCode = AArch64CC::GT;
1370 break;
1371 case ISD::SETGE:
1372 case ISD::SETOGE:
1373 CondCode = AArch64CC::GE;
1374 break;
1375 case ISD::SETOLT:
1376 CondCode = AArch64CC::MI;
1377 break;
1378 case ISD::SETOLE:
1379 CondCode = AArch64CC::LS;
1380 break;
1381 case ISD::SETONE:
1382 CondCode = AArch64CC::MI;
1383 CondCode2 = AArch64CC::GT;
1384 break;
1385 case ISD::SETO:
1386 CondCode = AArch64CC::VC;
1387 break;
1388 case ISD::SETUO:
1389 CondCode = AArch64CC::VS;
1390 break;
1391 case ISD::SETUEQ:
1392 CondCode = AArch64CC::EQ;
1393 CondCode2 = AArch64CC::VS;
1394 break;
1395 case ISD::SETUGT:
1396 CondCode = AArch64CC::HI;
1397 break;
1398 case ISD::SETUGE:
1399 CondCode = AArch64CC::PL;
1400 break;
1401 case ISD::SETLT:
1402 case ISD::SETULT:
1403 CondCode = AArch64CC::LT;
1404 break;
1405 case ISD::SETLE:
1406 case ISD::SETULE:
1407 CondCode = AArch64CC::LE;
1408 break;
1409 case ISD::SETNE:
1410 case ISD::SETUNE:
1411 CondCode = AArch64CC::NE;
1412 break;
1413 }
1414}
1415
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001416/// Convert a DAG fp condition code to an AArch64 CC.
1417/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1418/// should be AND'ed instead of OR'ed.
1419static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1420 AArch64CC::CondCode &CondCode,
1421 AArch64CC::CondCode &CondCode2) {
1422 CondCode2 = AArch64CC::AL;
1423 switch (CC) {
1424 default:
1425 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1426 assert(CondCode2 == AArch64CC::AL);
1427 break;
1428 case ISD::SETONE:
1429 // (a one b)
1430 // == ((a olt b) || (a ogt b))
1431 // == ((a ord b) && (a une b))
1432 CondCode = AArch64CC::VC;
1433 CondCode2 = AArch64CC::NE;
1434 break;
1435 case ISD::SETUEQ:
1436 // (a ueq b)
1437 // == ((a uno b) || (a oeq b))
1438 // == ((a ule b) && (a uge b))
1439 CondCode = AArch64CC::PL;
1440 CondCode2 = AArch64CC::LE;
1441 break;
1442 }
1443}
1444
Tim Northover3b0846e2014-05-24 12:50:23 +00001445/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1446/// CC usable with the vector instructions. Fewer operations are available
1447/// without a real NZCV register, so we have to use less efficient combinations
1448/// to get the same effect.
1449static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1450 AArch64CC::CondCode &CondCode,
1451 AArch64CC::CondCode &CondCode2,
1452 bool &Invert) {
1453 Invert = false;
1454 switch (CC) {
1455 default:
1456 // Mostly the scalar mappings work fine.
1457 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1458 break;
1459 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001460 Invert = true;
1461 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001462 case ISD::SETO:
1463 CondCode = AArch64CC::MI;
1464 CondCode2 = AArch64CC::GE;
1465 break;
1466 case ISD::SETUEQ:
1467 case ISD::SETULT:
1468 case ISD::SETULE:
1469 case ISD::SETUGT:
1470 case ISD::SETUGE:
1471 // All of the compare-mask comparisons are ordered, but we can switch
1472 // between the two by a double inversion. E.g. ULE == !OGT.
1473 Invert = true;
1474 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1475 break;
1476 }
1477}
1478
1479static bool isLegalArithImmed(uint64_t C) {
1480 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001481 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001482 LLVM_DEBUG(dbgs() << "Is imm " << C
1483 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001484 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001485}
1486
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001487// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1488// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1489// can be set differently by this operation. It comes down to whether
1490// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1491// everything is fine. If not then the optimization is wrong. Thus general
1492// comparisons are only valid if op2 != 0.
1493//
1494// So, finally, the only LLVM-native comparisons that don't mention C and V
1495// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1496// the absence of information about op2.
1497static bool isCMN(SDValue Op, ISD::CondCode CC) {
1498 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1499 (CC == ISD::SETEQ || CC == ISD::SETNE);
1500}
1501
Tim Northover3b0846e2014-05-24 12:50:23 +00001502static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001503 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001504 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001505 const bool FullFP16 =
1506 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001507
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001508 if (VT.isFloatingPoint()) {
1509 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001510 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001511 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1512 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001513 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001514 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001515 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001516 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001517
1518 // The CMP instruction is just an alias for SUBS, and representing it as
1519 // SUBS means that it's possible to get CSE with subtract operations.
1520 // A later phase can perform the optimization of setting the destination
1521 // register to WZR/XZR if it ends up being unused.
1522 unsigned Opcode = AArch64ISD::SUBS;
1523
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001524 if (isCMN(RHS, CC)) {
1525 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001526 Opcode = AArch64ISD::ADDS;
1527 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001528 } else if (isCMN(LHS, CC)) {
1529 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1530 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1531 Opcode = AArch64ISD::ADDS;
1532 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001533 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001534 !isUnsignedIntSetCC(CC)) {
1535 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1536 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1537 // of the signed comparisons.
1538 Opcode = AArch64ISD::ANDS;
1539 RHS = LHS.getOperand(1);
1540 LHS = LHS.getOperand(0);
1541 }
1542
Matthias Braunaf7d7702015-07-16 20:02:37 +00001543 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001544 .getValue(1);
1545}
1546
Matthias Braunaf7d7702015-07-16 20:02:37 +00001547/// \defgroup AArch64CCMP CMP;CCMP matching
1548///
1549/// These functions deal with the formation of CMP;CCMP;... sequences.
1550/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1551/// a comparison. They set the NZCV flags to a predefined value if their
1552/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001553/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001554/// expressed as:
1555/// cmp A
1556/// ccmp B, inv(CB), CA
1557/// check for CB flags
1558///
Matthias Braund0412122018-12-06 01:40:23 +00001559/// This naturally lets us implement chains of AND operations with SETCC
1560/// operands. And we can even implement some other situations by transforming
1561/// them:
1562/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1563/// negating the flags used in a CCMP/FCCMP operations.
1564/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1565/// by negating the flags we test for afterwards. i.e.
1566/// NEG (CMP CCMP CCCMP ...) can be implemented.
1567/// - Note that we can only ever negate all previously processed results.
1568/// What we can not implement by flipping the flags to test is a negation
1569/// of two sub-trees (because the negation affects all sub-trees emitted so
1570/// far, so the 2nd sub-tree we emit would also affect the first).
1571/// With those tools we can implement some OR operations:
1572/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1573/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1574/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1575/// elimination rules from earlier to implement the whole thing as a
1576/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001577///
Matthias Braund0412122018-12-06 01:40:23 +00001578/// As complete example:
1579/// or (or (setCA (cmp A)) (setCB (cmp B)))
1580/// (and (setCC (cmp C)) (setCD (cmp D)))"
1581/// can be reassociated to:
1582/// or (and (setCC (cmp C)) setCD (cmp D))
1583// (or (setCA (cmp A)) (setCB (cmp B)))
1584/// can be transformed to:
1585/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1586/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1587/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001588/// cmp C
1589/// ccmp D, inv(CD), CC
1590/// ccmp A, CA, inv(CD)
1591/// ccmp B, CB, inv(CA)
1592/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001593///
1594/// A counterexample is "or (and A B) (and C D)" which translates to
1595/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1596/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001597/// @{
1598
Geoff Berrye41c2df2015-07-20 22:03:52 +00001599/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001600static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1601 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001602 AArch64CC::CondCode Predicate,
1603 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001604 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001605 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001606 const bool FullFP16 =
1607 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1608
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001609 if (LHS.getValueType().isFloatingPoint()) {
1610 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001611 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001612 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1613 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1614 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001615 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001616 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001617 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001618 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001619 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1620 Opcode = AArch64ISD::CCMN;
1621 RHS = RHS.getOperand(1);
1622 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001623 }
1624 if (Opcode == 0)
1625 Opcode = AArch64ISD::CCMP;
1626
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001627 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1628 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1629 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001630 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1631 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1632}
1633
Matthias Braun96d12512018-11-06 03:15:22 +00001634/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1635/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001636/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1637/// changing the conditions on the SETCC tests.
1638/// (this means we can call emitConjunctionRec() with
1639/// Negate==true on this sub-tree)
1640/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1641/// cannot do the negation naturally. We are required to
1642/// emit the subtree first in this case.
1643/// \param WillNegate Is true if are called when the result of this
1644/// subexpression must be negated. This happens when the
1645/// outer expression is an OR. We can use this fact to know
1646/// that we have a double negation (or (or ...) ...) that
1647/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001648static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001649 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001650 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001651 if (!Val.hasOneUse())
1652 return false;
1653 unsigned Opcode = Val->getOpcode();
1654 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001655 if (Val->getOperand(0).getValueType() == MVT::f128)
1656 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001657 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001658 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001659 return true;
1660 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001661 // Protect against exponential runtime and stack overflow.
1662 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001663 return false;
1664 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001665 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001666 SDValue O0 = Val->getOperand(0);
1667 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001668 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001669 bool MustBeFirstL;
1670 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001671 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001672 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001673 bool MustBeFirstR;
1674 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001675 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001676
Matthias Braund0412122018-12-06 01:40:23 +00001677 if (MustBeFirstL && MustBeFirstR)
1678 return false;
1679
1680 if (IsOR) {
1681 // For an OR expression we need to be able to naturally negate at least
1682 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001683 if (!CanNegateL && !CanNegateR)
1684 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001685 // If we the result of the OR will be negated and we can naturally negate
1686 // the leafs, then this sub-tree as a whole negates naturally.
1687 CanNegate = WillNegate && CanNegateL && CanNegateR;
1688 // If we cannot naturally negate the whole sub-tree, then this must be
1689 // emitted first.
1690 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001691 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001692 assert(Opcode == ISD::AND && "Must be OR or AND");
1693 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001694 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001695 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001696 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001697 return true;
1698 }
1699 return false;
1700}
1701
1702/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1703/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1704/// Tries to transform the given i1 producing node @p Val to a series compare
1705/// and conditional compare operations. @returns an NZCV flags producing node
1706/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1707/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001708/// \p Negate is true if we want this sub-tree being negated just by changing
1709/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001710static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001711 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001712 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001713 // We're at a tree leaf, produce a conditional comparison operation.
1714 unsigned Opcode = Val->getOpcode();
1715 if (Opcode == ISD::SETCC) {
1716 SDValue LHS = Val->getOperand(0);
1717 SDValue RHS = Val->getOperand(1);
1718 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1719 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001720 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001721 CC = getSetCCInverse(CC, isInteger);
1722 SDLoc DL(Val);
1723 // Determine OutCC and handle FP special case.
1724 if (isInteger) {
1725 OutCC = changeIntCCToAArch64CC(CC);
1726 } else {
1727 assert(LHS.getValueType().isFloatingPoint());
1728 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001729 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1730 // Some floating point conditions can't be tested with a single condition
1731 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001732 if (ExtraCC != AArch64CC::AL) {
1733 SDValue ExtraCmp;
1734 if (!CCOp.getNode())
1735 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001736 else
1737 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001738 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001739 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001740 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001741 }
1742 }
1743
1744 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001745 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001746 return emitComparison(LHS, RHS, CC, DL, DAG);
1747 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001748 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001749 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001750 }
Matthias Braund0412122018-12-06 01:40:23 +00001751 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001752
Matthias Braund0412122018-12-06 01:40:23 +00001753 bool IsOR = Opcode == ISD::OR;
1754
Matthias Braunaf7d7702015-07-16 20:02:37 +00001755 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001756 bool CanNegateL;
1757 bool MustBeFirstL;
1758 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1759 assert(ValidL && "Valid conjunction/disjunction tree");
1760 (void)ValidL;
1761
Matthias Braunaf7d7702015-07-16 20:02:37 +00001762 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001763 bool CanNegateR;
1764 bool MustBeFirstR;
1765 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1766 assert(ValidR && "Valid conjunction/disjunction tree");
1767 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001768
Matthias Braund0412122018-12-06 01:40:23 +00001769 // Swap sub-tree that must come first to the right side.
1770 if (MustBeFirstL) {
1771 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1772 std::swap(LHS, RHS);
1773 std::swap(CanNegateL, CanNegateR);
1774 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001775 }
1776
Matthias Braund0412122018-12-06 01:40:23 +00001777 bool NegateR;
1778 bool NegateAfterR;
1779 bool NegateL;
1780 bool NegateAfterAll;
1781 if (Opcode == ISD::OR) {
1782 // Swap the sub-tree that we can negate naturally to the left.
1783 if (!CanNegateL) {
1784 assert(CanNegateR && "at least one side must be negatable");
1785 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1786 assert(!Negate);
1787 std::swap(LHS, RHS);
1788 NegateR = false;
1789 NegateAfterR = true;
1790 } else {
1791 // Negate the left sub-tree if possible, otherwise negate the result.
1792 NegateR = CanNegateR;
1793 NegateAfterR = !CanNegateR;
1794 }
1795 NegateL = true;
1796 NegateAfterAll = !Negate;
1797 } else {
1798 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1799 assert(!Negate && "Valid conjunction/disjunction tree");
1800
1801 NegateL = false;
1802 NegateR = false;
1803 NegateAfterR = false;
1804 NegateAfterAll = false;
1805 }
1806
1807 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001808 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001809 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1810 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001811 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001812 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1813 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001814 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1815 return CmpL;
1816}
1817
Matthias Braun96d12512018-11-06 03:15:22 +00001818/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1819/// In some cases this is even possible with OR operations in the expression.
1820/// See \ref AArch64CCMP.
1821/// \see emitConjunctionRec().
1822static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1823 AArch64CC::CondCode &OutCC) {
1824 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001825 bool DummyMustBeFirst;
1826 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001827 return SDValue();
1828
Matthias Braun96d12512018-11-06 03:15:22 +00001829 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001830}
1831
Matthias Braunaf7d7702015-07-16 20:02:37 +00001832/// @}
1833
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001834/// Returns how profitable it is to fold a comparison's operand's shift and/or
1835/// extension operations.
1836static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1837 auto isSupportedExtend = [&](SDValue V) {
1838 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1839 return true;
1840
1841 if (V.getOpcode() == ISD::AND)
1842 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1843 uint64_t Mask = MaskCst->getZExtValue();
1844 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1845 }
1846
1847 return false;
1848 };
1849
1850 if (!Op.hasOneUse())
1851 return 0;
1852
1853 if (isSupportedExtend(Op))
1854 return 1;
1855
1856 unsigned Opc = Op.getOpcode();
1857 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1858 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1859 uint64_t Shift = ShiftCst->getZExtValue();
1860 if (isSupportedExtend(Op.getOperand(0)))
1861 return (Shift <= 4) ? 2 : 1;
1862 EVT VT = Op.getValueType();
1863 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1864 return 1;
1865 }
1866
1867 return 0;
1868}
1869
Tim Northover3b0846e2014-05-24 12:50:23 +00001870static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001871 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001872 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001873 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1874 EVT VT = RHS.getValueType();
1875 uint64_t C = RHSC->getZExtValue();
1876 if (!isLegalArithImmed(C)) {
1877 // Constant does not fit, try adjusting it by one?
1878 switch (CC) {
1879 default:
1880 break;
1881 case ISD::SETLT:
1882 case ISD::SETGE:
1883 if ((VT == MVT::i32 && C != 0x80000000 &&
1884 isLegalArithImmed((uint32_t)(C - 1))) ||
1885 (VT == MVT::i64 && C != 0x80000000ULL &&
1886 isLegalArithImmed(C - 1ULL))) {
1887 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1888 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001889 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001890 }
1891 break;
1892 case ISD::SETULT:
1893 case ISD::SETUGE:
1894 if ((VT == MVT::i32 && C != 0 &&
1895 isLegalArithImmed((uint32_t)(C - 1))) ||
1896 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1897 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1898 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001899 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001900 }
1901 break;
1902 case ISD::SETLE:
1903 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001904 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001905 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001906 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001907 isLegalArithImmed(C + 1ULL))) {
1908 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1909 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001910 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001911 }
1912 break;
1913 case ISD::SETULE:
1914 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001915 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001916 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001917 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001918 isLegalArithImmed(C + 1ULL))) {
1919 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1920 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001921 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001922 }
1923 break;
1924 }
1925 }
1926 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001927
1928 // Comparisons are canonicalized so that the RHS operand is simpler than the
1929 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1930 // can fold some shift+extend operations on the RHS operand, so swap the
1931 // operands if that can be done.
1932 //
1933 // For example:
1934 // lsl w13, w11, #1
1935 // cmp w13, w12
1936 // can be turned into:
1937 // cmp w12, w11, lsl #1
1938 if (!isa<ConstantSDNode>(RHS) ||
1939 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1940 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1941
1942 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1943 std::swap(LHS, RHS);
1944 CC = ISD::getSetCCSwappedOperands(CC);
1945 }
1946 }
1947
Matthias Braunaf7d7702015-07-16 20:02:37 +00001948 SDValue Cmp;
1949 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001950 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001951 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1952
1953 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1954 // For the i8 operand, the largest immediate is 255, so this can be easily
1955 // encoded in the compare instruction. For the i16 operand, however, the
1956 // largest immediate cannot be encoded in the compare.
1957 // Therefore, use a sign extending load and cmn to avoid materializing the
1958 // -1 constant. For example,
1959 // movz w1, #65535
1960 // ldrh w0, [x0, #0]
1961 // cmp w0, w1
1962 // >
1963 // ldrsh w0, [x0, #0]
1964 // cmn w0, #1
1965 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1966 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001967 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001968 // transformation is profitable.
1969 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1970 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1971 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1972 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1973 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1974 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1975 SDValue SExt =
1976 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1977 DAG.getValueType(MVT::i16));
1978 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1979 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001980 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001981 AArch64CC = changeIntCCToAArch64CC(CC);
1982 }
1983 }
1984
1985 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00001986 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001987 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1988 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001989 }
1990 }
1991 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001992
1993 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001994 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001995 AArch64CC = changeIntCCToAArch64CC(CC);
1996 }
1997 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001998 return Cmp;
1999}
2000
2001static std::pair<SDValue, SDValue>
2002getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2003 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2004 "Unsupported value type");
2005 SDValue Value, Overflow;
2006 SDLoc DL(Op);
2007 SDValue LHS = Op.getOperand(0);
2008 SDValue RHS = Op.getOperand(1);
2009 unsigned Opc = 0;
2010 switch (Op.getOpcode()) {
2011 default:
2012 llvm_unreachable("Unknown overflow instruction!");
2013 case ISD::SADDO:
2014 Opc = AArch64ISD::ADDS;
2015 CC = AArch64CC::VS;
2016 break;
2017 case ISD::UADDO:
2018 Opc = AArch64ISD::ADDS;
2019 CC = AArch64CC::HS;
2020 break;
2021 case ISD::SSUBO:
2022 Opc = AArch64ISD::SUBS;
2023 CC = AArch64CC::VS;
2024 break;
2025 case ISD::USUBO:
2026 Opc = AArch64ISD::SUBS;
2027 CC = AArch64CC::LO;
2028 break;
2029 // Multiply needs a little bit extra work.
2030 case ISD::SMULO:
2031 case ISD::UMULO: {
2032 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002033 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002034 if (Op.getValueType() == MVT::i32) {
2035 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2036 // For a 32 bit multiply with overflow check we want the instruction
2037 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2038 // need to generate the following pattern:
2039 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2040 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2041 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2042 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2043 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002044 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002045 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2046 // operation. We need to clear out the upper 32 bits, because we used a
2047 // widening multiply that wrote all 64 bits. In the end this should be a
2048 // noop.
2049 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2050 if (IsSigned) {
2051 // The signed overflow check requires more than just a simple check for
2052 // any bit set in the upper 32 bits of the result. These bits could be
2053 // just the sign bits of a negative number. To perform the overflow
2054 // check we have to arithmetic shift right the 32nd bit of the result by
2055 // 31 bits. Then we compare the result to the upper 32 bits.
2056 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002057 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002058 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2059 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002060 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002061 // It is important that LowerBits is last, otherwise the arithmetic
2062 // shift will not be folded into the compare (SUBS).
2063 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2064 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2065 .getValue(1);
2066 } else {
2067 // The overflow check for unsigned multiply is easy. We only need to
2068 // check if any of the upper 32 bits are set. This can be done with a
2069 // CMP (shifted register). For that we need to generate the following
2070 // pattern:
2071 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2072 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002073 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002074 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2075 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002076 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2077 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002078 UpperBits).getValue(1);
2079 }
2080 break;
2081 }
2082 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2083 // For the 64 bit multiply
2084 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2085 if (IsSigned) {
2086 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2087 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002088 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002089 // It is important that LowerBits is last, otherwise the arithmetic
2090 // shift will not be folded into the compare (SUBS).
2091 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2092 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2093 .getValue(1);
2094 } else {
2095 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2096 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2097 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002098 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2099 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002100 UpperBits).getValue(1);
2101 }
2102 break;
2103 }
2104 } // switch (...)
2105
2106 if (Opc) {
2107 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2108
2109 // Emit the AArch64 operation with overflow check.
2110 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2111 Overflow = Value.getValue(1);
2112 }
2113 return std::make_pair(Value, Overflow);
2114}
2115
2116SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2117 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002118 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002119 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002120}
2121
Amara Emerson24ca39c2017-10-09 15:15:09 +00002122// Returns true if the given Op is the overflow flag result of an overflow
2123// intrinsic operation.
2124static bool isOverflowIntrOpRes(SDValue Op) {
2125 unsigned Opc = Op.getOpcode();
2126 return (Op.getResNo() == 1 &&
2127 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2128 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2129}
2130
Tim Northover3b0846e2014-05-24 12:50:23 +00002131static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2132 SDValue Sel = Op.getOperand(0);
2133 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002134 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002135
Amara Emerson24ca39c2017-10-09 15:15:09 +00002136 // If the operand is an overflow checking operation, invert the condition
2137 // code and kill the Not operation. I.e., transform:
2138 // (xor (overflow_op_bool, 1))
2139 // -->
2140 // (csel 1, 0, invert(cc), overflow_op_bool)
2141 // ... which later gets transformed to just a cset instruction with an
2142 // inverted condition code, rather than a cset + eor sequence.
2143 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2144 // Only lower legal XALUO ops.
2145 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2146 return SDValue();
2147
2148 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2149 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2150 AArch64CC::CondCode CC;
2151 SDValue Value, Overflow;
2152 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2153 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2154 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2155 CCVal, Overflow);
2156 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002157 // If neither operand is a SELECT_CC, give up.
2158 if (Sel.getOpcode() != ISD::SELECT_CC)
2159 std::swap(Sel, Other);
2160 if (Sel.getOpcode() != ISD::SELECT_CC)
2161 return Op;
2162
2163 // The folding we want to perform is:
2164 // (xor x, (select_cc a, b, cc, 0, -1) )
2165 // -->
2166 // (csel x, (xor x, -1), cc ...)
2167 //
2168 // The latter will get matched to a CSINV instruction.
2169
2170 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2171 SDValue LHS = Sel.getOperand(0);
2172 SDValue RHS = Sel.getOperand(1);
2173 SDValue TVal = Sel.getOperand(2);
2174 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002175
2176 // FIXME: This could be generalized to non-integer comparisons.
2177 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2178 return Op;
2179
2180 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2181 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2182
Eric Christopher572e03a2015-06-19 01:53:21 +00002183 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002184 if (!CFVal || !CTVal)
2185 return Op;
2186
2187 // We can commute the SELECT_CC by inverting the condition. This
2188 // might be needed to make this fit into a CSINV pattern.
2189 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2190 std::swap(TVal, FVal);
2191 std::swap(CTVal, CFVal);
2192 CC = ISD::getSetCCInverse(CC, true);
2193 }
2194
2195 // If the constants line up, perform the transform!
2196 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2197 SDValue CCVal;
2198 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2199
2200 FVal = Other;
2201 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002202 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002203
2204 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2205 CCVal, Cmp);
2206 }
2207
2208 return Op;
2209}
2210
2211static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2212 EVT VT = Op.getValueType();
2213
2214 // Let legalize expand this if it isn't a legal type yet.
2215 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2216 return SDValue();
2217
2218 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2219
2220 unsigned Opc;
2221 bool ExtraOp = false;
2222 switch (Op.getOpcode()) {
2223 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002224 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002225 case ISD::ADDC:
2226 Opc = AArch64ISD::ADDS;
2227 break;
2228 case ISD::SUBC:
2229 Opc = AArch64ISD::SUBS;
2230 break;
2231 case ISD::ADDE:
2232 Opc = AArch64ISD::ADCS;
2233 ExtraOp = true;
2234 break;
2235 case ISD::SUBE:
2236 Opc = AArch64ISD::SBCS;
2237 ExtraOp = true;
2238 break;
2239 }
2240
2241 if (!ExtraOp)
2242 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2243 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2244 Op.getOperand(2));
2245}
2246
2247static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2248 // Let legalize expand this if it isn't a legal type yet.
2249 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2250 return SDValue();
2251
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002252 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002253 AArch64CC::CondCode CC;
2254 // The actual operation that sets the overflow or carry flag.
2255 SDValue Value, Overflow;
2256 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2257
2258 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002259 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2260 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002261
2262 // We use an inverted condition, because the conditional select is inverted
2263 // too. This will allow it to be selected to a single instruction:
2264 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002265 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2266 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002267 CCVal, Overflow);
2268
2269 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002270 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002271}
2272
2273// Prefetch operands are:
2274// 1: Address to prefetch
2275// 2: bool isWrite
2276// 3: int locality (0 = no locality ... 3 = extreme locality)
2277// 4: bool isDataCache
2278static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2279 SDLoc DL(Op);
2280 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2281 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002282 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002283
2284 bool IsStream = !Locality;
2285 // When the locality number is set
2286 if (Locality) {
2287 // The front-end should have filtered out the out-of-range values
2288 assert(Locality <= 3 && "Prefetch locality out-of-range");
2289 // The locality degree is the opposite of the cache speed.
2290 // Put the number the other way around.
2291 // The encoding starts at 0 for level 1
2292 Locality = 3 - Locality;
2293 }
2294
2295 // built the mask value encoding the expected behavior.
2296 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002297 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002298 (Locality << 1) | // Cache level bits
2299 (unsigned)IsStream; // Stream bit
2300 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002301 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002302}
2303
2304SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2305 SelectionDAG &DAG) const {
2306 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2307
2308 RTLIB::Libcall LC;
2309 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2310
2311 return LowerF128Call(Op, DAG, LC);
2312}
2313
2314SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2315 SelectionDAG &DAG) const {
2316 if (Op.getOperand(0).getValueType() != MVT::f128) {
2317 // It's legal except when f128 is involved
2318 return Op;
2319 }
2320
2321 RTLIB::Libcall LC;
2322 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2323
2324 // FP_ROUND node has a second operand indicating whether it is known to be
2325 // precise. That doesn't take part in the LibCall so we can't directly use
2326 // LowerF128Call.
2327 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002328 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2329 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002330}
2331
2332static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2333 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2334 // Any additional optimization in this function should be recorded
2335 // in the cost tables.
2336 EVT InVT = Op.getOperand(0).getValueType();
2337 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002338 unsigned NumElts = InVT.getVectorNumElements();
2339
2340 // f16 vectors are promoted to f32 before a conversion.
2341 if (InVT.getVectorElementType() == MVT::f16) {
2342 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2343 SDLoc dl(Op);
2344 return DAG.getNode(
2345 Op.getOpcode(), dl, Op.getValueType(),
2346 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2347 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002348
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002349 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002350 SDLoc dl(Op);
2351 SDValue Cv =
2352 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2353 Op.getOperand(0));
2354 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002355 }
2356
2357 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002358 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002359 MVT ExtVT =
2360 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2361 VT.getVectorNumElements());
2362 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002363 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2364 }
2365
2366 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002367 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002368}
2369
2370SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2371 SelectionDAG &DAG) const {
2372 if (Op.getOperand(0).getValueType().isVector())
2373 return LowerVectorFP_TO_INT(Op, DAG);
2374
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002375 // f16 conversions are promoted to f32 when full fp16 is not supported.
2376 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2377 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002378 SDLoc dl(Op);
2379 return DAG.getNode(
2380 Op.getOpcode(), dl, Op.getValueType(),
2381 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2382 }
2383
Tim Northover3b0846e2014-05-24 12:50:23 +00002384 if (Op.getOperand(0).getValueType() != MVT::f128) {
2385 // It's legal except when f128 is involved
2386 return Op;
2387 }
2388
2389 RTLIB::Libcall LC;
2390 if (Op.getOpcode() == ISD::FP_TO_SINT)
2391 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2392 else
2393 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2394
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002395 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002396 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002397}
2398
2399static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2400 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2401 // Any additional optimization in this function should be recorded
2402 // in the cost tables.
2403 EVT VT = Op.getValueType();
2404 SDLoc dl(Op);
2405 SDValue In = Op.getOperand(0);
2406 EVT InVT = In.getValueType();
2407
Tim Northoveref0d7602014-06-15 09:27:06 +00002408 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2409 MVT CastVT =
2410 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2411 InVT.getVectorNumElements());
2412 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002413 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002414 }
2415
Tim Northoveref0d7602014-06-15 09:27:06 +00002416 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2417 unsigned CastOpc =
2418 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2419 EVT CastVT = VT.changeVectorElementTypeToInteger();
2420 In = DAG.getNode(CastOpc, dl, CastVT, In);
2421 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002422 }
2423
Tim Northoveref0d7602014-06-15 09:27:06 +00002424 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002425}
2426
2427SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2428 SelectionDAG &DAG) const {
2429 if (Op.getValueType().isVector())
2430 return LowerVectorINT_TO_FP(Op, DAG);
2431
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002432 // f16 conversions are promoted to f32 when full fp16 is not supported.
2433 if (Op.getValueType() == MVT::f16 &&
2434 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002435 SDLoc dl(Op);
2436 return DAG.getNode(
2437 ISD::FP_ROUND, dl, MVT::f16,
2438 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002439 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002440 }
2441
Tim Northover3b0846e2014-05-24 12:50:23 +00002442 // i128 conversions are libcalls.
2443 if (Op.getOperand(0).getValueType() == MVT::i128)
2444 return SDValue();
2445
2446 // Other conversions are legal, unless it's to the completely software-based
2447 // fp128.
2448 if (Op.getValueType() != MVT::f128)
2449 return Op;
2450
2451 RTLIB::Libcall LC;
2452 if (Op.getOpcode() == ISD::SINT_TO_FP)
2453 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2454 else
2455 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2456
2457 return LowerF128Call(Op, DAG, LC);
2458}
2459
2460SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2461 SelectionDAG &DAG) const {
2462 // For iOS, we want to call an alternative entry point: __sincos_stret,
2463 // which returns the values in two S / D registers.
2464 SDLoc dl(Op);
2465 SDValue Arg = Op.getOperand(0);
2466 EVT ArgVT = Arg.getValueType();
2467 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2468
2469 ArgListTy Args;
2470 ArgListEntry Entry;
2471
2472 Entry.Node = Arg;
2473 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002474 Entry.IsSExt = false;
2475 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002476 Args.push_back(Entry);
2477
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002478 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2479 : RTLIB::SINCOS_STRET_F32;
2480 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002481 SDValue Callee =
2482 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002483
Serge Gueltone38003f2017-05-09 19:31:13 +00002484 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002485 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002486 CLI.setDebugLoc(dl)
2487 .setChain(DAG.getEntryNode())
2488 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002489
2490 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2491 return CallResult.first;
2492}
2493
Tim Northoverf8bfe212014-07-18 13:07:05 +00002494static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2495 if (Op.getValueType() != MVT::f16)
2496 return SDValue();
2497
2498 assert(Op.getOperand(0).getValueType() == MVT::i16);
2499 SDLoc DL(Op);
2500
2501 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2502 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2503 return SDValue(
2504 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002505 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002506 0);
2507}
2508
Chad Rosierd9d0f862014-10-08 02:31:24 +00002509static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2510 if (OrigVT.getSizeInBits() >= 64)
2511 return OrigVT;
2512
2513 assert(OrigVT.isSimple() && "Expecting a simple value type");
2514
2515 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2516 switch (OrigSimpleTy) {
2517 default: llvm_unreachable("Unexpected Vector Type");
2518 case MVT::v2i8:
2519 case MVT::v2i16:
2520 return MVT::v2i32;
2521 case MVT::v4i8:
2522 return MVT::v4i16;
2523 }
2524}
2525
2526static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2527 const EVT &OrigTy,
2528 const EVT &ExtTy,
2529 unsigned ExtOpcode) {
2530 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2531 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2532 // 64-bits we need to insert a new extension so that it will be 64-bits.
2533 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2534 if (OrigTy.getSizeInBits() >= 64)
2535 return N;
2536
2537 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2538 EVT NewVT = getExtensionTo64Bits(OrigTy);
2539
2540 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2541}
2542
2543static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2544 bool isSigned) {
2545 EVT VT = N->getValueType(0);
2546
2547 if (N->getOpcode() != ISD::BUILD_VECTOR)
2548 return false;
2549
Pete Cooper3af9a252015-06-26 18:17:36 +00002550 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002551 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002552 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002553 unsigned HalfSize = EltSize / 2;
2554 if (isSigned) {
2555 if (!isIntN(HalfSize, C->getSExtValue()))
2556 return false;
2557 } else {
2558 if (!isUIntN(HalfSize, C->getZExtValue()))
2559 return false;
2560 }
2561 continue;
2562 }
2563 return false;
2564 }
2565
2566 return true;
2567}
2568
2569static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2570 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2571 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2572 N->getOperand(0)->getValueType(0),
2573 N->getValueType(0),
2574 N->getOpcode());
2575
2576 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2577 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002578 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002579 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002580 unsigned NumElts = VT.getVectorNumElements();
2581 MVT TruncVT = MVT::getIntegerVT(EltSize);
2582 SmallVector<SDValue, 8> Ops;
2583 for (unsigned i = 0; i != NumElts; ++i) {
2584 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2585 const APInt &CInt = C->getAPIntValue();
2586 // Element types smaller than 32 bits are not legal, so use i32 elements.
2587 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002588 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002589 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002590 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002591}
2592
2593static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002594 return N->getOpcode() == ISD::SIGN_EXTEND ||
2595 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002596}
2597
2598static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002599 return N->getOpcode() == ISD::ZERO_EXTEND ||
2600 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002601}
2602
2603static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2604 unsigned Opcode = N->getOpcode();
2605 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2606 SDNode *N0 = N->getOperand(0).getNode();
2607 SDNode *N1 = N->getOperand(1).getNode();
2608 return N0->hasOneUse() && N1->hasOneUse() &&
2609 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2610 }
2611 return false;
2612}
2613
2614static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2615 unsigned Opcode = N->getOpcode();
2616 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2617 SDNode *N0 = N->getOperand(0).getNode();
2618 SDNode *N1 = N->getOperand(1).getNode();
2619 return N0->hasOneUse() && N1->hasOneUse() &&
2620 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2621 }
2622 return false;
2623}
2624
Tim Northover70666e72018-06-20 12:09:01 +00002625SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2626 SelectionDAG &DAG) const {
2627 // The rounding mode is in bits 23:22 of the FPSCR.
2628 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2629 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2630 // so that the shift + and get folded into a bitfield extract.
2631 SDLoc dl(Op);
2632
2633 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2634 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2635 MVT::i64));
2636 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2637 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2638 DAG.getConstant(1U << 22, dl, MVT::i32));
2639 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2640 DAG.getConstant(22, dl, MVT::i32));
2641 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2642 DAG.getConstant(3, dl, MVT::i32));
2643}
2644
Chad Rosierd9d0f862014-10-08 02:31:24 +00002645static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2646 // Multiplications are only custom-lowered for 128-bit vectors so that
2647 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2648 EVT VT = Op.getValueType();
2649 assert(VT.is128BitVector() && VT.isInteger() &&
2650 "unexpected type for custom-lowering ISD::MUL");
2651 SDNode *N0 = Op.getOperand(0).getNode();
2652 SDNode *N1 = Op.getOperand(1).getNode();
2653 unsigned NewOpc = 0;
2654 bool isMLA = false;
2655 bool isN0SExt = isSignExtended(N0, DAG);
2656 bool isN1SExt = isSignExtended(N1, DAG);
2657 if (isN0SExt && isN1SExt)
2658 NewOpc = AArch64ISD::SMULL;
2659 else {
2660 bool isN0ZExt = isZeroExtended(N0, DAG);
2661 bool isN1ZExt = isZeroExtended(N1, DAG);
2662 if (isN0ZExt && isN1ZExt)
2663 NewOpc = AArch64ISD::UMULL;
2664 else if (isN1SExt || isN1ZExt) {
2665 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2666 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2667 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2668 NewOpc = AArch64ISD::SMULL;
2669 isMLA = true;
2670 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2671 NewOpc = AArch64ISD::UMULL;
2672 isMLA = true;
2673 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2674 std::swap(N0, N1);
2675 NewOpc = AArch64ISD::UMULL;
2676 isMLA = true;
2677 }
2678 }
2679
2680 if (!NewOpc) {
2681 if (VT == MVT::v2i64)
2682 // Fall through to expand this. It is not legal.
2683 return SDValue();
2684 else
2685 // Other vector multiplications are legal.
2686 return Op;
2687 }
2688 }
2689
2690 // Legalize to a S/UMULL instruction
2691 SDLoc DL(Op);
2692 SDValue Op0;
2693 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2694 if (!isMLA) {
2695 Op0 = skipExtensionForVectorMULL(N0, DAG);
2696 assert(Op0.getValueType().is64BitVector() &&
2697 Op1.getValueType().is64BitVector() &&
2698 "unexpected types for extended operands to VMULL");
2699 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2700 }
2701 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2702 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2703 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2704 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2705 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2706 EVT Op1VT = Op1.getValueType();
2707 return DAG.getNode(N0->getOpcode(), DL, VT,
2708 DAG.getNode(NewOpc, DL, VT,
2709 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2710 DAG.getNode(NewOpc, DL, VT,
2711 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2712}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002713
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002714SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2715 SelectionDAG &DAG) const {
2716 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2717 SDLoc dl(Op);
2718 switch (IntNo) {
2719 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002720 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002721 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2722 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2723 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002724 case Intrinsic::aarch64_neon_abs: {
2725 EVT Ty = Op.getValueType();
2726 if (Ty == MVT::i64) {
2727 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2728 Op.getOperand(1));
2729 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2730 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2731 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2732 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2733 } else {
2734 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2735 }
2736 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002737 case Intrinsic::aarch64_neon_smax:
2738 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2739 Op.getOperand(1), Op.getOperand(2));
2740 case Intrinsic::aarch64_neon_umax:
2741 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2742 Op.getOperand(1), Op.getOperand(2));
2743 case Intrinsic::aarch64_neon_smin:
2744 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2745 Op.getOperand(1), Op.getOperand(2));
2746 case Intrinsic::aarch64_neon_umin:
2747 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2748 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002749
2750 case Intrinsic::localaddress: {
Mandeep Singh Grang70d484d2019-02-01 21:41:33 +00002751 const auto &MF = DAG.getMachineFunction();
2752 const auto *RegInfo = Subtarget->getRegisterInfo();
2753 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002754 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2755 Op.getSimpleValueType());
2756 }
2757
2758 case Intrinsic::eh_recoverfp: {
2759 // FIXME: This needs to be implemented to correctly handle highly aligned
2760 // stack objects. For now we simply return the incoming FP. Refer D53541
2761 // for more details.
2762 SDValue FnOp = Op.getOperand(1);
2763 SDValue IncomingFPOp = Op.getOperand(2);
2764 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2765 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2766 if (!Fn)
2767 report_fatal_error(
2768 "llvm.eh.recoverfp must take a function as the first argument");
2769 return IncomingFPOp;
2770 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002771 }
2772}
2773
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002774// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2775static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2776 EVT VT, EVT MemVT,
2777 SelectionDAG &DAG) {
2778 assert(VT.isVector() && "VT should be a vector type");
2779 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2780
2781 SDValue Value = ST->getValue();
2782
2783 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2784 // the word lane which represent the v4i8 subvector. It optimizes the store
2785 // to:
2786 //
2787 // xtn v0.8b, v0.8h
2788 // str s0, [x0]
2789
2790 SDValue Undef = DAG.getUNDEF(MVT::i16);
2791 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2792 {Undef, Undef, Undef, Undef});
2793
2794 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2795 Value, UndefVec);
2796 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2797
2798 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2799 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2800 Trunc, DAG.getConstant(0, DL, MVT::i64));
2801
2802 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2803 ST->getBasePtr(), ST->getMemOperand());
2804}
2805
2806// Custom lowering for any store, vector or scalar and/or default or with
2807// a truncate operations. Currently only custom lower truncate operation
2808// from vector v4i16 to v4i8.
2809SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2810 SelectionDAG &DAG) const {
2811 SDLoc Dl(Op);
2812 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2813 assert (StoreNode && "Can only custom lower store nodes");
2814
2815 SDValue Value = StoreNode->getValue();
2816
2817 EVT VT = Value.getValueType();
2818 EVT MemVT = StoreNode->getMemoryVT();
2819
2820 assert (VT.isVector() && "Can only custom lower vector store types");
2821
2822 unsigned AS = StoreNode->getAddressSpace();
2823 unsigned Align = StoreNode->getAlignment();
2824 if (Align < MemVT.getStoreSize() &&
2825 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2826 return scalarizeVectorStore(StoreNode, DAG);
2827 }
2828
2829 if (StoreNode->isTruncatingStore()) {
2830 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2831 }
2832
2833 return SDValue();
2834}
2835
Tim Northover3b0846e2014-05-24 12:50:23 +00002836SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2837 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002838 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2839 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002840
Tim Northover3b0846e2014-05-24 12:50:23 +00002841 switch (Op.getOpcode()) {
2842 default:
2843 llvm_unreachable("unimplemented operand");
2844 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002845 case ISD::BITCAST:
2846 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002847 case ISD::GlobalAddress:
2848 return LowerGlobalAddress(Op, DAG);
2849 case ISD::GlobalTLSAddress:
2850 return LowerGlobalTLSAddress(Op, DAG);
2851 case ISD::SETCC:
2852 return LowerSETCC(Op, DAG);
2853 case ISD::BR_CC:
2854 return LowerBR_CC(Op, DAG);
2855 case ISD::SELECT:
2856 return LowerSELECT(Op, DAG);
2857 case ISD::SELECT_CC:
2858 return LowerSELECT_CC(Op, DAG);
2859 case ISD::JumpTable:
2860 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002861 case ISD::BR_JT:
2862 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002863 case ISD::ConstantPool:
2864 return LowerConstantPool(Op, DAG);
2865 case ISD::BlockAddress:
2866 return LowerBlockAddress(Op, DAG);
2867 case ISD::VASTART:
2868 return LowerVASTART(Op, DAG);
2869 case ISD::VACOPY:
2870 return LowerVACOPY(Op, DAG);
2871 case ISD::VAARG:
2872 return LowerVAARG(Op, DAG);
2873 case ISD::ADDC:
2874 case ISD::ADDE:
2875 case ISD::SUBC:
2876 case ISD::SUBE:
2877 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2878 case ISD::SADDO:
2879 case ISD::UADDO:
2880 case ISD::SSUBO:
2881 case ISD::USUBO:
2882 case ISD::SMULO:
2883 case ISD::UMULO:
2884 return LowerXALUO(Op, DAG);
2885 case ISD::FADD:
2886 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2887 case ISD::FSUB:
2888 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2889 case ISD::FMUL:
2890 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2891 case ISD::FDIV:
2892 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2893 case ISD::FP_ROUND:
2894 return LowerFP_ROUND(Op, DAG);
2895 case ISD::FP_EXTEND:
2896 return LowerFP_EXTEND(Op, DAG);
2897 case ISD::FRAMEADDR:
2898 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002899 case ISD::SPONENTRY:
2900 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002901 case ISD::RETURNADDR:
2902 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002903 case ISD::ADDROFRETURNADDR:
2904 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002905 case ISD::INSERT_VECTOR_ELT:
2906 return LowerINSERT_VECTOR_ELT(Op, DAG);
2907 case ISD::EXTRACT_VECTOR_ELT:
2908 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2909 case ISD::BUILD_VECTOR:
2910 return LowerBUILD_VECTOR(Op, DAG);
2911 case ISD::VECTOR_SHUFFLE:
2912 return LowerVECTOR_SHUFFLE(Op, DAG);
2913 case ISD::EXTRACT_SUBVECTOR:
2914 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2915 case ISD::SRA:
2916 case ISD::SRL:
2917 case ISD::SHL:
2918 return LowerVectorSRA_SRL_SHL(Op, DAG);
2919 case ISD::SHL_PARTS:
2920 return LowerShiftLeftParts(Op, DAG);
2921 case ISD::SRL_PARTS:
2922 case ISD::SRA_PARTS:
2923 return LowerShiftRightParts(Op, DAG);
2924 case ISD::CTPOP:
2925 return LowerCTPOP(Op, DAG);
2926 case ISD::FCOPYSIGN:
2927 return LowerFCOPYSIGN(Op, DAG);
2928 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002929 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002930 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002931 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002932 case ISD::XOR:
2933 return LowerXOR(Op, DAG);
2934 case ISD::PREFETCH:
2935 return LowerPREFETCH(Op, DAG);
2936 case ISD::SINT_TO_FP:
2937 case ISD::UINT_TO_FP:
2938 return LowerINT_TO_FP(Op, DAG);
2939 case ISD::FP_TO_SINT:
2940 case ISD::FP_TO_UINT:
2941 return LowerFP_TO_INT(Op, DAG);
2942 case ISD::FSINCOS:
2943 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002944 case ISD::FLT_ROUNDS_:
2945 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002946 case ISD::MUL:
2947 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002948 case ISD::INTRINSIC_WO_CHAIN:
2949 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002950 case ISD::STORE:
2951 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002952 case ISD::VECREDUCE_ADD:
2953 case ISD::VECREDUCE_SMAX:
2954 case ISD::VECREDUCE_SMIN:
2955 case ISD::VECREDUCE_UMAX:
2956 case ISD::VECREDUCE_UMIN:
2957 case ISD::VECREDUCE_FMAX:
2958 case ISD::VECREDUCE_FMIN:
2959 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002960 case ISD::ATOMIC_LOAD_SUB:
2961 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002962 case ISD::ATOMIC_LOAD_AND:
2963 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002964 case ISD::DYNAMIC_STACKALLOC:
2965 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002966 }
2967}
2968
Tim Northover3b0846e2014-05-24 12:50:23 +00002969//===----------------------------------------------------------------------===//
2970// Calling Convention Implementation
2971//===----------------------------------------------------------------------===//
2972
Robin Morisset039781e2014-08-29 21:53:01 +00002973/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002974CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2975 bool IsVarArg) const {
2976 switch (CC) {
2977 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002978 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002979 case CallingConv::WebKit_JS:
2980 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002981 case CallingConv::GHC:
2982 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002983 case CallingConv::C:
2984 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002985 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002986 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002987 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002988 if (Subtarget->isTargetWindows() && IsVarArg)
2989 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002990 if (!Subtarget->isTargetDarwin())
2991 return CC_AArch64_AAPCS;
2992 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002993 case CallingConv::Win64:
2994 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00002995 case CallingConv::AArch64_VectorCall:
2996 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002997 }
2998}
2999
Tim Northover406024a2016-08-10 21:44:01 +00003000CCAssignFn *
3001AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3002 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3003 : RetCC_AArch64_AAPCS;
3004}
3005
Tim Northover3b0846e2014-05-24 12:50:23 +00003006SDValue AArch64TargetLowering::LowerFormalArguments(
3007 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003008 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3009 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003010 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003011 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003012 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003013
3014 // Assign locations to all of the incoming arguments.
3015 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003016 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3017 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003018
3019 // At this point, Ins[].VT may already be promoted to i32. To correctly
3020 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3021 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3022 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3023 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3024 // LocVT.
3025 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003026 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003027 unsigned CurArgIdx = 0;
3028 for (unsigned i = 0; i != NumArgs; ++i) {
3029 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003030 if (Ins[i].isOrigArg()) {
3031 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3032 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003033
Andrew Trick05938a52015-02-16 18:10:47 +00003034 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003035 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3036 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003037 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3038 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3039 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3040 ValVT = MVT::i8;
3041 else if (ActualMVT == MVT::i16)
3042 ValVT = MVT::i16;
3043 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003044 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3045 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003046 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003047 assert(!Res && "Call operand has unhandled type");
3048 (void)Res;
3049 }
3050 assert(ArgLocs.size() == Ins.size());
3051 SmallVector<SDValue, 16> ArgValues;
3052 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3053 CCValAssign &VA = ArgLocs[i];
3054
3055 if (Ins[i].Flags.isByVal()) {
3056 // Byval is used for HFAs in the PCS, but the system should work in a
3057 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003058 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003059 int Size = Ins[i].Flags.getByValSize();
3060 unsigned NumRegs = (Size + 7) / 8;
3061
3062 // FIXME: This works on big-endian for composite byvals, which are the common
3063 // case. It should also work for fundamental types too.
3064 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003065 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003066 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003067 InVals.push_back(FrameIdxN);
3068
3069 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003070 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003071
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003072 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003073 // Arguments stored in registers.
3074 EVT RegVT = VA.getLocVT();
3075
3076 SDValue ArgValue;
3077 const TargetRegisterClass *RC;
3078
3079 if (RegVT == MVT::i32)
3080 RC = &AArch64::GPR32RegClass;
3081 else if (RegVT == MVT::i64)
3082 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003083 else if (RegVT == MVT::f16)
3084 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003085 else if (RegVT == MVT::f32)
3086 RC = &AArch64::FPR32RegClass;
3087 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3088 RC = &AArch64::FPR64RegClass;
3089 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3090 RC = &AArch64::FPR128RegClass;
3091 else
3092 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3093
3094 // Transform the arguments in physical registers into virtual ones.
3095 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3096 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3097
3098 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3099 // to 64 bits. Insert an assert[sz]ext to capture this, then
3100 // truncate to the right size.
3101 switch (VA.getLocInfo()) {
3102 default:
3103 llvm_unreachable("Unknown loc info!");
3104 case CCValAssign::Full:
3105 break;
3106 case CCValAssign::BCvt:
3107 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3108 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003109 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003110 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003111 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003112 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3113 // nodes after our lowering.
3114 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003115 break;
3116 }
3117
3118 InVals.push_back(ArgValue);
3119
3120 } else { // VA.isRegLoc()
3121 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3122 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003123 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003124
3125 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003126 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3127 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003128 BEAlign = 8 - ArgSize;
3129
Matthias Braun941a7052016-07-28 18:40:00 +00003130 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003131
3132 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003133 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003134 SDValue ArgValue;
3135
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003136 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003137 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003138 MVT MemVT = VA.getValVT();
3139
Tim Northover47e003c2014-05-26 17:21:53 +00003140 switch (VA.getLocInfo()) {
3141 default:
3142 break;
Tim Northover6890add2014-06-03 13:54:53 +00003143 case CCValAssign::BCvt:
3144 MemVT = VA.getLocVT();
3145 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003146 case CCValAssign::SExt:
3147 ExtType = ISD::SEXTLOAD;
3148 break;
3149 case CCValAssign::ZExt:
3150 ExtType = ISD::ZEXTLOAD;
3151 break;
3152 case CCValAssign::AExt:
3153 ExtType = ISD::EXTLOAD;
3154 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003155 }
3156
Alex Lorenze40c8a22015-08-11 23:09:45 +00003157 ArgValue = DAG.getExtLoad(
3158 ExtType, DL, VA.getLocVT(), Chain, FIN,
3159 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003160 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003161
Tim Northover3b0846e2014-05-24 12:50:23 +00003162 InVals.push_back(ArgValue);
3163 }
3164 }
3165
3166 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003167 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003168 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003169 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003170 // The AAPCS variadic function ABI is identical to the non-variadic
3171 // one. As a result there may be more arguments in registers and we should
3172 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003173 // Win64 variadic functions also pass arguments in registers, but all float
3174 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003175 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3176 }
3177
Tim Northover3b0846e2014-05-24 12:50:23 +00003178 // This will point to the next argument passed via stack.
3179 unsigned StackOffset = CCInfo.getNextStackOffset();
3180 // We currently pass all varargs at 8-byte alignment.
3181 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003182 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003183
3184 if (MFI.hasMustTailInVarArgFunc()) {
3185 SmallVector<MVT, 2> RegParmTypes;
3186 RegParmTypes.push_back(MVT::i64);
3187 RegParmTypes.push_back(MVT::f128);
3188 // Compute the set of forwarded registers. The rest are scratch.
3189 SmallVectorImpl<ForwardedRegister> &Forwards =
3190 FuncInfo->getForwardedMustTailRegParms();
3191 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3192 CC_AArch64_AAPCS);
3193 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003194 }
3195
Tim Northover3b0846e2014-05-24 12:50:23 +00003196 unsigned StackArgSize = CCInfo.getNextStackOffset();
3197 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3198 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3199 // This is a non-standard ABI so by fiat I say we're allowed to make full
3200 // use of the stack area to be popped, which must be aligned to 16 bytes in
3201 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003202 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003203
3204 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3205 // a multiple of 16.
3206 FuncInfo->setArgumentStackToRestore(StackArgSize);
3207
3208 // This realignment carries over to the available bytes below. Our own
3209 // callers will guarantee the space is free by giving an aligned value to
3210 // CALLSEQ_START.
3211 }
3212 // Even if we're not expected to free up the space, it's useful to know how
3213 // much is there while considering tail calls (because we can reuse it).
3214 FuncInfo->setBytesInStackArgArea(StackArgSize);
3215
Tri Vo6c47c622018-09-22 22:17:50 +00003216 if (Subtarget->hasCustomCallingConv())
3217 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3218
Tim Northover3b0846e2014-05-24 12:50:23 +00003219 return Chain;
3220}
3221
3222void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003223 SelectionDAG &DAG,
3224 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003225 SDValue &Chain) const {
3226 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003227 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003228 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003229 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003230 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003231
3232 SmallVector<SDValue, 8> MemOps;
3233
3234 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3235 AArch64::X3, AArch64::X4, AArch64::X5,
3236 AArch64::X6, AArch64::X7 };
3237 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003238 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003239
3240 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3241 int GPRIdx = 0;
3242 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003243 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003244 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003245 if (GPRSaveSize & 15)
3246 // The extra size here, if triggered, will always be 8.
3247 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3248 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003249 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003250
Mehdi Amini44ede332015-07-09 02:09:04 +00003251 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003252
3253 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3254 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3255 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003256 SDValue Store = DAG.getStore(
3257 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003258 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003259 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3260 GPRIdx,
3261 (i - FirstVariadicGPR) * 8)
3262 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003263 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003264 FIN =
3265 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003266 }
3267 }
3268 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3269 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3270
Martin Storsjo2f24e932017-07-17 20:05:19 +00003271 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003272 static const MCPhysReg FPRArgRegs[] = {
3273 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3274 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3275 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003276 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003277
3278 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3279 int FPRIdx = 0;
3280 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003281 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003282
Mehdi Amini44ede332015-07-09 02:09:04 +00003283 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003284
3285 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3286 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3287 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3288
Alex Lorenze40c8a22015-08-11 23:09:45 +00003289 SDValue Store = DAG.getStore(
3290 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003291 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003292 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003293 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3294 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003295 }
3296 }
3297 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3298 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3299 }
3300
3301 if (!MemOps.empty()) {
3302 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3303 }
3304}
3305
3306/// LowerCallResult - Lower the result values of a call into the
3307/// appropriate copies out of appropriate physical registers.
3308SDValue AArch64TargetLowering::LowerCallResult(
3309 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003310 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3311 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003312 SDValue ThisVal) const {
3313 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3314 ? RetCC_AArch64_WebKit_JS
3315 : RetCC_AArch64_AAPCS;
3316 // Assign locations to each value returned by this call.
3317 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003318 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3319 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003320 CCInfo.AnalyzeCallResult(Ins, RetCC);
3321
3322 // Copy all of the result registers out of their specified physreg.
3323 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3324 CCValAssign VA = RVLocs[i];
3325
3326 // Pass 'this' value directly from the argument to return value, to avoid
3327 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003328 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003329 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3330 "unexpected return calling convention register assignment");
3331 InVals.push_back(ThisVal);
3332 continue;
3333 }
3334
3335 SDValue Val =
3336 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3337 Chain = Val.getValue(1);
3338 InFlag = Val.getValue(2);
3339
3340 switch (VA.getLocInfo()) {
3341 default:
3342 llvm_unreachable("Unknown loc info!");
3343 case CCValAssign::Full:
3344 break;
3345 case CCValAssign::BCvt:
3346 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3347 break;
3348 }
3349
3350 InVals.push_back(Val);
3351 }
3352
3353 return Chain;
3354}
3355
Matthias Braun1af14142016-09-13 19:27:38 +00003356/// Return true if the calling convention is one that we can guarantee TCO for.
3357static bool canGuaranteeTCO(CallingConv::ID CC) {
3358 return CC == CallingConv::Fast;
3359}
3360
3361/// Return true if we might ever do TCO for calls with this calling convention.
3362static bool mayTailCallThisCC(CallingConv::ID CC) {
3363 switch (CC) {
3364 case CallingConv::C:
3365 case CallingConv::PreserveMost:
3366 case CallingConv::Swift:
3367 return true;
3368 default:
3369 return canGuaranteeTCO(CC);
3370 }
3371}
3372
Tim Northover3b0846e2014-05-24 12:50:23 +00003373bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3374 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003375 const SmallVectorImpl<ISD::OutputArg> &Outs,
3376 const SmallVectorImpl<SDValue> &OutVals,
3377 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003378 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003379 return false;
3380
Matthias Braun8d414362016-03-30 22:46:04 +00003381 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003382 const Function &CallerF = MF.getFunction();
3383 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003384 bool CCMatch = CallerCC == CalleeCC;
3385
3386 // Byval parameters hand the function a pointer directly into the stack area
3387 // we want to reuse during a tail call. Working around this *is* possible (see
3388 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003389 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3390 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003391 i != e; ++i)
3392 if (i->hasByValAttr())
3393 return false;
3394
Matthias Braun1af14142016-09-13 19:27:38 +00003395 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3396 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003397
Oliver Stannard12993dd2014-08-18 12:42:15 +00003398 // Externally-defined functions with weak linkage should not be
3399 // tail-called on AArch64 when the OS does not support dynamic
3400 // pre-emption of symbols, as the AAELF spec requires normal calls
3401 // to undefined weak functions to be replaced with a NOP or jump to the
3402 // next instruction. The behaviour of branch instructions in this
3403 // situation (as used for tail calls) is implementation-defined, so we
3404 // cannot rely on the linker replacing the tail call with a return.
3405 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3406 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003407 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003408 if (GV->hasExternalWeakLinkage() &&
3409 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003410 return false;
3411 }
3412
Tim Northover3b0846e2014-05-24 12:50:23 +00003413 // Now we search for cases where we can use a tail call without changing the
3414 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3415 // concept.
3416
3417 // I want anyone implementing a new calling convention to think long and hard
3418 // about this assert.
3419 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3420 "Unexpected variadic calling convention");
3421
Matthias Braun8d414362016-03-30 22:46:04 +00003422 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003423 if (isVarArg && !Outs.empty()) {
3424 // At least two cases here: if caller is fastcc then we can't have any
3425 // memory arguments (we'd be expected to clean up the stack afterwards). If
3426 // caller is C then we could potentially use its argument area.
3427
3428 // FIXME: for now we take the most conservative of these in both cases:
3429 // disallow all variadic memory operands.
3430 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003431 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003432
3433 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003434 for (const CCValAssign &ArgLoc : ArgLocs)
3435 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003436 return false;
3437 }
3438
Matthias Braun8d414362016-03-30 22:46:04 +00003439 // Check that the call results are passed in the same way.
3440 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3441 CCAssignFnForCall(CalleeCC, isVarArg),
3442 CCAssignFnForCall(CallerCC, isVarArg)))
3443 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003444 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003445 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3446 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003447 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003448 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003449 if (Subtarget->hasCustomCallingConv()) {
3450 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3451 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3452 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003453 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003454 return false;
3455 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003456
3457 // Nothing more to check if the callee is taking no arguments
3458 if (Outs.empty())
3459 return true;
3460
3461 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003462 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003463
3464 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3465
3466 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3467
Matthias Braun74a0bd32016-04-13 21:43:16 +00003468 // If the stack arguments for this call do not fit into our own save area then
3469 // the call cannot be made tail.
3470 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3471 return false;
3472
Matthias Braun46b0f032016-04-14 01:10:42 +00003473 const MachineRegisterInfo &MRI = MF.getRegInfo();
3474 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3475 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003476
3477 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003478}
3479
3480SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3481 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003482 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003483 int ClobberedFI) const {
3484 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003485 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3486 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003487
3488 // Include the original chain at the beginning of the list. When this is
3489 // used by target LowerCall hooks, this helps legalize find the
3490 // CALLSEQ_BEGIN node.
3491 ArgChains.push_back(Chain);
3492
3493 // Add a chain value for each stack argument corresponding
3494 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3495 UE = DAG.getEntryNode().getNode()->use_end();
3496 U != UE; ++U)
3497 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3498 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3499 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003500 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003501 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003502 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003503
3504 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3505 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3506 ArgChains.push_back(SDValue(L, 1));
3507 }
3508
3509 // Build a tokenfactor for all the chains.
3510 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3511}
3512
3513bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3514 bool TailCallOpt) const {
3515 return CallCC == CallingConv::Fast && TailCallOpt;
3516}
3517
Tim Northover3b0846e2014-05-24 12:50:23 +00003518/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3519/// and add input and output parameter nodes.
3520SDValue
3521AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3522 SmallVectorImpl<SDValue> &InVals) const {
3523 SelectionDAG &DAG = CLI.DAG;
3524 SDLoc &DL = CLI.DL;
3525 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3526 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3527 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3528 SDValue Chain = CLI.Chain;
3529 SDValue Callee = CLI.Callee;
3530 bool &IsTailCall = CLI.IsTailCall;
3531 CallingConv::ID CallConv = CLI.CallConv;
3532 bool IsVarArg = CLI.IsVarArg;
3533
3534 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003535 bool IsThisReturn = false;
3536
3537 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3538 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3539 bool IsSibCall = false;
3540
3541 if (IsTailCall) {
3542 // Check if it's really possible to do a tail call.
3543 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003544 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003545 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003546 report_fatal_error("failed to perform tail call elimination on a call "
3547 "site marked musttail");
3548
3549 // A sibling call is one where we're under the usual C ABI and not planning
3550 // to change that but can still do a tail call:
3551 if (!TailCallOpt && IsTailCall)
3552 IsSibCall = true;
3553
3554 if (IsTailCall)
3555 ++NumTailCalls;
3556 }
3557
3558 // Analyze operands of the call, assigning locations to each operand.
3559 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003560 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3561 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003562
3563 if (IsVarArg) {
3564 // Handle fixed and variable vector arguments differently.
3565 // Variable vector arguments always go into memory.
3566 unsigned NumArgs = Outs.size();
3567
3568 for (unsigned i = 0; i != NumArgs; ++i) {
3569 MVT ArgVT = Outs[i].VT;
3570 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3571 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3572 /*IsVarArg=*/ !Outs[i].IsFixed);
3573 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3574 assert(!Res && "Call operand has unhandled type");
3575 (void)Res;
3576 }
3577 } else {
3578 // At this point, Outs[].VT may already be promoted to i32. To correctly
3579 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3580 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3581 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3582 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3583 // LocVT.
3584 unsigned NumArgs = Outs.size();
3585 for (unsigned i = 0; i != NumArgs; ++i) {
3586 MVT ValVT = Outs[i].VT;
3587 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003588 EVT ActualVT = getValueType(DAG.getDataLayout(),
3589 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003590 /*AllowUnknown*/ true);
3591 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3592 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3593 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003594 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003595 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003596 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003597 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003598
3599 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003600 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003601 assert(!Res && "Call operand has unhandled type");
3602 (void)Res;
3603 }
3604 }
3605
3606 // Get a count of how many bytes are to be pushed on the stack.
3607 unsigned NumBytes = CCInfo.getNextStackOffset();
3608
3609 if (IsSibCall) {
3610 // Since we're not changing the ABI to make this a tail call, the memory
3611 // operands are already available in the caller's incoming argument space.
3612 NumBytes = 0;
3613 }
3614
3615 // FPDiff is the byte offset of the call's argument area from the callee's.
3616 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3617 // by this amount for a tail call. In a sibling call it must be 0 because the
3618 // caller will deallocate the entire stack and the callee still expects its
3619 // arguments to begin at SP+0. Completely unused for non-tail calls.
3620 int FPDiff = 0;
3621
3622 if (IsTailCall && !IsSibCall) {
3623 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3624
3625 // Since callee will pop argument stack as a tail call, we must keep the
3626 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003627 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003628
3629 // FPDiff will be negative if this tail call requires more space than we
3630 // would automatically have in our incoming argument space. Positive if we
3631 // can actually shrink the stack.
3632 FPDiff = NumReusableBytes - NumBytes;
3633
3634 // The stack pointer must be 16-byte aligned at all times it's used for a
3635 // memory operation, which in practice means at *all* times and in
3636 // particular across call boundaries. Therefore our own arguments started at
3637 // a 16-byte aligned SP and the delta applied for the tail call should
3638 // satisfy the same constraint.
3639 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3640 }
3641
3642 // Adjust the stack pointer for the new arguments...
3643 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003644 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003645 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003646
Mehdi Amini44ede332015-07-09 02:09:04 +00003647 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3648 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003649
3650 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3651 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003652 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003653
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003654 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3655 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3656 for (const auto &F : Forwards) {
3657 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3658 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3659 }
3660 }
3661
Tim Northover3b0846e2014-05-24 12:50:23 +00003662 // Walk the register/memloc assignments, inserting copies/loads.
3663 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3664 ++i, ++realArgIdx) {
3665 CCValAssign &VA = ArgLocs[i];
3666 SDValue Arg = OutVals[realArgIdx];
3667 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3668
3669 // Promote the value if needed.
3670 switch (VA.getLocInfo()) {
3671 default:
3672 llvm_unreachable("Unknown loc info!");
3673 case CCValAssign::Full:
3674 break;
3675 case CCValAssign::SExt:
3676 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3677 break;
3678 case CCValAssign::ZExt:
3679 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3680 break;
3681 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003682 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3683 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3684 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3685 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3686 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003687 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3688 break;
3689 case CCValAssign::BCvt:
3690 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3691 break;
3692 case CCValAssign::FPExt:
3693 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3694 break;
3695 }
3696
3697 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003698 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3699 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003700 assert(VA.getLocVT() == MVT::i64 &&
3701 "unexpected calling convention register assignment");
3702 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3703 "unexpected use of 'returned'");
3704 IsThisReturn = true;
3705 }
3706 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3707 } else {
3708 assert(VA.isMemLoc());
3709
3710 SDValue DstAddr;
3711 MachinePointerInfo DstInfo;
3712
3713 // FIXME: This works on big-endian for composite byvals, which are the
3714 // common case. It should also work for fundamental types too.
3715 uint32_t BEAlign = 0;
3716 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003717 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003718 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003719 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3720 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003721 if (OpSize < 8)
3722 BEAlign = 8 - OpSize;
3723 }
3724 unsigned LocMemOffset = VA.getLocMemOffset();
3725 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003726 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003727 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003728
3729 if (IsTailCall) {
3730 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003731 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003732
Mehdi Amini44ede332015-07-09 02:09:04 +00003733 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003734 DstInfo =
3735 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003736
3737 // Make sure any stack arguments overlapping with where we're storing
3738 // are loaded before this eventual operation. Otherwise they'll be
3739 // clobbered.
3740 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3741 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003742 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003743
Mehdi Amini44ede332015-07-09 02:09:04 +00003744 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003745 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3746 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003747 }
3748
3749 if (Outs[i].Flags.isByVal()) {
3750 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003751 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003752 SDValue Cpy = DAG.getMemcpy(
3753 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003754 /*isVol = */ false, /*AlwaysInline = */ false,
3755 /*isTailCall = */ false,
3756 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003757
3758 MemOpChains.push_back(Cpy);
3759 } else {
3760 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3761 // promoted to a legal register type i32, we should truncate Arg back to
3762 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003763 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3764 VA.getValVT() == MVT::i16)
3765 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003766
Justin Lebar9c375812016-07-15 18:27:10 +00003767 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003768 MemOpChains.push_back(Store);
3769 }
3770 }
3771 }
3772
3773 if (!MemOpChains.empty())
3774 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3775
3776 // Build a sequence of copy-to-reg nodes chained together with token chain
3777 // and flag operands which copy the outgoing args into the appropriate regs.
3778 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003779 for (auto &RegToPass : RegsToPass) {
3780 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3781 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003782 InFlag = Chain.getValue(1);
3783 }
3784
3785 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3786 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3787 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003788 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3789 auto GV = G->getGlobal();
3790 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3791 AArch64II::MO_GOT) {
3792 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3793 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003794 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3795 assert(Subtarget->isTargetWindows() &&
3796 "Windows is the only supported COFF target");
3797 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003798 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003799 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003800 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3801 }
3802 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3803 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3804 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003805 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003806 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3807 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003808 } else {
3809 const char *Sym = S->getSymbol();
3810 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003811 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003812 }
3813
3814 // We don't usually want to end the call-sequence here because we would tidy
3815 // the frame up *after* the call, however in the ABI-changing tail-call case
3816 // we've carefully laid out the parameters so that when sp is reset they'll be
3817 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003818 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003819 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3820 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003821 InFlag = Chain.getValue(1);
3822 }
3823
3824 std::vector<SDValue> Ops;
3825 Ops.push_back(Chain);
3826 Ops.push_back(Callee);
3827
3828 if (IsTailCall) {
3829 // Each tail call may have to adjust the stack by a different amount, so
3830 // this information must travel along with the operation for eventual
3831 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003832 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003833 }
3834
3835 // Add argument registers to the end of the list so that they are known live
3836 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003837 for (auto &RegToPass : RegsToPass)
3838 Ops.push_back(DAG.getRegister(RegToPass.first,
3839 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003840
3841 // Add a register mask operand representing the call-preserved registers.
3842 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003843 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003844 if (IsThisReturn) {
3845 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003846 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003847 if (!Mask) {
3848 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003849 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003850 }
3851 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003852 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003853
Tri Vo6c47c622018-09-22 22:17:50 +00003854 if (Subtarget->hasCustomCallingConv())
3855 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3856
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003857 if (TRI->isAnyArgRegReserved(MF))
3858 TRI->emitReservedArgRegCallError(MF);
3859
Tim Northover3b0846e2014-05-24 12:50:23 +00003860 assert(Mask && "Missing call preserved mask for calling convention");
3861 Ops.push_back(DAG.getRegisterMask(Mask));
3862
3863 if (InFlag.getNode())
3864 Ops.push_back(InFlag);
3865
3866 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3867
3868 // If we're doing a tall call, use a TC_RETURN here rather than an
3869 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003870 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003871 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003872 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003873 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003874
3875 // Returns a chain and a flag for retval copy to use.
3876 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3877 InFlag = Chain.getValue(1);
3878
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003879 uint64_t CalleePopBytes =
3880 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003881
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003882 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3883 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3884 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003885 if (!Ins.empty())
3886 InFlag = Chain.getValue(1);
3887
3888 // Handle result values, copying them out of physregs into vregs that we
3889 // return.
3890 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3891 InVals, IsThisReturn,
3892 IsThisReturn ? OutVals[0] : SDValue());
3893}
3894
3895bool AArch64TargetLowering::CanLowerReturn(
3896 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3897 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3898 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3899 ? RetCC_AArch64_WebKit_JS
3900 : RetCC_AArch64_AAPCS;
3901 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003902 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003903 return CCInfo.CheckReturn(Outs, RetCC);
3904}
3905
3906SDValue
3907AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3908 bool isVarArg,
3909 const SmallVectorImpl<ISD::OutputArg> &Outs,
3910 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003911 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003912 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3913 ? RetCC_AArch64_WebKit_JS
3914 : RetCC_AArch64_AAPCS;
3915 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003916 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3917 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003918 CCInfo.AnalyzeReturn(Outs, RetCC);
3919
3920 // Copy the result values into the output registers.
3921 SDValue Flag;
3922 SmallVector<SDValue, 4> RetOps(1, Chain);
3923 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3924 ++i, ++realRVLocIdx) {
3925 CCValAssign &VA = RVLocs[i];
3926 assert(VA.isRegLoc() && "Can only return in registers!");
3927 SDValue Arg = OutVals[realRVLocIdx];
3928
3929 switch (VA.getLocInfo()) {
3930 default:
3931 llvm_unreachable("Unknown loc info!");
3932 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003933 if (Outs[i].ArgVT == MVT::i1) {
3934 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3935 // value. This is strictly redundant on Darwin (which uses "zeroext
3936 // i1"), but will be optimised out before ISel.
3937 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3938 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3939 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003940 break;
3941 case CCValAssign::BCvt:
3942 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3943 break;
3944 }
3945
3946 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3947 Flag = Chain.getValue(1);
3948 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3949 }
Manman Rencbe4f942015-12-16 21:04:19 +00003950 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3951 const MCPhysReg *I =
3952 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3953 if (I) {
3954 for (; *I; ++I) {
3955 if (AArch64::GPR64RegClass.contains(*I))
3956 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3957 else if (AArch64::FPR64RegClass.contains(*I))
3958 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3959 else
3960 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3961 }
3962 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003963
3964 RetOps[0] = Chain; // Update chain.
3965
3966 // Add the flag if we have it.
3967 if (Flag.getNode())
3968 RetOps.push_back(Flag);
3969
3970 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3971}
3972
3973//===----------------------------------------------------------------------===//
3974// Other Lowering Code
3975//===----------------------------------------------------------------------===//
3976
Joel Jonesa7c4a522017-04-21 17:31:03 +00003977SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3978 SelectionDAG &DAG,
3979 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003980 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3981 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003982}
3983
3984SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3985 SelectionDAG &DAG,
3986 unsigned Flag) const {
3987 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3988}
3989
3990SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3991 SelectionDAG &DAG,
3992 unsigned Flag) const {
3993 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3994 N->getOffset(), Flag);
3995}
3996
3997SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3998 SelectionDAG &DAG,
3999 unsigned Flag) const {
4000 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4001}
4002
4003// (loadGOT sym)
4004template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004005SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4006 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004007 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004008 SDLoc DL(N);
4009 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004010 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004011 // FIXME: Once remat is capable of dealing with instructions with register
4012 // operands, expand this into two nodes instead of using a wrapper node.
4013 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4014}
4015
4016// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4017template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004018SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4019 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004020 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004021 SDLoc DL(N);
4022 EVT Ty = getPointerTy(DAG.getDataLayout());
4023 const unsigned char MO_NC = AArch64II::MO_NC;
4024 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004025 AArch64ISD::WrapperLarge, DL, Ty,
4026 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4027 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4028 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4029 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004030}
4031
4032// (addlow (adrp %hi(sym)) %lo(sym))
4033template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004034SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4035 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004036 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004037 SDLoc DL(N);
4038 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004039 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004040 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004041 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004042 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4043 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4044}
4045
David Green9dd1d452018-08-22 11:31:39 +00004046// (adr sym)
4047template <class NodeTy>
4048SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4049 unsigned Flags) const {
4050 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4051 SDLoc DL(N);
4052 EVT Ty = getPointerTy(DAG.getDataLayout());
4053 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4054 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4055}
4056
Tim Northover3b0846e2014-05-24 12:50:23 +00004057SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4058 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004059 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004060 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00004061 unsigned char OpFlags =
4062 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004063
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004064 if (OpFlags != AArch64II::MO_NO_FLAG)
4065 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4066 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004067
David Green9dd1d452018-08-22 11:31:39 +00004068 // This also catches the large code model case for Darwin, and tiny code
4069 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004070 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004071 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004072 }
4073
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004074 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004075 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004076 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004077 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004078 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004079 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004080 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004081 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004082 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4083 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004084 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004085 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4086 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4087 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004088}
4089
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004090/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004091/// and calls to compute the variable's address (for Darwin, currently) and
4092/// return an SDValue containing the final node.
4093
4094/// Darwin only has one TLS scheme which must be capable of dealing with the
4095/// fully general situation, in the worst case. This means:
4096/// + "extern __thread" declaration.
4097/// + Defined in a possibly unknown dynamic library.
4098///
4099/// The general system is that each __thread variable has a [3 x i64] descriptor
4100/// which contains information used by the runtime to calculate the address. The
4101/// only part of this the compiler needs to know about is the first xword, which
4102/// contains a function pointer that must be called with the address of the
4103/// entire descriptor in "x0".
4104///
4105/// Since this descriptor may be in a different unit, in general even the
4106/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4107/// is:
4108/// adrp x0, _var@TLVPPAGE
4109/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4110/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4111/// ; the function pointer
4112/// blr x1 ; Uses descriptor address in x0
4113/// ; Address of _var is now in x0.
4114///
4115/// If the address of _var's descriptor *is* known to the linker, then it can
4116/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4117/// a slight efficiency gain.
4118SDValue
4119AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4120 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004121 assert(Subtarget->isTargetDarwin() &&
4122 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004123
4124 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004125 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004126 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4127
4128 SDValue TLVPAddr =
4129 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4130 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4131
4132 // The first entry in the descriptor is a function pointer that we must call
4133 // to obtain the address of the variable.
4134 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004135 SDValue FuncTLVGet = DAG.getLoad(
4136 MVT::i64, DL, Chain, DescAddr,
4137 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4138 /* Alignment = */ 8,
4139 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4140 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004141 Chain = FuncTLVGet.getValue(1);
4142
Matthias Braun941a7052016-07-28 18:40:00 +00004143 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4144 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004145
4146 // TLS calls preserve all registers except those that absolutely must be
4147 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4148 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004149 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4150 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4151 if (Subtarget->hasCustomCallingConv())
4152 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004153
4154 // Finally, we can make the call. This is just a degenerate version of a
4155 // normal AArch64 call node: x0 takes the address of the descriptor, and
4156 // returns the address of the variable in this thread.
4157 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4158 Chain =
4159 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4160 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4161 DAG.getRegisterMask(Mask), Chain.getValue(1));
4162 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4163}
4164
4165/// When accessing thread-local variables under either the general-dynamic or
4166/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4167/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004168/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004169///
Kristof Beylsaea84612015-03-04 09:12:08 +00004170/// The sequence is:
4171/// adrp x0, :tlsdesc:var
4172/// ldr x1, [x0, #:tlsdesc_lo12:var]
4173/// add x0, x0, #:tlsdesc_lo12:var
4174/// .tlsdesccall var
4175/// blr x1
4176/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004177///
Kristof Beylsaea84612015-03-04 09:12:08 +00004178/// The above sequence must be produced unscheduled, to enable the linker to
4179/// optimize/relax this sequence.
4180/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4181/// above sequence, and expanded really late in the compilation flow, to ensure
4182/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004183SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4184 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004185 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004186 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004187
Kristof Beylsaea84612015-03-04 09:12:08 +00004188 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004189 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004190
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004191 Chain =
4192 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004193 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004194
4195 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4196}
4197
4198SDValue
4199AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4200 SelectionDAG &DAG) const {
4201 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004202 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4203 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004204 // Different choices can be made for the maximum size of the TLS area for a
4205 // module. For the small address model, the default TLS size is 16MiB and the
4206 // maximum TLS size is 4GiB.
4207 // FIXME: add -mtls-size command line option and make it control the 16MiB
4208 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004209 // FIXME: add tiny codemodel support. We currently generate the same code as
4210 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004211 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4212
4213 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004214
Kristof Beylsaea84612015-03-04 09:12:08 +00004215 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4216 if (Model == TLSModel::LocalDynamic)
4217 Model = TLSModel::GeneralDynamic;
4218 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004219
4220 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004221 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004222 SDLoc DL(Op);
4223 const GlobalValue *GV = GA->getGlobal();
4224
4225 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4226
4227 if (Model == TLSModel::LocalExec) {
4228 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004229 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004230 SDValue LoVar = DAG.getTargetGlobalAddress(
4231 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004232 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004233
Kristof Beylsaea84612015-03-04 09:12:08 +00004234 SDValue TPWithOff_lo =
4235 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004236 HiVar,
4237 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004238 0);
4239 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004240 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4241 LoVar,
4242 DAG.getTargetConstant(0, DL, MVT::i32)),
4243 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004244 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004245 } else if (Model == TLSModel::InitialExec) {
4246 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4247 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4248 } else if (Model == TLSModel::LocalDynamic) {
4249 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4250 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4251 // the beginning of the module's TLS region, followed by a DTPREL offset
4252 // calculation.
4253
4254 // These accesses will need deduplicating if there's more than one.
4255 AArch64FunctionInfo *MFI =
4256 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4257 MFI->incNumLocalDynamicTLSAccesses();
4258
Tim Northover3b0846e2014-05-24 12:50:23 +00004259 // The call needs a relocation too for linker relaxation. It doesn't make
4260 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4261 // the address.
4262 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4263 AArch64II::MO_TLS);
4264
4265 // Now we can calculate the offset from TPIDR_EL0 to this module's
4266 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004267 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004268
4269 // Now use :dtprel_whatever: operations to calculate this variable's offset
4270 // in its thread-storage area.
4271 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004272 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004273 SDValue LoVar = DAG.getTargetGlobalAddress(
4274 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004275 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4276
Kristof Beylsaea84612015-03-04 09:12:08 +00004277 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004278 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004279 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004280 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4281 DAG.getTargetConstant(0, DL, MVT::i32)),
4282 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004283 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004284 // The call needs a relocation too for linker relaxation. It doesn't make
4285 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4286 // the address.
4287 SDValue SymAddr =
4288 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4289
4290 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004291 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004292 } else
4293 llvm_unreachable("Unsupported ELF TLS access model");
4294
4295 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4296}
4297
Martin Storsjocc240962018-03-10 19:05:21 +00004298SDValue
4299AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4300 SelectionDAG &DAG) const {
4301 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4302
4303 SDValue Chain = DAG.getEntryNode();
4304 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4305 SDLoc DL(Op);
4306
4307 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4308
4309 // Load the ThreadLocalStoragePointer from the TEB
4310 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4311 SDValue TLSArray =
4312 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4313 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4314 Chain = TLSArray.getValue(1);
4315
4316 // Load the TLS index from the C runtime;
4317 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4318 // This also does the same as LOADgot, but using a generic i32 load,
4319 // while LOADgot only loads i64.
4320 SDValue TLSIndexHi =
4321 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4322 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4323 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4324 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4325 SDValue TLSIndex =
4326 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4327 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4328 Chain = TLSIndex.getValue(1);
4329
4330 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4331 // offset into the TLSArray.
4332 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4333 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4334 DAG.getConstant(3, DL, PtrVT));
4335 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4336 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4337 MachinePointerInfo());
4338 Chain = TLS.getValue(1);
4339
4340 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4341 const GlobalValue *GV = GA->getGlobal();
4342 SDValue TGAHi = DAG.getTargetGlobalAddress(
4343 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4344 SDValue TGALo = DAG.getTargetGlobalAddress(
4345 GV, DL, PtrVT, 0,
4346 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4347
4348 // Add the offset from the start of the .tls section (section base).
4349 SDValue Addr =
4350 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4351 DAG.getTargetConstant(0, DL, MVT::i32)),
4352 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004353 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004354 return Addr;
4355}
4356
Tim Northover3b0846e2014-05-24 12:50:23 +00004357SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4358 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004359 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004360 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004361 return LowerToTLSEmulatedModel(GA, DAG);
4362
Tim Northover3b0846e2014-05-24 12:50:23 +00004363 if (Subtarget->isTargetDarwin())
4364 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004365 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004366 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004367 if (Subtarget->isTargetWindows())
4368 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004369
4370 llvm_unreachable("Unexpected platform trying to use TLS");
4371}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004372
Tim Northover3b0846e2014-05-24 12:50:23 +00004373SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4374 SDValue Chain = Op.getOperand(0);
4375 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4376 SDValue LHS = Op.getOperand(2);
4377 SDValue RHS = Op.getOperand(3);
4378 SDValue Dest = Op.getOperand(4);
4379 SDLoc dl(Op);
4380
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004381 MachineFunction &MF = DAG.getMachineFunction();
4382 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4383 // will not be produced, as they are conditional branch instructions that do
4384 // not set flags.
4385 bool ProduceNonFlagSettingCondBr =
4386 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4387
Tim Northover3b0846e2014-05-24 12:50:23 +00004388 // Handle f128 first, since lowering it will result in comparing the return
4389 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4390 // is expecting to deal with.
4391 if (LHS.getValueType() == MVT::f128) {
4392 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4393
4394 // If softenSetCCOperands returned a scalar, we need to compare the result
4395 // against zero to select between true and false values.
4396 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004397 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004398 CC = ISD::SETNE;
4399 }
4400 }
4401
4402 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4403 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004404 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4405 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004406 // Only lower legal XALUO ops.
4407 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4408 return SDValue();
4409
4410 // The actual operation with overflow check.
4411 AArch64CC::CondCode OFCC;
4412 SDValue Value, Overflow;
4413 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4414
4415 if (CC == ISD::SETNE)
4416 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004417 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004418
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004419 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4420 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004421 }
4422
4423 if (LHS.getValueType().isInteger()) {
4424 assert((LHS.getValueType() == RHS.getValueType()) &&
4425 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4426
4427 // If the RHS of the comparison is zero, we can potentially fold this
4428 // to a specialized branch.
4429 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004430 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004431 if (CC == ISD::SETEQ) {
4432 // See if we can use a TBZ to fold in an AND as well.
4433 // TBZ has a smaller branch displacement than CBZ. If the offset is
4434 // out of bounds, a late MI-layer pass rewrites branches.
4435 // 403.gcc is an example that hits this case.
4436 if (LHS.getOpcode() == ISD::AND &&
4437 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4438 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4439 SDValue Test = LHS.getOperand(0);
4440 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004441 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004442 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4443 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004444 }
4445
4446 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4447 } else if (CC == ISD::SETNE) {
4448 // See if we can use a TBZ to fold in an AND as well.
4449 // TBZ has a smaller branch displacement than CBZ. If the offset is
4450 // out of bounds, a late MI-layer pass rewrites branches.
4451 // 403.gcc is an example that hits this case.
4452 if (LHS.getOpcode() == ISD::AND &&
4453 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4454 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4455 SDValue Test = LHS.getOperand(0);
4456 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004457 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004458 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4459 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004460 }
4461
4462 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004463 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4464 // Don't combine AND since emitComparison converts the AND to an ANDS
4465 // (a.k.a. TST) and the test in the test bit and branch instruction
4466 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004467 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004468 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004469 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004470 }
4471 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004472 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004473 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004474 // Don't combine AND since emitComparison converts the AND to an ANDS
4475 // (a.k.a. TST) and the test in the test bit and branch instruction
4476 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004477 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004478 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004479 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004480 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004481
4482 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004483 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004484 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4485 Cmp);
4486 }
4487
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004488 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4489 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004490
4491 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4492 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004493 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004494 AArch64CC::CondCode CC1, CC2;
4495 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004496 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004497 SDValue BR1 =
4498 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4499 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004500 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004501 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4502 Cmp);
4503 }
4504
4505 return BR1;
4506}
4507
4508SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4509 SelectionDAG &DAG) const {
4510 EVT VT = Op.getValueType();
4511 SDLoc DL(Op);
4512
4513 SDValue In1 = Op.getOperand(0);
4514 SDValue In2 = Op.getOperand(1);
4515 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004516
4517 if (SrcVT.bitsLT(VT))
4518 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4519 else if (SrcVT.bitsGT(VT))
4520 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004521
4522 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004523 uint64_t EltMask;
4524 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004525
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004526 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004527 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004528 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004529 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004530 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004531 DAG.getUNDEF(VecVT), In2);
4532 } else {
4533 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4534 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4535 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004536 };
4537
4538 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4539 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4540 EltMask = 0x80000000ULL;
4541 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004542 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004543 VecVT = MVT::v2i64;
4544
Eric Christopher572e03a2015-06-19 01:53:21 +00004545 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004546 // immediate moves cannot materialize that in a single instruction for
4547 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004548 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004549
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004550 setVecVal(AArch64::dsub);
4551 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4552 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4553 EltMask = 0x8000ULL;
4554 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004555 } else {
4556 llvm_unreachable("Invalid type for copysign!");
4557 }
4558
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004559 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004560
4561 // If we couldn't materialize the mask above, then the mask vector will be
4562 // the zero vector, and we need to negate it here.
4563 if (VT == MVT::f64 || VT == MVT::v2f64) {
4564 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4565 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4566 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4567 }
4568
4569 SDValue Sel =
4570 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4571
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004572 if (VT == MVT::f16)
4573 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004574 if (VT == MVT::f32)
4575 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4576 else if (VT == MVT::f64)
4577 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4578 else
4579 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4580}
4581
4582SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004583 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004584 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004585 return SDValue();
4586
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004587 if (!Subtarget->hasNEON())
4588 return SDValue();
4589
Tim Northover3b0846e2014-05-24 12:50:23 +00004590 // While there is no integer popcount instruction, it can
4591 // be more efficiently lowered to the following sequence that uses
4592 // AdvSIMD registers/instructions as long as the copies to/from
4593 // the AdvSIMD registers are cheap.
4594 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4595 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4596 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4597 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4598 SDValue Val = Op.getOperand(0);
4599 SDLoc DL(Op);
4600 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004601
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004602 if (VT == MVT::i32 || VT == MVT::i64) {
4603 if (VT == MVT::i32)
4604 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4605 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004606
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004607 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4608 SDValue UaddLV = DAG.getNode(
4609 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4610 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004611
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004612 if (VT == MVT::i64)
4613 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4614 return UaddLV;
4615 }
4616
4617 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4618 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4619 "Unexpected type for custom ctpop lowering");
4620
4621 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4622 Val = DAG.getBitcast(VT8Bit, Val);
4623 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4624
4625 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4626 unsigned EltSize = 8;
4627 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4628 while (EltSize != VT.getScalarSizeInBits()) {
4629 EltSize *= 2;
4630 NumElts /= 2;
4631 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4632 Val = DAG.getNode(
4633 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4634 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4635 }
4636
4637 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004638}
4639
4640SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4641
4642 if (Op.getValueType().isVector())
4643 return LowerVSETCC(Op, DAG);
4644
4645 SDValue LHS = Op.getOperand(0);
4646 SDValue RHS = Op.getOperand(1);
4647 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4648 SDLoc dl(Op);
4649
4650 // We chose ZeroOrOneBooleanContents, so use zero and one.
4651 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004652 SDValue TVal = DAG.getConstant(1, dl, VT);
4653 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004654
4655 // Handle f128 first, since one possible outcome is a normal integer
4656 // comparison which gets picked up by the next if statement.
4657 if (LHS.getValueType() == MVT::f128) {
4658 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4659
4660 // If softenSetCCOperands returned a scalar, use it.
4661 if (!RHS.getNode()) {
4662 assert(LHS.getValueType() == Op.getValueType() &&
4663 "Unexpected setcc expansion!");
4664 return LHS;
4665 }
4666 }
4667
4668 if (LHS.getValueType().isInteger()) {
4669 SDValue CCVal;
4670 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004671 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004672
4673 // Note that we inverted the condition above, so we reverse the order of
4674 // the true and false operands here. This will allow the setcc to be
4675 // matched to a single CSINC instruction.
4676 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4677 }
4678
4679 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004680 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4681 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004682
4683 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4684 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004685 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004686
4687 AArch64CC::CondCode CC1, CC2;
4688 changeFPCCToAArch64CC(CC, CC1, CC2);
4689 if (CC2 == AArch64CC::AL) {
4690 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004691 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004692
4693 // Note that we inverted the condition above, so we reverse the order of
4694 // the true and false operands here. This will allow the setcc to be
4695 // matched to a single CSINC instruction.
4696 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4697 } else {
4698 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4699 // totally clean. Some of them require two CSELs to implement. As is in
4700 // this case, we emit the first CSEL and then emit a second using the output
4701 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4702
4703 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004704 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004705 SDValue CS1 =
4706 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4707
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004708 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004709 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4710 }
4711}
4712
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004713SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4714 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004715 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004716 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004717 // Handle f128 first, because it will result in a comparison of some RTLIB
4718 // call result against zero.
4719 if (LHS.getValueType() == MVT::f128) {
4720 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4721
4722 // If softenSetCCOperands returned a scalar, we need to compare the result
4723 // against zero to select between true and false values.
4724 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004725 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004726 CC = ISD::SETNE;
4727 }
4728 }
4729
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004730 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004731 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004732 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4733 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4734 }
4735
4736 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004737 if (LHS.getValueType().isInteger()) {
4738 assert((LHS.getValueType() == RHS.getValueType()) &&
4739 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4740
4741 unsigned Opcode = AArch64ISD::CSEL;
4742
4743 // If both the TVal and the FVal are constants, see if we can swap them in
4744 // order to for a CSINV or CSINC out of them.
4745 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4746 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4747
4748 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4749 std::swap(TVal, FVal);
4750 std::swap(CTVal, CFVal);
4751 CC = ISD::getSetCCInverse(CC, true);
4752 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4753 std::swap(TVal, FVal);
4754 std::swap(CTVal, CFVal);
4755 CC = ISD::getSetCCInverse(CC, true);
4756 } else if (TVal.getOpcode() == ISD::XOR) {
4757 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4758 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004759 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004760 std::swap(TVal, FVal);
4761 std::swap(CTVal, CFVal);
4762 CC = ISD::getSetCCInverse(CC, true);
4763 }
4764 } else if (TVal.getOpcode() == ISD::SUB) {
4765 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4766 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004767 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004768 std::swap(TVal, FVal);
4769 std::swap(CTVal, CFVal);
4770 CC = ISD::getSetCCInverse(CC, true);
4771 }
4772 } else if (CTVal && CFVal) {
4773 const int64_t TrueVal = CTVal->getSExtValue();
4774 const int64_t FalseVal = CFVal->getSExtValue();
4775 bool Swap = false;
4776
4777 // If both TVal and FVal are constants, see if FVal is the
4778 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4779 // instead of a CSEL in that case.
4780 if (TrueVal == ~FalseVal) {
4781 Opcode = AArch64ISD::CSINV;
4782 } else if (TrueVal == -FalseVal) {
4783 Opcode = AArch64ISD::CSNEG;
4784 } else if (TVal.getValueType() == MVT::i32) {
4785 // If our operands are only 32-bit wide, make sure we use 32-bit
4786 // arithmetic for the check whether we can use CSINC. This ensures that
4787 // the addition in the check will wrap around properly in case there is
4788 // an overflow (which would not be the case if we do the check with
4789 // 64-bit arithmetic).
4790 const uint32_t TrueVal32 = CTVal->getZExtValue();
4791 const uint32_t FalseVal32 = CFVal->getZExtValue();
4792
4793 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4794 Opcode = AArch64ISD::CSINC;
4795
4796 if (TrueVal32 > FalseVal32) {
4797 Swap = true;
4798 }
4799 }
4800 // 64-bit check whether we can use CSINC.
4801 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4802 Opcode = AArch64ISD::CSINC;
4803
4804 if (TrueVal > FalseVal) {
4805 Swap = true;
4806 }
4807 }
4808
4809 // Swap TVal and FVal if necessary.
4810 if (Swap) {
4811 std::swap(TVal, FVal);
4812 std::swap(CTVal, CFVal);
4813 CC = ISD::getSetCCInverse(CC, true);
4814 }
4815
4816 if (Opcode != AArch64ISD::CSEL) {
4817 // Drop FVal since we can get its value by simply inverting/negating
4818 // TVal.
4819 FVal = TVal;
4820 }
4821 }
4822
Chad Rosier58f505b2016-08-26 18:05:50 +00004823 // Avoid materializing a constant when possible by reusing a known value in
4824 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004825 // is one, zero or negative one in the case of a CSEL. We can always
4826 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4827 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004828 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4829 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4830 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4831 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4832 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4833 // "a != C ? x : a" to avoid materializing C.
4834 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4835 TVal = LHS;
4836 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4837 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004838 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4839 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4840 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4841 // avoid materializing C.
4842 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4843 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4844 Opcode = AArch64ISD::CSINV;
4845 TVal = LHS;
4846 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4847 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004848 }
4849
Tim Northover3b0846e2014-05-24 12:50:23 +00004850 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004851 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004852 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004853 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4854 }
4855
4856 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004857 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4858 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004859 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004860 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004861 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004862
4863 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4864 // clean. Some of them require two CSELs to implement.
4865 AArch64CC::CondCode CC1, CC2;
4866 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004867
4868 if (DAG.getTarget().Options.UnsafeFPMath) {
4869 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4870 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4871 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4872 if (RHSVal && RHSVal->isZero()) {
4873 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4874 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4875
4876 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004877 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004878 TVal = LHS;
4879 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004880 CFVal && CFVal->isZero() &&
4881 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004882 FVal = LHS;
4883 }
4884 }
4885
4886 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004887 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004888 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4889
4890 // If we need a second CSEL, emit it, using the output of the first as the
4891 // RHS. We're effectively OR'ing the two CC's together.
4892 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004893 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004894 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4895 }
4896
4897 // Otherwise, return the output of the first CSEL.
4898 return CS1;
4899}
4900
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004901SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4902 SelectionDAG &DAG) const {
4903 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4904 SDValue LHS = Op.getOperand(0);
4905 SDValue RHS = Op.getOperand(1);
4906 SDValue TVal = Op.getOperand(2);
4907 SDValue FVal = Op.getOperand(3);
4908 SDLoc DL(Op);
4909 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4910}
4911
4912SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4913 SelectionDAG &DAG) const {
4914 SDValue CCVal = Op->getOperand(0);
4915 SDValue TVal = Op->getOperand(1);
4916 SDValue FVal = Op->getOperand(2);
4917 SDLoc DL(Op);
4918
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004919 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4920 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004921 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004922 // Only lower legal XALUO ops.
4923 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4924 return SDValue();
4925
4926 AArch64CC::CondCode OFCC;
4927 SDValue Value, Overflow;
4928 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004929 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004930
4931 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4932 CCVal, Overflow);
4933 }
4934
4935 // Lower it the same way as we would lower a SELECT_CC node.
4936 ISD::CondCode CC;
4937 SDValue LHS, RHS;
4938 if (CCVal.getOpcode() == ISD::SETCC) {
4939 LHS = CCVal.getOperand(0);
4940 RHS = CCVal.getOperand(1);
4941 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4942 } else {
4943 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004944 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004945 CC = ISD::SETNE;
4946 }
4947 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4948}
4949
Tim Northover3b0846e2014-05-24 12:50:23 +00004950SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4951 SelectionDAG &DAG) const {
4952 // Jump table entries as PC relative offsets. No additional tweaking
4953 // is necessary here. Just get the address of the jump table.
4954 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004955
4956 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4957 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004958 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004959 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4960 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004961 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004962 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004963}
4964
Tim Northover1c353412018-10-24 20:19:09 +00004965SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
4966 SelectionDAG &DAG) const {
4967 // Jump table entries as PC relative offsets. No additional tweaking
4968 // is necessary here. Just get the address of the jump table.
4969 SDLoc DL(Op);
4970 SDValue JT = Op.getOperand(1);
4971 SDValue Entry = Op.getOperand(2);
4972 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
4973
4974 SDNode *Dest =
4975 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
4976 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
4977 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
4978 SDValue(Dest, 0));
4979}
4980
Tim Northover3b0846e2014-05-24 12:50:23 +00004981SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4982 SelectionDAG &DAG) const {
4983 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004984
4985 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4986 // Use the GOT for the large code model on iOS.
4987 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004988 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004989 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004990 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004991 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4992 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004993 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004994 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004995 }
4996}
4997
4998SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4999 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005000 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005001 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5002 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005003 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005004 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5005 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005006 }
David Green9dd1d452018-08-22 11:31:39 +00005007 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005008}
5009
5010SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5011 SelectionDAG &DAG) const {
5012 AArch64FunctionInfo *FuncInfo =
5013 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5014
5015 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005016 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5017 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005018 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5019 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005020 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005021}
5022
Martin Storsjo68266fa2017-07-13 17:03:12 +00005023SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5024 SelectionDAG &DAG) const {
5025 AArch64FunctionInfo *FuncInfo =
5026 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5027
5028 SDLoc DL(Op);
5029 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5030 ? FuncInfo->getVarArgsGPRIndex()
5031 : FuncInfo->getVarArgsStackIndex(),
5032 getPointerTy(DAG.getDataLayout()));
5033 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5034 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5035 MachinePointerInfo(SV));
5036}
5037
Tim Northover3b0846e2014-05-24 12:50:23 +00005038SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5039 SelectionDAG &DAG) const {
5040 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5041 // Standard, section B.3.
5042 MachineFunction &MF = DAG.getMachineFunction();
5043 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005044 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005045 SDLoc DL(Op);
5046
5047 SDValue Chain = Op.getOperand(0);
5048 SDValue VAList = Op.getOperand(1);
5049 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5050 SmallVector<SDValue, 4> MemOps;
5051
5052 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005053 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005054 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005055 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005056
5057 // void *__gr_top at offset 8
5058 int GPRSize = FuncInfo->getVarArgsGPRSize();
5059 if (GPRSize > 0) {
5060 SDValue GRTop, GRTopAddr;
5061
Mehdi Amini44ede332015-07-09 02:09:04 +00005062 GRTopAddr =
5063 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005064
Mehdi Amini44ede332015-07-09 02:09:04 +00005065 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5066 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5067 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005068
5069 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005070 MachinePointerInfo(SV, 8),
5071 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005072 }
5073
5074 // void *__vr_top at offset 16
5075 int FPRSize = FuncInfo->getVarArgsFPRSize();
5076 if (FPRSize > 0) {
5077 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005078 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5079 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005080
Mehdi Amini44ede332015-07-09 02:09:04 +00005081 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5082 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5083 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005084
5085 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005086 MachinePointerInfo(SV, 16),
5087 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005088 }
5089
5090 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005091 SDValue GROffsAddr =
5092 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005093 MemOps.push_back(DAG.getStore(
5094 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5095 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005096
5097 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005098 SDValue VROffsAddr =
5099 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005100 MemOps.push_back(DAG.getStore(
5101 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5102 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005103
5104 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5105}
5106
5107SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5108 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005109 MachineFunction &MF = DAG.getMachineFunction();
5110
Matthias Braunf1caa282017-12-15 22:22:58 +00005111 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005112 return LowerWin64_VASTART(Op, DAG);
5113 else if (Subtarget->isTargetDarwin())
5114 return LowerDarwin_VASTART(Op, DAG);
5115 else
5116 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005117}
5118
5119SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5120 SelectionDAG &DAG) const {
5121 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5122 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005123 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005124 unsigned VaListSize =
5125 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005126 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5127 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5128
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005129 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5130 Op.getOperand(2),
5131 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005132 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005133 MachinePointerInfo(SrcSV));
5134}
5135
5136SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5137 assert(Subtarget->isTargetDarwin() &&
5138 "automatic va_arg instruction only works on Darwin");
5139
5140 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5141 EVT VT = Op.getValueType();
5142 SDLoc DL(Op);
5143 SDValue Chain = Op.getOperand(0);
5144 SDValue Addr = Op.getOperand(1);
5145 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005146 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005147
Justin Lebar9c375812016-07-15 18:27:10 +00005148 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005149 Chain = VAList.getValue(1);
5150
5151 if (Align > 8) {
5152 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005153 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5154 DAG.getConstant(Align - 1, DL, PtrVT));
5155 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5156 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005157 }
5158
5159 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005160 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005161
5162 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5163 // up to 64 bits. At the very least, we have to increase the striding of the
5164 // vaargs list to match this, and for FP values we need to introduce
5165 // FP_ROUND nodes as well.
5166 if (VT.isInteger() && !VT.isVector())
5167 ArgSize = 8;
5168 bool NeedFPTrunc = false;
5169 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5170 ArgSize = 8;
5171 NeedFPTrunc = true;
5172 }
5173
5174 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005175 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5176 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005177 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005178 SDValue APStore =
5179 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005180
5181 // Load the actual argument out of the pointer VAList
5182 if (NeedFPTrunc) {
5183 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005184 SDValue WideFP =
5185 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005186 // Round the value down to an f32.
5187 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005188 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005189 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5190 // Merge the rounded value with the chain output of the load.
5191 return DAG.getMergeValues(Ops, DL);
5192 }
5193
Justin Lebar9c375812016-07-15 18:27:10 +00005194 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005195}
5196
5197SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5198 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005199 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5200 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005201
5202 EVT VT = Op.getValueType();
5203 SDLoc DL(Op);
5204 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5205 SDValue FrameAddr =
5206 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5207 while (Depth--)
5208 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005209 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005210 return FrameAddr;
5211}
5212
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005213SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5214 SelectionDAG &DAG) const {
5215 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5216
5217 EVT VT = getPointerTy(DAG.getDataLayout());
5218 SDLoc DL(Op);
5219 int FI = MFI.CreateFixedObject(4, 0, false);
5220 return DAG.getFrameIndex(FI, VT);
5221}
5222
Petr Hosekfcbec022019-02-13 17:28:47 +00005223#define GET_REGISTER_MATCHER
5224#include "AArch64GenAsmMatcher.inc"
5225
Tim Northover3b0846e2014-05-24 12:50:23 +00005226// FIXME? Maybe this could be a TableGen attribute on some registers and
5227// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005228unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5229 SelectionDAG &DAG) const {
Petr Hosekfcbec022019-02-13 17:28:47 +00005230 unsigned Reg = MatchRegisterName(RegName);
5231 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5232 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5233 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5234 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5235 Reg = 0;
5236 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005237 if (Reg)
5238 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005239 report_fatal_error(Twine("Invalid register name \""
5240 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005241}
5242
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005243SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5244 SelectionDAG &DAG) const {
5245 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5246
5247 EVT VT = Op.getValueType();
5248 SDLoc DL(Op);
5249
5250 SDValue FrameAddr =
5251 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5252 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5253
5254 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5255}
5256
Tim Northover3b0846e2014-05-24 12:50:23 +00005257SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5258 SelectionDAG &DAG) const {
5259 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005260 MachineFrameInfo &MFI = MF.getFrameInfo();
5261 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005262
5263 EVT VT = Op.getValueType();
5264 SDLoc DL(Op);
5265 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5266 if (Depth) {
5267 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005268 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005269 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5270 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005271 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005272 }
5273
5274 // Return LR, which contains the return address. Mark it an implicit live-in.
5275 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5276 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5277}
5278
5279/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5280/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5281SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5282 SelectionDAG &DAG) const {
5283 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5284 EVT VT = Op.getValueType();
5285 unsigned VTBits = VT.getSizeInBits();
5286 SDLoc dl(Op);
5287 SDValue ShOpLo = Op.getOperand(0);
5288 SDValue ShOpHi = Op.getOperand(1);
5289 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005290 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5291
5292 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5293
5294 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005295 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005296 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5297
5298 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5299 // is "undef". We wanted 0, so CSEL it directly.
5300 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5301 ISD::SETEQ, dl, DAG);
5302 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5303 HiBitsForLo =
5304 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5305 HiBitsForLo, CCVal, Cmp);
5306
Tim Northover3b0846e2014-05-24 12:50:23 +00005307 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005308 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005309
Tim Northoverf3be9d52015-12-02 00:33:54 +00005310 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5311 SDValue LoForNormalShift =
5312 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005313
Tim Northoverf3be9d52015-12-02 00:33:54 +00005314 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5315 dl, DAG);
5316 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5317 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5318 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5319 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005320
5321 // AArch64 shifts larger than the register width are wrapped rather than
5322 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005323 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5324 SDValue HiForBigShift =
5325 Opc == ISD::SRA
5326 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5327 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5328 : DAG.getConstant(0, dl, VT);
5329 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5330 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005331
5332 SDValue Ops[2] = { Lo, Hi };
5333 return DAG.getMergeValues(Ops, dl);
5334}
5335
5336/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5337/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5338SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005339 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005340 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5341 EVT VT = Op.getValueType();
5342 unsigned VTBits = VT.getSizeInBits();
5343 SDLoc dl(Op);
5344 SDValue ShOpLo = Op.getOperand(0);
5345 SDValue ShOpHi = Op.getOperand(1);
5346 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005347
5348 assert(Op.getOpcode() == ISD::SHL_PARTS);
5349 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005350 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005351 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5352
5353 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5354 // is "undef". We wanted 0, so CSEL it directly.
5355 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5356 ISD::SETEQ, dl, DAG);
5357 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5358 LoBitsForHi =
5359 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5360 LoBitsForHi, CCVal, Cmp);
5361
Tim Northover3b0846e2014-05-24 12:50:23 +00005362 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005363 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005364 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5365 SDValue HiForNormalShift =
5366 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005367
Tim Northoverf3be9d52015-12-02 00:33:54 +00005368 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005369
Tim Northoverf3be9d52015-12-02 00:33:54 +00005370 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5371 dl, DAG);
5372 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5373 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5374 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005375
5376 // AArch64 shifts of larger than register sizes are wrapped rather than
5377 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005378 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5379 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5380 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5381 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005382
5383 SDValue Ops[2] = { Lo, Hi };
5384 return DAG.getMergeValues(Ops, dl);
5385}
5386
5387bool AArch64TargetLowering::isOffsetFoldingLegal(
5388 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005389 // Offsets are folded in the DAG combine rather than here so that we can
5390 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005391 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005392}
5393
5394bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005395 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005396 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5397 // 16-bit case when target has full fp16 support.
5398 // FIXME: We should be able to handle f128 as well with a clever lowering.
5399 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005400 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005401 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005402 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005403 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005404 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005405 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5406 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5407 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005408
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005409 // If we can not materialize in immediate field for fmov, check if the
5410 // value can be encoded as the immediate operand of a logical instruction.
5411 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5412 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32))
5413 IsLegal = AArch64_AM::isAnyMOVWMovAlias(ImmInt.getZExtValue(),
5414 VT.getSizeInBits());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005415
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005416 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5417 << " imm value: "; Imm.dump(););
5418 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005419}
5420
5421//===----------------------------------------------------------------------===//
5422// AArch64 Optimization Hooks
5423//===----------------------------------------------------------------------===//
5424
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005425static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5426 SDValue Operand, SelectionDAG &DAG,
5427 int &ExtraSteps) {
5428 EVT VT = Operand.getValueType();
5429 if (ST->hasNEON() &&
5430 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5431 VT == MVT::f32 || VT == MVT::v1f32 ||
5432 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5433 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5434 // For the reciprocal estimates, convergence is quadratic, so the number
5435 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5436 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5437 // the result for float (23 mantissa bits) is 2 and for double (52
5438 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005439 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005440
5441 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5442 }
5443
5444 return SDValue();
5445}
5446
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005447SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5448 SelectionDAG &DAG, int Enabled,
5449 int &ExtraSteps,
5450 bool &UseOneConst,
5451 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005452 if (Enabled == ReciprocalEstimate::Enabled ||
5453 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5454 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5455 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005456 SDLoc DL(Operand);
5457 EVT VT = Operand.getValueType();
5458
5459 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005460 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005461
5462 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5463 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5464 for (int i = ExtraSteps; i > 0; --i) {
5465 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005466 Flags);
5467 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5468 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005469 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005470 if (!Reciprocal) {
5471 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5472 VT);
5473 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5474 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5475
Amara Emersond28f0cd42017-05-01 15:17:51 +00005476 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005477 // Correct the result if the operand is 0.0.
5478 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5479 VT, Eq, Operand, Estimate);
5480 }
5481
5482 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005483 return Estimate;
5484 }
5485
5486 return SDValue();
5487}
5488
5489SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5490 SelectionDAG &DAG, int Enabled,
5491 int &ExtraSteps) const {
5492 if (Enabled == ReciprocalEstimate::Enabled)
5493 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005494 DAG, ExtraSteps)) {
5495 SDLoc DL(Operand);
5496 EVT VT = Operand.getValueType();
5497
5498 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005499 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005500
5501 // Newton reciprocal iteration: E * (2 - X * E)
5502 // AArch64 reciprocal iteration instruction: (2 - M * N)
5503 for (int i = ExtraSteps; i > 0; --i) {
5504 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005505 Estimate, Flags);
5506 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005507 }
5508
5509 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005510 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005511 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005512
5513 return SDValue();
5514}
5515
Tim Northover3b0846e2014-05-24 12:50:23 +00005516//===----------------------------------------------------------------------===//
5517// AArch64 Inline Assembly Support
5518//===----------------------------------------------------------------------===//
5519
5520// Table of Constraints
5521// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005522// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005523//
5524// r - A general register
5525// w - An FP/SIMD register of some size in the range v0-v31
5526// x - An FP/SIMD register of some size in the range v0-v15
5527// I - Constant that can be used with an ADD instruction
5528// J - Constant that can be used with a SUB instruction
5529// K - Constant that can be used with a 32-bit logical instruction
5530// L - Constant that can be used with a 64-bit logical instruction
5531// M - Constant that can be used as a 32-bit MOV immediate
5532// N - Constant that can be used as a 64-bit MOV immediate
5533// Q - A memory reference with base register and no offset
5534// S - A symbolic address
5535// Y - Floating point constant zero
5536// Z - Integer constant zero
5537//
5538// Note that general register operands will be output using their 64-bit x
5539// register name, whatever the size of the variable, unless the asm operand
5540// is prefixed by the %w modifier. Floating-point and SIMD register operands
5541// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5542// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005543const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5544 // At this point, we have to lower this constraint to something else, so we
5545 // lower it to an "r" or "w". However, by doing this we will force the result
5546 // to be in register, while the X constraint is much more permissive.
5547 //
5548 // Although we are correct (we are free to emit anything, without
5549 // constraints), we might break use cases that would expect us to be more
5550 // efficient and emit something else.
5551 if (!Subtarget->hasFPARMv8())
5552 return "r";
5553
5554 if (ConstraintVT.isFloatingPoint())
5555 return "w";
5556
5557 if (ConstraintVT.isVector() &&
5558 (ConstraintVT.getSizeInBits() == 64 ||
5559 ConstraintVT.getSizeInBits() == 128))
5560 return "w";
5561
5562 return "r";
5563}
Tim Northover3b0846e2014-05-24 12:50:23 +00005564
5565/// getConstraintType - Given a constraint letter, return the type of
5566/// constraint it is for this target.
5567AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005568AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005569 if (Constraint.size() == 1) {
5570 switch (Constraint[0]) {
5571 default:
5572 break;
5573 case 'z':
5574 return C_Other;
5575 case 'x':
5576 case 'w':
5577 return C_RegisterClass;
5578 // An address with a single base register. Due to the way we
5579 // currently handle addresses it is the same as 'r'.
5580 case 'Q':
5581 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005582 case 'S': // A symbolic address
5583 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005584 }
5585 }
5586 return TargetLowering::getConstraintType(Constraint);
5587}
5588
5589/// Examine constraint type and operand type and determine a weight value.
5590/// This object must already have been set up with the operand type
5591/// and the current alternative constraint selected.
5592TargetLowering::ConstraintWeight
5593AArch64TargetLowering::getSingleConstraintMatchWeight(
5594 AsmOperandInfo &info, const char *constraint) const {
5595 ConstraintWeight weight = CW_Invalid;
5596 Value *CallOperandVal = info.CallOperandVal;
5597 // If we don't have a value, we can't do a match,
5598 // but allow it at the lowest weight.
5599 if (!CallOperandVal)
5600 return CW_Default;
5601 Type *type = CallOperandVal->getType();
5602 // Look at the constraint type.
5603 switch (*constraint) {
5604 default:
5605 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5606 break;
5607 case 'x':
5608 case 'w':
5609 if (type->isFloatingPointTy() || type->isVectorTy())
5610 weight = CW_Register;
5611 break;
5612 case 'z':
5613 weight = CW_Constant;
5614 break;
5615 }
5616 return weight;
5617}
5618
5619std::pair<unsigned, const TargetRegisterClass *>
5620AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005621 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005622 if (Constraint.size() == 1) {
5623 switch (Constraint[0]) {
5624 case 'r':
5625 if (VT.getSizeInBits() == 64)
5626 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5627 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5628 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005629 if (!Subtarget->hasFPARMv8())
5630 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005631 if (VT.getSizeInBits() == 16)
5632 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005633 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005634 return std::make_pair(0U, &AArch64::FPR32RegClass);
5635 if (VT.getSizeInBits() == 64)
5636 return std::make_pair(0U, &AArch64::FPR64RegClass);
5637 if (VT.getSizeInBits() == 128)
5638 return std::make_pair(0U, &AArch64::FPR128RegClass);
5639 break;
5640 // The instructions that this constraint is designed for can
5641 // only take 128-bit registers so just use that regclass.
5642 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005643 if (!Subtarget->hasFPARMv8())
5644 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005645 if (VT.getSizeInBits() == 128)
5646 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5647 break;
5648 }
5649 }
5650 if (StringRef("{cc}").equals_lower(Constraint))
5651 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5652
5653 // Use the default implementation in TargetLowering to convert the register
5654 // constraint into a member of a register class.
5655 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005656 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005657
5658 // Not found as a standard register?
5659 if (!Res.second) {
5660 unsigned Size = Constraint.size();
5661 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5662 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005663 int RegNo;
5664 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5665 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005666 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005667 // By default we'll emit v0-v31 for this unless there's a modifier where
5668 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005669 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5670 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5671 Res.second = &AArch64::FPR64RegClass;
5672 } else {
5673 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5674 Res.second = &AArch64::FPR128RegClass;
5675 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005676 }
5677 }
5678 }
5679
Eli Friedman071203b2018-08-24 19:12:13 +00005680 if (Res.second && !Subtarget->hasFPARMv8() &&
5681 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5682 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5683 return std::make_pair(0U, nullptr);
5684
Tim Northover3b0846e2014-05-24 12:50:23 +00005685 return Res;
5686}
5687
5688/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5689/// vector. If it is invalid, don't add anything to Ops.
5690void AArch64TargetLowering::LowerAsmOperandForConstraint(
5691 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5692 SelectionDAG &DAG) const {
5693 SDValue Result;
5694
5695 // Currently only support length 1 constraints.
5696 if (Constraint.length() != 1)
5697 return;
5698
5699 char ConstraintLetter = Constraint[0];
5700 switch (ConstraintLetter) {
5701 default:
5702 break;
5703
5704 // This set of constraints deal with valid constants for various instructions.
5705 // Validate and return a target constant for them if we can.
5706 case 'z': {
5707 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005708 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005709 return;
5710
5711 if (Op.getValueType() == MVT::i64)
5712 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5713 else
5714 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5715 break;
5716 }
Peter Smithc8117582018-05-16 09:33:25 +00005717 case 'S': {
5718 // An absolute symbolic address or label reference.
5719 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5720 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5721 GA->getValueType(0));
5722 } else if (const BlockAddressSDNode *BA =
5723 dyn_cast<BlockAddressSDNode>(Op)) {
5724 Result =
5725 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5726 } else if (const ExternalSymbolSDNode *ES =
5727 dyn_cast<ExternalSymbolSDNode>(Op)) {
5728 Result =
5729 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5730 } else
5731 return;
5732 break;
5733 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005734
5735 case 'I':
5736 case 'J':
5737 case 'K':
5738 case 'L':
5739 case 'M':
5740 case 'N':
5741 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5742 if (!C)
5743 return;
5744
5745 // Grab the value and do some validation.
5746 uint64_t CVal = C->getZExtValue();
5747 switch (ConstraintLetter) {
5748 // The I constraint applies only to simple ADD or SUB immediate operands:
5749 // i.e. 0 to 4095 with optional shift by 12
5750 // The J constraint applies only to ADD or SUB immediates that would be
5751 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5752 // instruction [or vice versa], in other words -1 to -4095 with optional
5753 // left shift by 12.
5754 case 'I':
5755 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5756 break;
5757 return;
5758 case 'J': {
5759 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005760 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5761 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005762 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005763 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005764 return;
5765 }
5766 // The K and L constraints apply *only* to logical immediates, including
5767 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5768 // been removed and MOV should be used). So these constraints have to
5769 // distinguish between bit patterns that are valid 32-bit or 64-bit
5770 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5771 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5772 // versa.
5773 case 'K':
5774 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5775 break;
5776 return;
5777 case 'L':
5778 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5779 break;
5780 return;
5781 // The M and N constraints are a superset of K and L respectively, for use
5782 // with the MOV (immediate) alias. As well as the logical immediates they
5783 // also match 32 or 64-bit immediates that can be loaded either using a
5784 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5785 // (M) or 64-bit 0x1234000000000000 (N) etc.
5786 // As a note some of this code is liberally stolen from the asm parser.
5787 case 'M': {
5788 if (!isUInt<32>(CVal))
5789 return;
5790 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5791 break;
5792 if ((CVal & 0xFFFF) == CVal)
5793 break;
5794 if ((CVal & 0xFFFF0000ULL) == CVal)
5795 break;
5796 uint64_t NCVal = ~(uint32_t)CVal;
5797 if ((NCVal & 0xFFFFULL) == NCVal)
5798 break;
5799 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5800 break;
5801 return;
5802 }
5803 case 'N': {
5804 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5805 break;
5806 if ((CVal & 0xFFFFULL) == CVal)
5807 break;
5808 if ((CVal & 0xFFFF0000ULL) == CVal)
5809 break;
5810 if ((CVal & 0xFFFF00000000ULL) == CVal)
5811 break;
5812 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5813 break;
5814 uint64_t NCVal = ~CVal;
5815 if ((NCVal & 0xFFFFULL) == NCVal)
5816 break;
5817 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5818 break;
5819 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5820 break;
5821 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5822 break;
5823 return;
5824 }
5825 default:
5826 return;
5827 }
5828
5829 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005830 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005831 break;
5832 }
5833
5834 if (Result.getNode()) {
5835 Ops.push_back(Result);
5836 return;
5837 }
5838
5839 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5840}
5841
5842//===----------------------------------------------------------------------===//
5843// AArch64 Advanced SIMD Support
5844//===----------------------------------------------------------------------===//
5845
5846/// WidenVector - Given a value in the V64 register class, produce the
5847/// equivalent value in the V128 register class.
5848static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5849 EVT VT = V64Reg.getValueType();
5850 unsigned NarrowSize = VT.getVectorNumElements();
5851 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5852 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5853 SDLoc DL(V64Reg);
5854
5855 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005856 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005857}
5858
5859/// getExtFactor - Determine the adjustment factor for the position when
5860/// generating an "extract from vector registers" instruction.
5861static unsigned getExtFactor(SDValue &V) {
5862 EVT EltType = V.getValueType().getVectorElementType();
5863 return EltType.getSizeInBits() / 8;
5864}
5865
5866/// NarrowVector - Given a value in the V128 register class, produce the
5867/// equivalent value in the V64 register class.
5868static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5869 EVT VT = V128Reg.getValueType();
5870 unsigned WideSize = VT.getVectorNumElements();
5871 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5872 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5873 SDLoc DL(V128Reg);
5874
5875 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5876}
5877
5878// Gather data to see if the operation can be modelled as a
5879// shuffle in combination with VEXTs.
5880SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5881 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005882 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005883 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005884 SDLoc dl(Op);
5885 EVT VT = Op.getValueType();
5886 unsigned NumElts = VT.getVectorNumElements();
5887
Tim Northover7324e842014-07-24 15:39:55 +00005888 struct ShuffleSourceInfo {
5889 SDValue Vec;
5890 unsigned MinElt;
5891 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005892
Tim Northover7324e842014-07-24 15:39:55 +00005893 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5894 // be compatible with the shuffle we intend to construct. As a result
5895 // ShuffleVec will be some sliding window into the original Vec.
5896 SDValue ShuffleVec;
5897
5898 // Code should guarantee that element i in Vec starts at element "WindowBase
5899 // + i * WindowScale in ShuffleVec".
5900 int WindowBase;
5901 int WindowScale;
5902
Tim Northover7324e842014-07-24 15:39:55 +00005903 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005904 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5905 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5906
5907 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005908 };
5909
5910 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5911 // node.
5912 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005913 for (unsigned i = 0; i < NumElts; ++i) {
5914 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005915 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005916 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005917 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5918 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005919 LLVM_DEBUG(
5920 dbgs() << "Reshuffle failed: "
5921 "a shuffle can only come from building a vector from "
5922 "various elements of other vectors, provided their "
5923 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005924 return SDValue();
5925 }
5926
Tim Northover7324e842014-07-24 15:39:55 +00005927 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005928 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005929 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005930 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005931 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005932
Tim Northover7324e842014-07-24 15:39:55 +00005933 // Update the minimum and maximum lane number seen.
5934 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5935 Source->MinElt = std::min(Source->MinElt, EltNo);
5936 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005937 }
5938
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005939 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005940 LLVM_DEBUG(
5941 dbgs() << "Reshuffle failed: currently only do something sane when at "
5942 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005943 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005944 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005945
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005946 // Find out the smallest element size among result and two sources, and use
5947 // it as element size to build the shuffle_vector.
5948 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005949 for (auto &Source : Sources) {
5950 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005951 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5952 SmallestEltTy = SrcEltTy;
5953 }
5954 }
5955 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005956 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005957 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5958 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005959
Tim Northover7324e842014-07-24 15:39:55 +00005960 // If the source vector is too wide or too narrow, we may nevertheless be able
5961 // to construct a compatible shuffle either by concatenating it with UNDEF or
5962 // extracting a suitable range of elements.
5963 for (auto &Src : Sources) {
5964 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005965
Tim Northover7324e842014-07-24 15:39:55 +00005966 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005967 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005968
5969 // This stage of the search produces a source with the same element type as
5970 // the original, but with a total width matching the BUILD_VECTOR output.
5971 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005972 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5973 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005974
5975 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5976 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005977 // We can pad out the smaller vector for free, so if it's part of a
5978 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005979 Src.ShuffleVec =
5980 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5981 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005982 continue;
5983 }
5984
Tim Northover7324e842014-07-24 15:39:55 +00005985 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005986
James Molloyf497d552014-10-17 17:06:31 +00005987 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005988 LLVM_DEBUG(
5989 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005990 return SDValue();
5991 }
5992
James Molloyf497d552014-10-17 17:06:31 +00005993 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005994 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005995 Src.ShuffleVec =
5996 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005997 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005998 Src.WindowBase = -NumSrcElts;
5999 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006000 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006001 Src.ShuffleVec =
6002 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006003 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006004 } else {
6005 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006006 SDValue VEXTSrc1 =
6007 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006008 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006009 SDValue VEXTSrc2 =
6010 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006011 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006012 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6013
6014 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006015 VEXTSrc2,
6016 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006017 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006018 }
6019 }
6020
Tim Northover7324e842014-07-24 15:39:55 +00006021 // Another possible incompatibility occurs from the vector element types. We
6022 // can fix this by bitcasting the source vectors to the same type we intend
6023 // for the shuffle.
6024 for (auto &Src : Sources) {
6025 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6026 if (SrcEltTy == SmallestEltTy)
6027 continue;
6028 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6029 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6030 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6031 Src.WindowBase *= Src.WindowScale;
6032 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006033
Tim Northover7324e842014-07-24 15:39:55 +00006034 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006035 LLVM_DEBUG(for (auto Src
6036 : Sources)
6037 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006038
6039 // The stars all align, our next step is to produce the mask for the shuffle.
6040 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006041 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006042 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006043 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006044 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006045 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006046
David Majnemer0d955d02016-08-11 22:21:41 +00006047 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006048 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6049
6050 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6051 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6052 // segment.
6053 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006054 int BitsDefined =
6055 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006056 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6057
6058 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6059 // starting at the appropriate offset.
6060 int *LaneMask = &Mask[i * ResMultiplier];
6061
6062 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6063 ExtractBase += NumElts * (Src - Sources.begin());
6064 for (int j = 0; j < LanesDefined; ++j)
6065 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006066 }
6067
6068 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006069 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006070 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006071 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006072 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006073
Tim Northover7324e842014-07-24 15:39:55 +00006074 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6075 for (unsigned i = 0; i < Sources.size(); ++i)
6076 ShuffleOps[i] = Sources[i].ShuffleVec;
6077
6078 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006079 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006080 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6081
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006082 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6083 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006084
6085 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006086}
6087
6088// check if an EXT instruction can handle the shuffle mask when the
6089// vector sources of the shuffle are the same.
6090static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6091 unsigned NumElts = VT.getVectorNumElements();
6092
6093 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6094 if (M[0] < 0)
6095 return false;
6096
6097 Imm = M[0];
6098
6099 // If this is a VEXT shuffle, the immediate value is the index of the first
6100 // element. The other shuffle indices must be the successive elements after
6101 // the first one.
6102 unsigned ExpectedElt = Imm;
6103 for (unsigned i = 1; i < NumElts; ++i) {
6104 // Increment the expected index. If it wraps around, just follow it
6105 // back to index zero and keep going.
6106 ++ExpectedElt;
6107 if (ExpectedElt == NumElts)
6108 ExpectedElt = 0;
6109
6110 if (M[i] < 0)
6111 continue; // ignore UNDEF indices
6112 if (ExpectedElt != static_cast<unsigned>(M[i]))
6113 return false;
6114 }
6115
6116 return true;
6117}
6118
6119// check if an EXT instruction can handle the shuffle mask when the
6120// vector sources of the shuffle are different.
6121static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6122 unsigned &Imm) {
6123 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006124 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006125
6126 // Benefit form APInt to handle overflow when calculating expected element.
6127 unsigned NumElts = VT.getVectorNumElements();
6128 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6129 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6130 // The following shuffle indices must be the successive elements after the
6131 // first real element.
6132 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6133 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6134 if (FirstWrongElt != M.end())
6135 return false;
6136
6137 // The index of an EXT is the first element if it is not UNDEF.
6138 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006139 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006140 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6141 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6142 // ExpectedElt is the last mask index plus 1.
6143 Imm = ExpectedElt.getZExtValue();
6144
6145 // There are two difference cases requiring to reverse input vectors.
6146 // For example, for vector <4 x i32> we have the following cases,
6147 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6148 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6149 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6150 // to reverse two input vectors.
6151 if (Imm < NumElts)
6152 ReverseEXT = true;
6153 else
6154 Imm -= NumElts;
6155
6156 return true;
6157}
6158
6159/// isREVMask - Check if a vector shuffle corresponds to a REV
6160/// instruction with the specified blocksize. (The order of the elements
6161/// within each block of the vector is reversed.)
6162static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6163 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6164 "Only possible block sizes for REV are: 16, 32, 64");
6165
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006166 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006167 if (EltSz == 64)
6168 return false;
6169
6170 unsigned NumElts = VT.getVectorNumElements();
6171 unsigned BlockElts = M[0] + 1;
6172 // If the first shuffle index is UNDEF, be optimistic.
6173 if (M[0] < 0)
6174 BlockElts = BlockSize / EltSz;
6175
6176 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6177 return false;
6178
6179 for (unsigned i = 0; i < NumElts; ++i) {
6180 if (M[i] < 0)
6181 continue; // ignore UNDEF indices
6182 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6183 return false;
6184 }
6185
6186 return true;
6187}
6188
6189static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6190 unsigned NumElts = VT.getVectorNumElements();
6191 WhichResult = (M[0] == 0 ? 0 : 1);
6192 unsigned Idx = WhichResult * NumElts / 2;
6193 for (unsigned i = 0; i != NumElts; i += 2) {
6194 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6195 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6196 return false;
6197 Idx += 1;
6198 }
6199
6200 return true;
6201}
6202
6203static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6204 unsigned NumElts = VT.getVectorNumElements();
6205 WhichResult = (M[0] == 0 ? 0 : 1);
6206 for (unsigned i = 0; i != NumElts; ++i) {
6207 if (M[i] < 0)
6208 continue; // ignore UNDEF indices
6209 if ((unsigned)M[i] != 2 * i + WhichResult)
6210 return false;
6211 }
6212
6213 return true;
6214}
6215
6216static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6217 unsigned NumElts = VT.getVectorNumElements();
6218 WhichResult = (M[0] == 0 ? 0 : 1);
6219 for (unsigned i = 0; i < NumElts; i += 2) {
6220 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6221 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6222 return false;
6223 }
6224 return true;
6225}
6226
6227/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6228/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6229/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6230static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6231 unsigned NumElts = VT.getVectorNumElements();
6232 WhichResult = (M[0] == 0 ? 0 : 1);
6233 unsigned Idx = WhichResult * NumElts / 2;
6234 for (unsigned i = 0; i != NumElts; i += 2) {
6235 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6236 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6237 return false;
6238 Idx += 1;
6239 }
6240
6241 return true;
6242}
6243
6244/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6245/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6246/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6247static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6248 unsigned Half = VT.getVectorNumElements() / 2;
6249 WhichResult = (M[0] == 0 ? 0 : 1);
6250 for (unsigned j = 0; j != 2; ++j) {
6251 unsigned Idx = WhichResult;
6252 for (unsigned i = 0; i != Half; ++i) {
6253 int MIdx = M[i + j * Half];
6254 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6255 return false;
6256 Idx += 2;
6257 }
6258 }
6259
6260 return true;
6261}
6262
6263/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6264/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6265/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6266static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6267 unsigned NumElts = VT.getVectorNumElements();
6268 WhichResult = (M[0] == 0 ? 0 : 1);
6269 for (unsigned i = 0; i < NumElts; i += 2) {
6270 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6271 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6272 return false;
6273 }
6274 return true;
6275}
6276
6277static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6278 bool &DstIsLeft, int &Anomaly) {
6279 if (M.size() != static_cast<size_t>(NumInputElements))
6280 return false;
6281
6282 int NumLHSMatch = 0, NumRHSMatch = 0;
6283 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6284
6285 for (int i = 0; i < NumInputElements; ++i) {
6286 if (M[i] == -1) {
6287 ++NumLHSMatch;
6288 ++NumRHSMatch;
6289 continue;
6290 }
6291
6292 if (M[i] == i)
6293 ++NumLHSMatch;
6294 else
6295 LastLHSMismatch = i;
6296
6297 if (M[i] == i + NumInputElements)
6298 ++NumRHSMatch;
6299 else
6300 LastRHSMismatch = i;
6301 }
6302
6303 if (NumLHSMatch == NumInputElements - 1) {
6304 DstIsLeft = true;
6305 Anomaly = LastLHSMismatch;
6306 return true;
6307 } else if (NumRHSMatch == NumInputElements - 1) {
6308 DstIsLeft = false;
6309 Anomaly = LastRHSMismatch;
6310 return true;
6311 }
6312
6313 return false;
6314}
6315
6316static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6317 if (VT.getSizeInBits() != 128)
6318 return false;
6319
6320 unsigned NumElts = VT.getVectorNumElements();
6321
6322 for (int I = 0, E = NumElts / 2; I != E; I++) {
6323 if (Mask[I] != I)
6324 return false;
6325 }
6326
6327 int Offset = NumElts / 2;
6328 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6329 if (Mask[I] != I + SplitLHS * Offset)
6330 return false;
6331 }
6332
6333 return true;
6334}
6335
6336static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6337 SDLoc DL(Op);
6338 EVT VT = Op.getValueType();
6339 SDValue V0 = Op.getOperand(0);
6340 SDValue V1 = Op.getOperand(1);
6341 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6342
6343 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6344 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6345 return SDValue();
6346
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006347 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006348
6349 if (!isConcatMask(Mask, VT, SplitV0))
6350 return SDValue();
6351
6352 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6353 VT.getVectorNumElements() / 2);
6354 if (SplitV0) {
6355 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006356 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006357 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006358 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006359 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006360 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006361 }
6362 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6363}
6364
6365/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6366/// the specified operations to build the shuffle.
6367static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6368 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006369 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006370 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6371 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6372 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6373
6374 enum {
6375 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6376 OP_VREV,
6377 OP_VDUP0,
6378 OP_VDUP1,
6379 OP_VDUP2,
6380 OP_VDUP3,
6381 OP_VEXT1,
6382 OP_VEXT2,
6383 OP_VEXT3,
6384 OP_VUZPL, // VUZP, left result
6385 OP_VUZPR, // VUZP, right result
6386 OP_VZIPL, // VZIP, left result
6387 OP_VZIPR, // VZIP, right result
6388 OP_VTRNL, // VTRN, left result
6389 OP_VTRNR // VTRN, right result
6390 };
6391
6392 if (OpNum == OP_COPY) {
6393 if (LHSID == (1 * 9 + 2) * 9 + 3)
6394 return LHS;
6395 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6396 return RHS;
6397 }
6398
6399 SDValue OpLHS, OpRHS;
6400 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6401 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6402 EVT VT = OpLHS.getValueType();
6403
6404 switch (OpNum) {
6405 default:
6406 llvm_unreachable("Unknown shuffle opcode!");
6407 case OP_VREV:
6408 // VREV divides the vector in half and swaps within the half.
6409 if (VT.getVectorElementType() == MVT::i32 ||
6410 VT.getVectorElementType() == MVT::f32)
6411 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6412 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006413 if (VT.getVectorElementType() == MVT::i16 ||
6414 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006415 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6416 // vrev <4 x i8> -> REV16
6417 assert(VT.getVectorElementType() == MVT::i8);
6418 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6419 case OP_VDUP0:
6420 case OP_VDUP1:
6421 case OP_VDUP2:
6422 case OP_VDUP3: {
6423 EVT EltTy = VT.getVectorElementType();
6424 unsigned Opcode;
6425 if (EltTy == MVT::i8)
6426 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006427 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006428 Opcode = AArch64ISD::DUPLANE16;
6429 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6430 Opcode = AArch64ISD::DUPLANE32;
6431 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6432 Opcode = AArch64ISD::DUPLANE64;
6433 else
6434 llvm_unreachable("Invalid vector element type?");
6435
6436 if (VT.getSizeInBits() == 64)
6437 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006438 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006439 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6440 }
6441 case OP_VEXT1:
6442 case OP_VEXT2:
6443 case OP_VEXT3: {
6444 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6445 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006446 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006447 }
6448 case OP_VUZPL:
6449 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6450 OpRHS);
6451 case OP_VUZPR:
6452 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6453 OpRHS);
6454 case OP_VZIPL:
6455 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6456 OpRHS);
6457 case OP_VZIPR:
6458 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6459 OpRHS);
6460 case OP_VTRNL:
6461 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6462 OpRHS);
6463 case OP_VTRNR:
6464 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6465 OpRHS);
6466 }
6467}
6468
6469static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6470 SelectionDAG &DAG) {
6471 // Check to see if we can use the TBL instruction.
6472 SDValue V1 = Op.getOperand(0);
6473 SDValue V2 = Op.getOperand(1);
6474 SDLoc DL(Op);
6475
6476 EVT EltVT = Op.getValueType().getVectorElementType();
6477 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6478
6479 SmallVector<SDValue, 8> TBLMask;
6480 for (int Val : ShuffleMask) {
6481 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6482 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006483 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006484 }
6485 }
6486
6487 MVT IndexVT = MVT::v8i8;
6488 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006489 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006490 IndexVT = MVT::v16i8;
6491 IndexLen = 16;
6492 }
6493
6494 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6495 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6496
6497 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006498 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006499 if (IndexLen == 8)
6500 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6501 Shuffle = DAG.getNode(
6502 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006503 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006504 DAG.getBuildVector(IndexVT, DL,
6505 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006506 } else {
6507 if (IndexLen == 8) {
6508 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6509 Shuffle = DAG.getNode(
6510 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006511 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006512 DAG.getBuildVector(IndexVT, DL,
6513 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006514 } else {
6515 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6516 // cannot currently represent the register constraints on the input
6517 // table registers.
6518 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006519 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6520 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006521 Shuffle = DAG.getNode(
6522 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006523 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6524 V2Cst, DAG.getBuildVector(IndexVT, DL,
6525 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006526 }
6527 }
6528 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6529}
6530
6531static unsigned getDUPLANEOp(EVT EltType) {
6532 if (EltType == MVT::i8)
6533 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006534 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006535 return AArch64ISD::DUPLANE16;
6536 if (EltType == MVT::i32 || EltType == MVT::f32)
6537 return AArch64ISD::DUPLANE32;
6538 if (EltType == MVT::i64 || EltType == MVT::f64)
6539 return AArch64ISD::DUPLANE64;
6540
6541 llvm_unreachable("Invalid vector element type?");
6542}
6543
6544SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6545 SelectionDAG &DAG) const {
6546 SDLoc dl(Op);
6547 EVT VT = Op.getValueType();
6548
6549 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6550
6551 // Convert shuffles that are directly supported on NEON to target-specific
6552 // DAG nodes, instead of keeping them as shuffles and matching them again
6553 // during code selection. This is more efficient and avoids the possibility
6554 // of inconsistencies between legalization and selection.
6555 ArrayRef<int> ShuffleMask = SVN->getMask();
6556
6557 SDValue V1 = Op.getOperand(0);
6558 SDValue V2 = Op.getOperand(1);
6559
Craig Topperbc56e3b2016-06-30 04:38:51 +00006560 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006561 int Lane = SVN->getSplatIndex();
6562 // If this is undef splat, generate it via "just" vdup, if possible.
6563 if (Lane == -1)
6564 Lane = 0;
6565
6566 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6567 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6568 V1.getOperand(0));
6569 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6570 // constant. If so, we can just reference the lane's definition directly.
6571 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6572 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6573 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6574
6575 // Otherwise, duplicate from the lane of the input vector.
6576 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6577
6578 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6579 // to make a vector of the same size as this SHUFFLE. We can ignore the
6580 // extract entirely, and canonicalise the concat using WidenVector.
6581 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6582 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6583 V1 = V1.getOperand(0);
6584 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6585 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6586 Lane -= Idx * VT.getVectorNumElements() / 2;
6587 V1 = WidenVector(V1.getOperand(Idx), DAG);
6588 } else if (VT.getSizeInBits() == 64)
6589 V1 = WidenVector(V1, DAG);
6590
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006591 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006592 }
6593
6594 if (isREVMask(ShuffleMask, VT, 64))
6595 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6596 if (isREVMask(ShuffleMask, VT, 32))
6597 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6598 if (isREVMask(ShuffleMask, VT, 16))
6599 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6600
6601 bool ReverseEXT = false;
6602 unsigned Imm;
6603 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6604 if (ReverseEXT)
6605 std::swap(V1, V2);
6606 Imm *= getExtFactor(V1);
6607 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006608 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006609 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006610 Imm *= getExtFactor(V1);
6611 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006612 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006613 }
6614
6615 unsigned WhichResult;
6616 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6617 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6618 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6619 }
6620 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6621 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6622 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6623 }
6624 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6625 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6626 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6627 }
6628
6629 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6630 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6631 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6632 }
6633 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6634 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6635 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6636 }
6637 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6638 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6639 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6640 }
6641
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006642 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006643 return Concat;
6644
6645 bool DstIsLeft;
6646 int Anomaly;
6647 int NumInputElements = V1.getValueType().getVectorNumElements();
6648 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6649 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006650 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006651
6652 SDValue SrcVec = V1;
6653 int SrcLane = ShuffleMask[Anomaly];
6654 if (SrcLane >= NumInputElements) {
6655 SrcVec = V2;
6656 SrcLane -= VT.getVectorNumElements();
6657 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006658 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006659
6660 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006661
6662 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006663 ScalarVT = MVT::i32;
6664
6665 return DAG.getNode(
6666 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6667 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6668 DstLaneV);
6669 }
6670
6671 // If the shuffle is not directly supported and it has 4 elements, use
6672 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6673 unsigned NumElts = VT.getVectorNumElements();
6674 if (NumElts == 4) {
6675 unsigned PFIndexes[4];
6676 for (unsigned i = 0; i != 4; ++i) {
6677 if (ShuffleMask[i] < 0)
6678 PFIndexes[i] = 8;
6679 else
6680 PFIndexes[i] = ShuffleMask[i];
6681 }
6682
6683 // Compute the index in the perfect shuffle table.
6684 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6685 PFIndexes[2] * 9 + PFIndexes[3];
6686 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6687 unsigned Cost = (PFEntry >> 30);
6688
6689 if (Cost <= 4)
6690 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6691 }
6692
6693 return GenerateTBL(Op, ShuffleMask, DAG);
6694}
6695
6696static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6697 APInt &UndefBits) {
6698 EVT VT = BVN->getValueType(0);
6699 APInt SplatBits, SplatUndef;
6700 unsigned SplatBitSize;
6701 bool HasAnyUndefs;
6702 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6703 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6704
6705 for (unsigned i = 0; i < NumSplats; ++i) {
6706 CnstBits <<= SplatBitSize;
6707 UndefBits <<= SplatBitSize;
6708 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6709 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6710 }
6711
6712 return true;
6713 }
6714
6715 return false;
6716}
6717
Evandro Menezes72f39832018-02-20 20:31:45 +00006718// Try 64-bit splatted SIMD immediate.
6719static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6720 const APInt &Bits) {
6721 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6722 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6723 EVT VT = Op.getValueType();
6724 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6725
6726 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6727 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6728
6729 SDLoc dl(Op);
6730 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6731 DAG.getConstant(Value, dl, MVT::i32));
6732 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6733 }
6734 }
6735
6736 return SDValue();
6737}
6738
6739// Try 32-bit splatted SIMD immediate.
6740static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6741 const APInt &Bits,
6742 const SDValue *LHS = nullptr) {
6743 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6744 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6745 EVT VT = Op.getValueType();
6746 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6747 bool isAdvSIMDModImm = false;
6748 uint64_t Shift;
6749
6750 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6751 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6752 Shift = 0;
6753 }
6754 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6755 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6756 Shift = 8;
6757 }
6758 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6759 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6760 Shift = 16;
6761 }
6762 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6763 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6764 Shift = 24;
6765 }
6766
6767 if (isAdvSIMDModImm) {
6768 SDLoc dl(Op);
6769 SDValue Mov;
6770
6771 if (LHS)
6772 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6773 DAG.getConstant(Value, dl, MVT::i32),
6774 DAG.getConstant(Shift, dl, MVT::i32));
6775 else
6776 Mov = DAG.getNode(NewOp, dl, MovTy,
6777 DAG.getConstant(Value, dl, MVT::i32),
6778 DAG.getConstant(Shift, dl, MVT::i32));
6779
6780 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6781 }
6782 }
6783
6784 return SDValue();
6785}
6786
6787// Try 16-bit splatted SIMD immediate.
6788static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6789 const APInt &Bits,
6790 const SDValue *LHS = nullptr) {
6791 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6792 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6793 EVT VT = Op.getValueType();
6794 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6795 bool isAdvSIMDModImm = false;
6796 uint64_t Shift;
6797
6798 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6799 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6800 Shift = 0;
6801 }
6802 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6803 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6804 Shift = 8;
6805 }
6806
6807 if (isAdvSIMDModImm) {
6808 SDLoc dl(Op);
6809 SDValue Mov;
6810
6811 if (LHS)
6812 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006813 DAG.getConstant(Value, dl, MVT::i32),
6814 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006815 else
6816 Mov = DAG.getNode(NewOp, dl, MovTy,
6817 DAG.getConstant(Value, dl, MVT::i32),
6818 DAG.getConstant(Shift, dl, MVT::i32));
6819
6820 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6821 }
6822 }
6823
6824 return SDValue();
6825}
6826
6827// Try 32-bit splatted SIMD immediate with shifted ones.
6828static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6829 SelectionDAG &DAG, const APInt &Bits) {
6830 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6831 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6832 EVT VT = Op.getValueType();
6833 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6834 bool isAdvSIMDModImm = false;
6835 uint64_t Shift;
6836
6837 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6838 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6839 Shift = 264;
6840 }
6841 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6842 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6843 Shift = 272;
6844 }
6845
6846 if (isAdvSIMDModImm) {
6847 SDLoc dl(Op);
6848 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6849 DAG.getConstant(Value, dl, MVT::i32),
6850 DAG.getConstant(Shift, dl, MVT::i32));
6851 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6852 }
6853 }
6854
6855 return SDValue();
6856}
6857
6858// Try 8-bit splatted SIMD immediate.
6859static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6860 const APInt &Bits) {
6861 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6862 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6863 EVT VT = Op.getValueType();
6864 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6865
6866 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6867 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6868
6869 SDLoc dl(Op);
6870 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6871 DAG.getConstant(Value, dl, MVT::i32));
6872 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6873 }
6874 }
6875
6876 return SDValue();
6877}
6878
6879// Try FP splatted SIMD immediate.
6880static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6881 const APInt &Bits) {
6882 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6883 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6884 EVT VT = Op.getValueType();
6885 bool isWide = (VT.getSizeInBits() == 128);
6886 MVT MovTy;
6887 bool isAdvSIMDModImm = false;
6888
6889 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6890 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6891 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6892 }
6893 else if (isWide &&
6894 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6895 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6896 MovTy = MVT::v2f64;
6897 }
6898
6899 if (isAdvSIMDModImm) {
6900 SDLoc dl(Op);
6901 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6902 DAG.getConstant(Value, dl, MVT::i32));
6903 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6904 }
6905 }
6906
6907 return SDValue();
6908}
6909
Tim Northover3b0846e2014-05-24 12:50:23 +00006910SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6911 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006912 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006913 EVT VT = Op.getValueType();
6914
Evandro Menezes72f39832018-02-20 20:31:45 +00006915 BuildVectorSDNode *BVN =
6916 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6917 if (!BVN) {
6918 // AND commutes, so try swapping the operands.
6919 LHS = Op.getOperand(1);
6920 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6921 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006922 if (!BVN)
6923 return Op;
6924
Evandro Menezes72f39832018-02-20 20:31:45 +00006925 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006926 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006927 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6928 SDValue NewOp;
6929
Tim Northover3b0846e2014-05-24 12:50:23 +00006930 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006931 DefBits = ~DefBits;
6932 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6933 DefBits, &LHS)) ||
6934 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6935 DefBits, &LHS)))
6936 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006937
6938 UndefBits = ~UndefBits;
6939 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6940 UndefBits, &LHS)) ||
6941 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6942 UndefBits, &LHS)))
6943 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006944 }
6945
Evandro Menezes72f39832018-02-20 20:31:45 +00006946 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006947 return Op;
6948}
6949
6950// Specialized code to quickly find if PotentialBVec is a BuildVector that
6951// consists of only the same constant int value, returned in reference arg
6952// ConstVal
6953static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6954 uint64_t &ConstVal) {
6955 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6956 if (!Bvec)
6957 return false;
6958 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6959 if (!FirstElt)
6960 return false;
6961 EVT VT = Bvec->getValueType(0);
6962 unsigned NumElts = VT.getVectorNumElements();
6963 for (unsigned i = 1; i < NumElts; ++i)
6964 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6965 return false;
6966 ConstVal = FirstElt->getZExtValue();
6967 return true;
6968}
6969
6970static unsigned getIntrinsicID(const SDNode *N) {
6971 unsigned Opcode = N->getOpcode();
6972 switch (Opcode) {
6973 default:
6974 return Intrinsic::not_intrinsic;
6975 case ISD::INTRINSIC_WO_CHAIN: {
6976 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6977 if (IID < Intrinsic::num_intrinsics)
6978 return IID;
6979 return Intrinsic::not_intrinsic;
6980 }
6981 }
6982}
6983
6984// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6985// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6986// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6987// Also, logical shift right -> sri, with the same structure.
6988static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6989 EVT VT = N->getValueType(0);
6990
6991 if (!VT.isVector())
6992 return SDValue();
6993
6994 SDLoc DL(N);
6995
6996 // Is the first op an AND?
6997 const SDValue And = N->getOperand(0);
6998 if (And.getOpcode() != ISD::AND)
6999 return SDValue();
7000
7001 // Is the second op an shl or lshr?
7002 SDValue Shift = N->getOperand(1);
7003 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7004 // or AArch64ISD::VLSHR vector, #shift
7005 unsigned ShiftOpc = Shift.getOpcode();
7006 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7007 return SDValue();
7008 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7009
7010 // Is the shift amount constant?
7011 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7012 if (!C2node)
7013 return SDValue();
7014
7015 // Is the and mask vector all constant?
7016 uint64_t C1;
7017 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7018 return SDValue();
7019
7020 // Is C1 == ~C2, taking into account how much one can shift elements of a
7021 // particular size?
7022 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007023 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007024 if (C2 > ElemSizeInBits)
7025 return SDValue();
7026 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7027 if ((C1 & ElemMask) != (~C2 & ElemMask))
7028 return SDValue();
7029
7030 SDValue X = And.getOperand(0);
7031 SDValue Y = Shift.getOperand(0);
7032
7033 unsigned Intrin =
7034 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7035 SDValue ResultSLI =
7036 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007037 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7038 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007039
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007040 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7041 LLVM_DEBUG(N->dump(&DAG));
7042 LLVM_DEBUG(dbgs() << "into: \n");
7043 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007044
7045 ++NumShiftInserts;
7046 return ResultSLI;
7047}
7048
7049SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7050 SelectionDAG &DAG) const {
7051 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7052 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007053 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007054 return Res;
7055 }
7056
Tim Northover3b0846e2014-05-24 12:50:23 +00007057 EVT VT = Op.getValueType();
7058
Evandro Menezescd855f72018-03-05 17:02:47 +00007059 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007060 BuildVectorSDNode *BVN =
7061 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007062 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007063 // OR commutes, so try swapping the operands.
7064 LHS = Op.getOperand(1);
7065 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007066 }
7067 if (!BVN)
7068 return Op;
7069
Evandro Menezes72f39832018-02-20 20:31:45 +00007070 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007071 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007072 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7073 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007074
Evandro Menezes72f39832018-02-20 20:31:45 +00007075 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7076 DefBits, &LHS)) ||
7077 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7078 DefBits, &LHS)))
7079 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007080
7081 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7082 UndefBits, &LHS)) ||
7083 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7084 UndefBits, &LHS)))
7085 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007086 }
7087
Evandro Menezes72f39832018-02-20 20:31:45 +00007088 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007089 return Op;
7090}
7091
Kevin Qin4473c192014-07-07 02:45:40 +00007092// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7093// be truncated to fit element width.
7094static SDValue NormalizeBuildVector(SDValue Op,
7095 SelectionDAG &DAG) {
7096 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007097 SDLoc dl(Op);
7098 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007099 EVT EltTy= VT.getVectorElementType();
7100
7101 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7102 return Op;
7103
7104 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007105 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007106 // For integer vectors, type legalization would have promoted the
7107 // operands already. Otherwise, if Op is a floating-point splat
7108 // (with operands cast to integers), then the only possibilities
7109 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007110 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007111 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007112 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007113 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007114 } else if (Lane.getNode()->isUndef()) {
7115 Lane = DAG.getUNDEF(MVT::i32);
7116 } else {
7117 assert(Lane.getValueType() == MVT::i32 &&
7118 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007119 }
7120 Ops.push_back(Lane);
7121 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007122 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007123}
7124
Evandro Menezescd855f72018-03-05 17:02:47 +00007125static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007126 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007127
Evandro Menezes72f39832018-02-20 20:31:45 +00007128 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007129 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007130 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007131 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007132 SDValue NewOp;
7133 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7134 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7135 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7136 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7137 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7138 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7139 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007140
Evandro Menezes72f39832018-02-20 20:31:45 +00007141 DefBits = ~DefBits;
7142 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7143 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7144 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7145 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007146
Evandro Menezes72f39832018-02-20 20:31:45 +00007147 DefBits = UndefBits;
7148 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7149 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7150 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7151 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7152 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7153 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7154 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007155
Evandro Menezes72f39832018-02-20 20:31:45 +00007156 DefBits = ~UndefBits;
7157 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7158 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7159 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7160 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007161 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007162
Evandro Menezescd855f72018-03-05 17:02:47 +00007163 return SDValue();
7164}
7165
7166SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7167 SelectionDAG &DAG) const {
7168 EVT VT = Op.getValueType();
7169
7170 // Try to build a simple constant vector.
7171 Op = NormalizeBuildVector(Op, DAG);
7172 if (VT.isInteger()) {
7173 // Certain vector constants, used to express things like logical NOT and
7174 // arithmetic NEG, are passed through unmodified. This allows special
7175 // patterns for these operations to match, which will lower these constants
7176 // to whatever is proven necessary.
7177 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7178 if (BVN->isConstant())
7179 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7180 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7181 APInt Val(BitSize,
7182 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7183 if (Val.isNullValue() || Val.isAllOnesValue())
7184 return Op;
7185 }
7186 }
7187
7188 if (SDValue V = ConstantBuildVector(Op, DAG))
7189 return V;
7190
Tim Northover3b0846e2014-05-24 12:50:23 +00007191 // Scan through the operands to find some interesting properties we can
7192 // exploit:
7193 // 1) If only one value is used, we can use a DUP, or
7194 // 2) if only the low element is not undef, we can just insert that, or
7195 // 3) if only one constant value is used (w/ some non-constant lanes),
7196 // we can splat the constant value into the whole vector then fill
7197 // in the non-constant lanes.
7198 // 4) FIXME: If different constant values are used, but we can intelligently
7199 // select the values we'll be overwriting for the non-constant
7200 // lanes such that we can directly materialize the vector
7201 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007202 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007203 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007204 unsigned NumElts = VT.getVectorNumElements();
7205 bool isOnlyLowElement = true;
7206 bool usesOnlyOneValue = true;
7207 bool usesOnlyOneConstantValue = true;
7208 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007209 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007210 unsigned NumConstantLanes = 0;
7211 SDValue Value;
7212 SDValue ConstantValue;
7213 for (unsigned i = 0; i < NumElts; ++i) {
7214 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007215 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7216 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007217 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007218 continue;
7219 if (i > 0)
7220 isOnlyLowElement = false;
7221 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7222 isConstant = false;
7223
7224 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7225 ++NumConstantLanes;
7226 if (!ConstantValue.getNode())
7227 ConstantValue = V;
7228 else if (ConstantValue != V)
7229 usesOnlyOneConstantValue = false;
7230 }
7231
7232 if (!Value.getNode())
7233 Value = V;
7234 else if (V != Value)
7235 usesOnlyOneValue = false;
7236 }
7237
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007238 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007239 LLVM_DEBUG(
7240 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007241 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007242 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007243
John Brawnd6e0ebe2018-11-22 11:45:23 +00007244 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7245 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7246 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7247 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007248 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7249 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007250 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007251 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007252
Sebastian Popc33af712018-03-01 15:47:39 +00007253 if (AllLanesExtractElt) {
7254 SDNode *Vector = nullptr;
7255 bool Even = false;
7256 bool Odd = false;
7257 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7258 // the Odd pattern <1,3,5,...>.
7259 for (unsigned i = 0; i < NumElts; ++i) {
7260 SDValue V = Op.getOperand(i);
7261 const SDNode *N = V.getNode();
7262 if (!isa<ConstantSDNode>(N->getOperand(1)))
7263 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007264 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007265
7266 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007267 if (!Vector) {
7268 Vector = N0.getNode();
7269 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7270 // BUILD_VECTOR.
7271 if (VT.getVectorElementType() !=
7272 N0.getValueType().getVectorElementType())
7273 break;
7274 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007275 Odd = false;
7276 Even = false;
7277 break;
7278 }
7279
7280 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7281 // indices <1,3,5,...>.
7282 uint64_t Val = N->getConstantOperandVal(1);
7283 if (Val == 2 * i) {
7284 Even = true;
7285 continue;
7286 }
7287 if (Val - 1 == 2 * i) {
7288 Odd = true;
7289 continue;
7290 }
7291
7292 // Something does not match: abort.
7293 Odd = false;
7294 Even = false;
7295 break;
7296 }
7297 if (Even || Odd) {
7298 SDValue LHS =
7299 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7300 DAG.getConstant(0, dl, MVT::i64));
7301 SDValue RHS =
7302 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7303 DAG.getConstant(NumElts, dl, MVT::i64));
7304
7305 if (Even && !Odd)
7306 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7307 RHS);
7308 if (Odd && !Even)
7309 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7310 RHS);
7311 }
7312 }
7313
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007314 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007315 // i32 and try again.
7316 if (usesOnlyOneValue) {
7317 if (!isConstant) {
7318 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007319 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007320 LLVM_DEBUG(
7321 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007322 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007323 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007324
7325 // This is actually a DUPLANExx operation, which keeps everything vectory.
7326
Tim Northover3b0846e2014-05-24 12:50:23 +00007327 SDValue Lane = Value.getOperand(1);
7328 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007329 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007330 LLVM_DEBUG(
7331 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7332 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007333 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007334 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007335
7336 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7337 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7338 }
7339
7340 if (VT.getVectorElementType().isFloatingPoint()) {
7341 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007342 EVT EltTy = VT.getVectorElementType();
7343 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7344 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007345 LLVM_DEBUG(
7346 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7347 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007348 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007349 for (unsigned i = 0; i < NumElts; ++i)
7350 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7351 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007352 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007353 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7354 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007355 Val = LowerBUILD_VECTOR(Val, DAG);
7356 if (Val.getNode())
7357 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7358 }
7359 }
7360
7361 // If there was only one constant value used and for more than one lane,
7362 // start by splatting that value, then replace the non-constant lanes. This
7363 // is better than the default, which will perform a separate initialization
7364 // for each lane.
7365 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007366 // Firstly, try to materialize the splat constant.
7367 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7368 Val = ConstantBuildVector(Vec, DAG);
7369 if (!Val) {
7370 // Otherwise, materialize the constant and splat it.
7371 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7372 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7373 }
7374
Tim Northover3b0846e2014-05-24 12:50:23 +00007375 // Now insert the non-constant lanes.
7376 for (unsigned i = 0; i < NumElts; ++i) {
7377 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007378 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007379 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007380 // Note that type legalization likely mucked about with the VT of the
7381 // source operand, so we may have to convert it here before inserting.
7382 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007383 }
7384 return Val;
7385 }
7386
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007387 // This will generate a load from the constant pool.
7388 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007389 LLVM_DEBUG(
7390 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7391 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007392 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007393 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007394
7395 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7396 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007397 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007398 return shuffle;
7399 }
7400
7401 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7402 // know the default expansion would otherwise fall back on something even
7403 // worse. For a vector with one or two non-undef values, that's
7404 // scalar_to_vector for the elements followed by a shuffle (provided the
7405 // shuffle is valid for the target) and materialization element by element
7406 // on the stack followed by a load for everything else.
7407 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007408 LLVM_DEBUG(
7409 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7410 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007411
Tim Northover3b0846e2014-05-24 12:50:23 +00007412 SDValue Vec = DAG.getUNDEF(VT);
7413 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007414 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007415
7416 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007417 // a) Avoid a RMW dependency on the full vector register, and
7418 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007419 // value is already in an S or D register, and we're forced to emit an
7420 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007421 //
7422 // We also allow types like i8 and i16 which are illegal scalar but legal
7423 // vector element types. After type-legalization the inserted value is
7424 // extended (i32) and it is safe to cast them to the vector type by ignoring
7425 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7426 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007427 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007428 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007429 ++i;
7430 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007431 LLVM_DEBUG(if (i < NumElts) dbgs()
7432 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007433 for (; i < NumElts; ++i) {
7434 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007435 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007436 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007437 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007438 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7439 }
7440 return Vec;
7441 }
7442
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007443 LLVM_DEBUG(
7444 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7445 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007446 return SDValue();
7447}
7448
7449SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7450 SelectionDAG &DAG) const {
7451 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7452
Tim Northovere4b8e132014-07-15 10:00:26 +00007453 // Check for non-constant or out of range lane.
7454 EVT VT = Op.getOperand(0).getValueType();
7455 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7456 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007457 return SDValue();
7458
Tim Northover3b0846e2014-05-24 12:50:23 +00007459
7460 // Insertion/extraction are legal for V128 types.
7461 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007462 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7463 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007464 return Op;
7465
7466 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007467 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007468 return SDValue();
7469
7470 // For V64 types, we perform insertion by expanding the value
7471 // to a V128 type and perform the insertion on that.
7472 SDLoc DL(Op);
7473 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7474 EVT WideTy = WideVec.getValueType();
7475
7476 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7477 Op.getOperand(1), Op.getOperand(2));
7478 // Re-narrow the resultant vector.
7479 return NarrowVector(Node, DAG);
7480}
7481
7482SDValue
7483AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7484 SelectionDAG &DAG) const {
7485 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7486
Tim Northovere4b8e132014-07-15 10:00:26 +00007487 // Check for non-constant or out of range lane.
7488 EVT VT = Op.getOperand(0).getValueType();
7489 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7490 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007491 return SDValue();
7492
Tim Northover3b0846e2014-05-24 12:50:23 +00007493
7494 // Insertion/extraction are legal for V128 types.
7495 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007496 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7497 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007498 return Op;
7499
7500 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007501 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007502 return SDValue();
7503
7504 // For V64 types, we perform extraction by expanding the value
7505 // to a V128 type and perform the extraction on that.
7506 SDLoc DL(Op);
7507 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7508 EVT WideTy = WideVec.getValueType();
7509
7510 EVT ExtrTy = WideTy.getVectorElementType();
7511 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7512 ExtrTy = MVT::i32;
7513
7514 // For extractions, we just return the result directly.
7515 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7516 Op.getOperand(1));
7517}
7518
7519SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7520 SelectionDAG &DAG) const {
7521 EVT VT = Op.getOperand(0).getValueType();
7522 SDLoc dl(Op);
7523 // Just in case...
7524 if (!VT.isVector())
7525 return SDValue();
7526
7527 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7528 if (!Cst)
7529 return SDValue();
7530 unsigned Val = Cst->getZExtValue();
7531
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007532 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007533
7534 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7535 if (Val == 0)
7536 return Op;
7537
Tim Northover3b0846e2014-05-24 12:50:23 +00007538 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7539 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007540 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007541 return Op;
7542
7543 return SDValue();
7544}
7545
Zvi Rackover1b736822017-07-26 08:06:58 +00007546bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007547 if (VT.getVectorNumElements() == 4 &&
7548 (VT.is128BitVector() || VT.is64BitVector())) {
7549 unsigned PFIndexes[4];
7550 for (unsigned i = 0; i != 4; ++i) {
7551 if (M[i] < 0)
7552 PFIndexes[i] = 8;
7553 else
7554 PFIndexes[i] = M[i];
7555 }
7556
7557 // Compute the index in the perfect shuffle table.
7558 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7559 PFIndexes[2] * 9 + PFIndexes[3];
7560 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7561 unsigned Cost = (PFEntry >> 30);
7562
7563 if (Cost <= 4)
7564 return true;
7565 }
7566
7567 bool DummyBool;
7568 int DummyInt;
7569 unsigned DummyUnsigned;
7570
7571 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7572 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7573 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7574 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7575 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7576 isZIPMask(M, VT, DummyUnsigned) ||
7577 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7578 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7579 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7580 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7581 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7582}
7583
7584/// getVShiftImm - Check if this is a valid build_vector for the immediate
7585/// operand of a vector shift operation, where all the elements of the
7586/// build_vector must have the same constant integer value.
7587static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7588 // Ignore bit_converts.
7589 while (Op.getOpcode() == ISD::BITCAST)
7590 Op = Op.getOperand(0);
7591 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7592 APInt SplatBits, SplatUndef;
7593 unsigned SplatBitSize;
7594 bool HasAnyUndefs;
7595 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7596 HasAnyUndefs, ElementBits) ||
7597 SplatBitSize > ElementBits)
7598 return false;
7599 Cnt = SplatBits.getSExtValue();
7600 return true;
7601}
7602
7603/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7604/// operand of a vector shift left operation. That value must be in the range:
7605/// 0 <= Value < ElementBits for a left shift; or
7606/// 0 <= Value <= ElementBits for a long left shift.
7607static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7608 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007609 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007610 if (!getVShiftImm(Op, ElementBits, Cnt))
7611 return false;
7612 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7613}
7614
7615/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007616/// operand of a vector shift right operation. The value must be in the range:
7617/// 1 <= Value <= ElementBits for a right shift; or
7618static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007619 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007620 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007621 if (!getVShiftImm(Op, ElementBits, Cnt))
7622 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007623 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7624}
7625
7626SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7627 SelectionDAG &DAG) const {
7628 EVT VT = Op.getValueType();
7629 SDLoc DL(Op);
7630 int64_t Cnt;
7631
7632 if (!Op.getOperand(1).getValueType().isVector())
7633 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007634 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007635
7636 switch (Op.getOpcode()) {
7637 default:
7638 llvm_unreachable("unexpected shift opcode");
7639
7640 case ISD::SHL:
7641 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007642 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7643 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007644 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007645 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7646 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007647 Op.getOperand(0), Op.getOperand(1));
7648 case ISD::SRA:
7649 case ISD::SRL:
7650 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007651 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007652 unsigned Opc =
7653 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007654 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7655 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007656 }
7657
7658 // Right shift register. Note, there is not a shift right register
7659 // instruction, but the shift left register instruction takes a signed
7660 // value, where negative numbers specify a right shift.
7661 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7662 : Intrinsic::aarch64_neon_ushl;
7663 // negate the shift amount
7664 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7665 SDValue NegShiftLeft =
7666 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007667 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7668 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007669 return NegShiftLeft;
7670 }
7671
7672 return SDValue();
7673}
7674
7675static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7676 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007677 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007678 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007679 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7680 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007681
7682 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7683 APInt CnstBits(VT.getSizeInBits(), 0);
7684 APInt UndefBits(VT.getSizeInBits(), 0);
7685 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7686 bool IsZero = IsCnst && (CnstBits == 0);
7687
7688 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7689 switch (CC) {
7690 default:
7691 return SDValue();
7692 case AArch64CC::NE: {
7693 SDValue Fcmeq;
7694 if (IsZero)
7695 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7696 else
7697 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7698 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7699 }
7700 case AArch64CC::EQ:
7701 if (IsZero)
7702 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7703 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7704 case AArch64CC::GE:
7705 if (IsZero)
7706 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7707 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7708 case AArch64CC::GT:
7709 if (IsZero)
7710 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7711 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7712 case AArch64CC::LS:
7713 if (IsZero)
7714 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7715 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7716 case AArch64CC::LT:
7717 if (!NoNans)
7718 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007719 // If we ignore NaNs then we can use to the MI implementation.
7720 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007721 case AArch64CC::MI:
7722 if (IsZero)
7723 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7724 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7725 }
7726 }
7727
7728 switch (CC) {
7729 default:
7730 return SDValue();
7731 case AArch64CC::NE: {
7732 SDValue Cmeq;
7733 if (IsZero)
7734 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7735 else
7736 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7737 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7738 }
7739 case AArch64CC::EQ:
7740 if (IsZero)
7741 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7742 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7743 case AArch64CC::GE:
7744 if (IsZero)
7745 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7746 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7747 case AArch64CC::GT:
7748 if (IsZero)
7749 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7750 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7751 case AArch64CC::LE:
7752 if (IsZero)
7753 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7754 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7755 case AArch64CC::LS:
7756 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7757 case AArch64CC::LO:
7758 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7759 case AArch64CC::LT:
7760 if (IsZero)
7761 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7762 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7763 case AArch64CC::HI:
7764 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7765 case AArch64CC::HS:
7766 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7767 }
7768}
7769
7770SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7771 SelectionDAG &DAG) const {
7772 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7773 SDValue LHS = Op.getOperand(0);
7774 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007775 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007776 SDLoc dl(Op);
7777
7778 if (LHS.getValueType().getVectorElementType().isInteger()) {
7779 assert(LHS.getValueType() == RHS.getValueType());
7780 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007781 SDValue Cmp =
7782 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7783 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007784 }
7785
Carey Williamsda15b5b2018-01-22 14:16:11 +00007786 const bool FullFP16 =
7787 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7788
7789 // Make v4f16 (only) fcmp operations utilise vector instructions
7790 // v8f16 support will be a litle more complicated
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007791 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7792 if (LHS.getValueType().getVectorNumElements() == 4) {
Carey Williamsda15b5b2018-01-22 14:16:11 +00007793 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7794 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7795 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7796 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7797 CmpVT = MVT::v4i32;
7798 } else
7799 return SDValue();
7800 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007801
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007802 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7803 LHS.getValueType().getVectorElementType() != MVT::f128);
Tim Northover3b0846e2014-05-24 12:50:23 +00007804
7805 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7806 // clean. Some of them require two branches to implement.
7807 AArch64CC::CondCode CC1, CC2;
7808 bool ShouldInvert;
7809 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7810
7811 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7812 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007813 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007814 if (!Cmp.getNode())
7815 return SDValue();
7816
7817 if (CC2 != AArch64CC::AL) {
7818 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007819 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007820 if (!Cmp2.getNode())
7821 return SDValue();
7822
Tim Northover45aa89c2015-02-08 00:50:47 +00007823 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007824 }
7825
Tim Northover45aa89c2015-02-08 00:50:47 +00007826 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7827
Tim Northover3b0846e2014-05-24 12:50:23 +00007828 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007829 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007830
7831 return Cmp;
7832}
7833
Amara Emersonc9916d72017-05-16 21:29:22 +00007834static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7835 SelectionDAG &DAG) {
7836 SDValue VecOp = ScalarOp.getOperand(0);
7837 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7838 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7839 DAG.getConstant(0, DL, MVT::i64));
7840}
7841
7842SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7843 SelectionDAG &DAG) const {
7844 SDLoc dl(Op);
7845 switch (Op.getOpcode()) {
7846 case ISD::VECREDUCE_ADD:
7847 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7848 case ISD::VECREDUCE_SMAX:
7849 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7850 case ISD::VECREDUCE_SMIN:
7851 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7852 case ISD::VECREDUCE_UMAX:
7853 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7854 case ISD::VECREDUCE_UMIN:
7855 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7856 case ISD::VECREDUCE_FMAX: {
7857 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7858 return DAG.getNode(
7859 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7860 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7861 Op.getOperand(0));
7862 }
7863 case ISD::VECREDUCE_FMIN: {
7864 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7865 return DAG.getNode(
7866 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7867 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7868 Op.getOperand(0));
7869 }
7870 default:
7871 llvm_unreachable("Unhandled reduction");
7872 }
7873}
7874
Oliver Stannard42699172018-02-12 14:22:03 +00007875SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7876 SelectionDAG &DAG) const {
7877 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7878 if (!Subtarget.hasLSE())
7879 return SDValue();
7880
7881 // LSE has an atomic load-add instruction, but not a load-sub.
7882 SDLoc dl(Op);
7883 MVT VT = Op.getSimpleValueType();
7884 SDValue RHS = Op.getOperand(2);
7885 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7886 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7887 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7888 Op.getOperand(0), Op.getOperand(1), RHS,
7889 AN->getMemOperand());
7890}
7891
Oliver Stannard02f08c92018-02-12 17:03:11 +00007892SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7893 SelectionDAG &DAG) const {
7894 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7895 if (!Subtarget.hasLSE())
7896 return SDValue();
7897
7898 // LSE has an atomic load-clear instruction, but not a load-and.
7899 SDLoc dl(Op);
7900 MVT VT = Op.getSimpleValueType();
7901 SDValue RHS = Op.getOperand(2);
7902 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7903 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7904 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7905 Op.getOperand(0), Op.getOperand(1), RHS,
7906 AN->getMemOperand());
7907}
7908
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007909SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7910 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7911 SDLoc dl(Op);
7912 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7913 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7914
Tri Vo6c47c622018-09-22 22:17:50 +00007915 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7916 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7917 if (Subtarget->hasCustomCallingConv())
7918 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007919
7920 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7921 DAG.getConstant(4, dl, MVT::i64));
7922 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7923 Chain =
7924 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7925 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7926 DAG.getRegisterMask(Mask), Chain.getValue(1));
7927 // To match the actual intent better, we should read the output from X15 here
7928 // again (instead of potentially spilling it to the stack), but rereading Size
7929 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7930 // here.
7931
7932 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7933 DAG.getConstant(4, dl, MVT::i64));
7934 return Chain;
7935}
7936
7937SDValue
7938AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7939 SelectionDAG &DAG) const {
7940 assert(Subtarget->isTargetWindows() &&
7941 "Only Windows alloca probing supported");
7942 SDLoc dl(Op);
7943 // Get the inputs.
7944 SDNode *Node = Op.getNode();
7945 SDValue Chain = Op.getOperand(0);
7946 SDValue Size = Op.getOperand(1);
7947 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7948 EVT VT = Node->getValueType(0);
7949
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00007950 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7951 "no-stack-arg-probe")) {
7952 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7953 Chain = SP.getValue(1);
7954 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7955 if (Align)
7956 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7957 DAG.getConstant(-(uint64_t)Align, dl, VT));
7958 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7959 SDValue Ops[2] = {SP, Chain};
7960 return DAG.getMergeValues(Ops, dl);
7961 }
7962
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007963 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7964
7965 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7966
7967 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7968 Chain = SP.getValue(1);
7969 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00007970 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007971 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7972 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00007973 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007974
7975 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7976 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7977
7978 SDValue Ops[2] = {SP, Chain};
7979 return DAG.getMergeValues(Ops, dl);
7980}
7981
Tim Northover3b0846e2014-05-24 12:50:23 +00007982/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7983/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7984/// specified in the intrinsic calls.
7985bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7986 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00007987 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00007988 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007989 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007990 switch (Intrinsic) {
7991 case Intrinsic::aarch64_neon_ld2:
7992 case Intrinsic::aarch64_neon_ld3:
7993 case Intrinsic::aarch64_neon_ld4:
7994 case Intrinsic::aarch64_neon_ld1x2:
7995 case Intrinsic::aarch64_neon_ld1x3:
7996 case Intrinsic::aarch64_neon_ld1x4:
7997 case Intrinsic::aarch64_neon_ld2lane:
7998 case Intrinsic::aarch64_neon_ld3lane:
7999 case Intrinsic::aarch64_neon_ld4lane:
8000 case Intrinsic::aarch64_neon_ld2r:
8001 case Intrinsic::aarch64_neon_ld3r:
8002 case Intrinsic::aarch64_neon_ld4r: {
8003 Info.opc = ISD::INTRINSIC_W_CHAIN;
8004 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008005 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008006 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8007 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8008 Info.offset = 0;
8009 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008010 // volatile loads with NEON intrinsics not supported
8011 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008012 return true;
8013 }
8014 case Intrinsic::aarch64_neon_st2:
8015 case Intrinsic::aarch64_neon_st3:
8016 case Intrinsic::aarch64_neon_st4:
8017 case Intrinsic::aarch64_neon_st1x2:
8018 case Intrinsic::aarch64_neon_st1x3:
8019 case Intrinsic::aarch64_neon_st1x4:
8020 case Intrinsic::aarch64_neon_st2lane:
8021 case Intrinsic::aarch64_neon_st3lane:
8022 case Intrinsic::aarch64_neon_st4lane: {
8023 Info.opc = ISD::INTRINSIC_VOID;
8024 // Conservatively set memVT to the entire set of vectors stored.
8025 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008026 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008027 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8028 if (!ArgTy->isVectorTy())
8029 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008030 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008031 }
8032 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8033 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8034 Info.offset = 0;
8035 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008036 // volatile stores with NEON intrinsics not supported
8037 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008038 return true;
8039 }
8040 case Intrinsic::aarch64_ldaxr:
8041 case Intrinsic::aarch64_ldxr: {
8042 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8043 Info.opc = ISD::INTRINSIC_W_CHAIN;
8044 Info.memVT = MVT::getVT(PtrTy->getElementType());
8045 Info.ptrVal = I.getArgOperand(0);
8046 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008047 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008048 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008049 return true;
8050 }
8051 case Intrinsic::aarch64_stlxr:
8052 case Intrinsic::aarch64_stxr: {
8053 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8054 Info.opc = ISD::INTRINSIC_W_CHAIN;
8055 Info.memVT = MVT::getVT(PtrTy->getElementType());
8056 Info.ptrVal = I.getArgOperand(1);
8057 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008058 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008059 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008060 return true;
8061 }
8062 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008063 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008064 Info.opc = ISD::INTRINSIC_W_CHAIN;
8065 Info.memVT = MVT::i128;
8066 Info.ptrVal = I.getArgOperand(0);
8067 Info.offset = 0;
8068 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008069 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008070 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008071 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008072 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008073 Info.opc = ISD::INTRINSIC_W_CHAIN;
8074 Info.memVT = MVT::i128;
8075 Info.ptrVal = I.getArgOperand(2);
8076 Info.offset = 0;
8077 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008078 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008079 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008080 default:
8081 break;
8082 }
8083
8084 return false;
8085}
8086
John Brawne3b44f92018-03-23 14:47:07 +00008087bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8088 ISD::LoadExtType ExtTy,
8089 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008090 // TODO: This may be worth removing. Check regression tests for diffs.
8091 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8092 return false;
8093
John Brawne3b44f92018-03-23 14:47:07 +00008094 // If we're reducing the load width in order to avoid having to use an extra
8095 // instruction to do extension then it's probably a good idea.
8096 if (ExtTy != ISD::NON_EXTLOAD)
8097 return true;
8098 // Don't reduce load width if it would prevent us from combining a shift into
8099 // the offset.
8100 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8101 assert(Mem);
8102 const SDValue &Base = Mem->getBasePtr();
8103 if (Base.getOpcode() == ISD::ADD &&
8104 Base.getOperand(1).getOpcode() == ISD::SHL &&
8105 Base.getOperand(1).hasOneUse() &&
8106 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8107 // The shift can be combined if it matches the size of the value being
8108 // loaded (and so reducing the width would make it not match).
8109 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8110 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8111 if (ShiftAmount == Log2_32(LoadBytes))
8112 return false;
8113 }
8114 // We have no reason to disallow reducing the load width, so allow it.
8115 return true;
8116}
8117
Tim Northover3b0846e2014-05-24 12:50:23 +00008118// Truncations from 64-bit GPR to 32-bit GPR is free.
8119bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8120 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8121 return false;
8122 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8123 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008124 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008125}
8126bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008127 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008128 return false;
8129 unsigned NumBits1 = VT1.getSizeInBits();
8130 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008131 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008132}
8133
Chad Rosier54390052015-02-23 19:15:16 +00008134/// Check if it is profitable to hoist instruction in then/else to if.
8135/// Not profitable if I and it's user can form a FMA instruction
8136/// because we prefer FMSUB/FMADD.
8137bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8138 if (I->getOpcode() != Instruction::FMul)
8139 return true;
8140
Davide Italiano3e9986f2017-04-18 00:29:54 +00008141 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008142 return true;
8143
8144 Instruction *User = I->user_back();
8145
8146 if (User &&
8147 !(User->getOpcode() == Instruction::FSub ||
8148 User->getOpcode() == Instruction::FAdd))
8149 return true;
8150
8151 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008152 const DataLayout &DL = I->getModule()->getDataLayout();
8153 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008154
Eric Christopher114fa1c2016-02-29 22:50:49 +00008155 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8156 isOperationLegalOrCustom(ISD::FMA, VT) &&
8157 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8158 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008159}
8160
Tim Northover3b0846e2014-05-24 12:50:23 +00008161// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8162// 64-bit GPR.
8163bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8164 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8165 return false;
8166 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8167 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008168 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008169}
8170bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008171 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008172 return false;
8173 unsigned NumBits1 = VT1.getSizeInBits();
8174 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008175 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008176}
8177
8178bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8179 EVT VT1 = Val.getValueType();
8180 if (isZExtFree(VT1, VT2)) {
8181 return true;
8182 }
8183
8184 if (Val.getOpcode() != ISD::LOAD)
8185 return false;
8186
8187 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008188 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8189 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8190 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008191}
8192
Quentin Colombet6843ac42015-03-31 20:52:32 +00008193bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8194 if (isa<FPExtInst>(Ext))
8195 return false;
8196
Haicheng Wu50692a22017-08-01 21:26:45 +00008197 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008198 if (Ext->getType()->isVectorTy())
8199 return false;
8200
8201 for (const Use &U : Ext->uses()) {
8202 // The extension is free if we can fold it with a left shift in an
8203 // addressing mode or an arithmetic operation: add, sub, and cmp.
8204
8205 // Is there a shift?
8206 const Instruction *Instr = cast<Instruction>(U.getUser());
8207
8208 // Is this a constant shift?
8209 switch (Instr->getOpcode()) {
8210 case Instruction::Shl:
8211 if (!isa<ConstantInt>(Instr->getOperand(1)))
8212 return false;
8213 break;
8214 case Instruction::GetElementPtr: {
8215 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008216 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008217 std::advance(GTI, U.getOperandNo()-1);
8218 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008219 // This extension will end up with a shift because of the scaling factor.
8220 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8221 // Get the shift amount based on the scaling factor:
8222 // log2(sizeof(IdxTy)) - log2(8).
8223 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008224 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008225 // Is the constant foldable in the shift of the addressing mode?
8226 // I.e., shift amount is between 1 and 4 inclusive.
8227 if (ShiftAmt == 0 || ShiftAmt > 4)
8228 return false;
8229 break;
8230 }
8231 case Instruction::Trunc:
8232 // Check if this is a noop.
8233 // trunc(sext ty1 to ty2) to ty1.
8234 if (Instr->getType() == Ext->getOperand(0)->getType())
8235 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008236 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008237 default:
8238 return false;
8239 }
8240
8241 // At this point we can use the bfm family, so this extension is free
8242 // for that use.
8243 }
8244 return true;
8245}
8246
Florian Hahn3b251962019-02-05 10:27:40 +00008247/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8248/// or upper half of the vector elements.
8249static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8250 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8251 auto *FullVT = cast<VectorType>(FullV->getType());
8252 auto *HalfVT = cast<VectorType>(HalfV->getType());
8253 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8254 };
8255
8256 auto extractHalf = [](Value *FullV, Value *HalfV) {
8257 auto *FullVT = cast<VectorType>(FullV->getType());
8258 auto *HalfVT = cast<VectorType>(HalfV->getType());
8259 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8260 };
8261
8262 Constant *M1, *M2;
8263 Value *S1Op1, *S2Op1;
8264 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8265 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8266 return false;
8267
8268 // Check that the operands are half as wide as the result and we extract
8269 // half of the elements of the input vectors.
8270 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8271 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8272 return false;
8273
8274 // Check the mask extracts either the lower or upper half of vector
8275 // elements.
8276 int M1Start = -1;
8277 int M2Start = -1;
8278 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8279 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8280 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8281 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8282 return false;
8283
8284 return true;
8285}
8286
8287/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8288/// of the vector elements.
8289static bool areExtractExts(Value *Ext1, Value *Ext2) {
8290 auto areExtDoubled = [](Instruction *Ext) {
8291 return Ext->getType()->getScalarSizeInBits() ==
8292 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8293 };
8294
8295 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8296 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8297 !areExtDoubled(cast<Instruction>(Ext1)) ||
8298 !areExtDoubled(cast<Instruction>(Ext2)))
8299 return false;
8300
8301 return true;
8302}
8303
8304/// Check if sinking \p I's operands to I's basic block is profitable, because
8305/// the operands can be folded into a target instruction, e.g.
8306/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8307bool AArch64TargetLowering::shouldSinkOperands(
8308 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8309 if (!I->getType()->isVectorTy())
8310 return false;
8311
8312 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8313 switch (II->getIntrinsicID()) {
8314 case Intrinsic::aarch64_neon_umull:
8315 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8316 return false;
8317 Ops.push_back(&II->getOperandUse(0));
8318 Ops.push_back(&II->getOperandUse(1));
8319 return true;
8320 default:
8321 return false;
8322 }
8323 }
8324
8325 switch (I->getOpcode()) {
8326 case Instruction::Sub:
8327 case Instruction::Add: {
8328 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8329 return false;
8330
8331 // If the exts' operands extract either the lower or upper elements, we
8332 // can sink them too.
8333 auto Ext1 = cast<Instruction>(I->getOperand(0));
8334 auto Ext2 = cast<Instruction>(I->getOperand(1));
8335 if (areExtractShuffleVectors(Ext1, Ext2)) {
8336 Ops.push_back(&Ext1->getOperandUse(0));
8337 Ops.push_back(&Ext2->getOperandUse(0));
8338 }
8339
8340 Ops.push_back(&I->getOperandUse(0));
8341 Ops.push_back(&I->getOperandUse(1));
8342
8343 return true;
8344 }
8345 default:
8346 return false;
8347 }
8348 return false;
8349}
8350
Tim Northover3b0846e2014-05-24 12:50:23 +00008351bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8352 unsigned &RequiredAligment) const {
8353 if (!LoadedType.isSimple() ||
8354 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8355 return false;
8356 // Cyclone supports unaligned accesses.
8357 RequiredAligment = 0;
8358 unsigned NumBits = LoadedType.getSizeInBits();
8359 return NumBits == 32 || NumBits == 64;
8360}
8361
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008362/// A helper function for determining the number of interleaved accesses we
8363/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008364unsigned
8365AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8366 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008367 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8368}
8369
Geoff Berryb1e87142017-07-14 21:44:12 +00008370MachineMemOperand::Flags
8371AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8372 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8373 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8374 return MOStridedAccess;
8375 return MachineMemOperand::MONone;
8376}
8377
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008378bool AArch64TargetLowering::isLegalInterleavedAccessType(
8379 VectorType *VecTy, const DataLayout &DL) const {
8380
8381 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8382 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8383
8384 // Ensure the number of vector elements is greater than 1.
8385 if (VecTy->getNumElements() < 2)
8386 return false;
8387
8388 // Ensure the element type is legal.
8389 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8390 return false;
8391
8392 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8393 // 128 will be split into multiple interleaved accesses.
8394 return VecSize == 64 || VecSize % 128 == 0;
8395}
8396
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008397/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008398///
8399/// E.g. Lower an interleaved load (Factor = 2):
8400/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8401/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8402/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8403///
8404/// Into:
8405/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8406/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8407/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8408bool AArch64TargetLowering::lowerInterleavedLoad(
8409 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8410 ArrayRef<unsigned> Indices, unsigned Factor) const {
8411 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8412 "Invalid interleave factor");
8413 assert(!Shuffles.empty() && "Empty shufflevector input");
8414 assert(Shuffles.size() == Indices.size() &&
8415 "Unmatched number of shufflevectors and indices");
8416
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008417 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008418
8419 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008420
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008421 // Skip if we do not have NEON and skip illegal vector types. We can
8422 // "legalize" wide vector types into multiple interleaved accesses as long as
8423 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008424 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008425 return false;
8426
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008427 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8428
Hao Liu7ec8ee32015-06-26 02:32:07 +00008429 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8430 // load integer vectors first and then convert to pointer vectors.
8431 Type *EltTy = VecTy->getVectorElementType();
8432 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008433 VecTy =
8434 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008435
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008436 IRBuilder<> Builder(LI);
8437
8438 // The base address of the load.
8439 Value *BaseAddr = LI->getPointerOperand();
8440
8441 if (NumLoads > 1) {
8442 // If we're going to generate more than one load, reset the sub-vector type
8443 // to something legal.
8444 VecTy = VectorType::get(VecTy->getVectorElementType(),
8445 VecTy->getVectorNumElements() / NumLoads);
8446
8447 // We will compute the pointer operand of each load from the original base
8448 // address using GEPs. Cast the base address to a pointer to the scalar
8449 // element type.
8450 BaseAddr = Builder.CreateBitCast(
8451 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8452 LI->getPointerAddressSpace()));
8453 }
8454
Hao Liu7ec8ee32015-06-26 02:32:07 +00008455 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8456 Type *Tys[2] = {VecTy, PtrTy};
8457 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8458 Intrinsic::aarch64_neon_ld3,
8459 Intrinsic::aarch64_neon_ld4};
8460 Function *LdNFunc =
8461 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8462
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008463 // Holds sub-vectors extracted from the load intrinsic return values. The
8464 // sub-vectors are associated with the shufflevector instructions they will
8465 // replace.
8466 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008467
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008468 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008469
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008470 // If we're generating more than one load, compute the base address of
8471 // subsequent loads as an offset from the previous.
8472 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008473 BaseAddr =
8474 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8475 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008476
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008477 CallInst *LdN = Builder.CreateCall(
8478 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008479
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008480 // Extract and store the sub-vectors returned by the load intrinsic.
8481 for (unsigned i = 0; i < Shuffles.size(); i++) {
8482 ShuffleVectorInst *SVI = Shuffles[i];
8483 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008484
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008485 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8486
8487 // Convert the integer vector to pointer vector if the element is pointer.
8488 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008489 SubVec = Builder.CreateIntToPtr(
8490 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8491 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008492 SubVecs[SVI].push_back(SubVec);
8493 }
8494 }
8495
8496 // Replace uses of the shufflevector instructions with the sub-vectors
8497 // returned by the load intrinsic. If a shufflevector instruction is
8498 // associated with more than one sub-vector, those sub-vectors will be
8499 // concatenated into a single wide vector.
8500 for (ShuffleVectorInst *SVI : Shuffles) {
8501 auto &SubVec = SubVecs[SVI];
8502 auto *WideVec =
8503 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8504 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008505 }
8506
8507 return true;
8508}
8509
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008510/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008511///
8512/// E.g. Lower an interleaved store (Factor = 3):
8513/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008514/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008515/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8516///
8517/// Into:
8518/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8519/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8520/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8521/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8522///
8523/// Note that the new shufflevectors will be removed and we'll only generate one
8524/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008525///
8526/// Example for a more general valid mask (Factor 3). Lower:
8527/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8528/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8529/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8530///
8531/// Into:
8532/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8533/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8534/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8535/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008536bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8537 ShuffleVectorInst *SVI,
8538 unsigned Factor) const {
8539 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8540 "Invalid interleave factor");
8541
8542 VectorType *VecTy = SVI->getType();
8543 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8544 "Invalid interleaved store");
8545
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008546 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008547 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008548 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008549
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008550 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008551
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008552 // Skip if we do not have NEON and skip illegal vector types. We can
8553 // "legalize" wide vector types into multiple interleaved accesses as long as
8554 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008555 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008556 return false;
8557
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008558 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8559
Hao Liu7ec8ee32015-06-26 02:32:07 +00008560 Value *Op0 = SVI->getOperand(0);
8561 Value *Op1 = SVI->getOperand(1);
8562 IRBuilder<> Builder(SI);
8563
8564 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8565 // vectors to integer vectors.
8566 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008567 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008568 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008569
8570 // Convert to the corresponding integer vector.
8571 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8572 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8573 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8574
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008575 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008576 }
8577
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008578 // The base address of the store.
8579 Value *BaseAddr = SI->getPointerOperand();
8580
8581 if (NumStores > 1) {
8582 // If we're going to generate more than one store, reset the lane length
8583 // and sub-vector type to something legal.
8584 LaneLen /= NumStores;
8585 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8586
8587 // We will compute the pointer operand of each store from the original base
8588 // address using GEPs. Cast the base address to a pointer to the scalar
8589 // element type.
8590 BaseAddr = Builder.CreateBitCast(
8591 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8592 SI->getPointerAddressSpace()));
8593 }
8594
8595 auto Mask = SVI->getShuffleMask();
8596
Hao Liu7ec8ee32015-06-26 02:32:07 +00008597 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8598 Type *Tys[2] = {SubVecTy, PtrTy};
8599 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8600 Intrinsic::aarch64_neon_st3,
8601 Intrinsic::aarch64_neon_st4};
8602 Function *StNFunc =
8603 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8604
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008605 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008606
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008607 SmallVector<Value *, 5> Ops;
8608
8609 // Split the shufflevector operands into sub vectors for the new stN call.
8610 for (unsigned i = 0; i < Factor; i++) {
8611 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8612 if (Mask[IdxI] >= 0) {
8613 Ops.push_back(Builder.CreateShuffleVector(
8614 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8615 } else {
8616 unsigned StartMask = 0;
8617 for (unsigned j = 1; j < LaneLen; j++) {
8618 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8619 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8620 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8621 break;
8622 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008623 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008624 // Note: Filling undef gaps with random elements is ok, since
8625 // those elements were being written anyway (with undefs).
8626 // In the case of all undefs we're defaulting to using elems from 0
8627 // Note: StartMask cannot be negative, it's checked in
8628 // isReInterleaveMask
8629 Ops.push_back(Builder.CreateShuffleVector(
8630 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008631 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008632 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008633
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008634 // If we generating more than one store, we compute the base address of
8635 // subsequent stores as an offset from the previous.
8636 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008637 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8638 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008639
8640 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8641 Builder.CreateCall(StNFunc, Ops);
8642 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008643 return true;
8644}
8645
Tim Northover3b0846e2014-05-24 12:50:23 +00008646static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8647 unsigned AlignCheck) {
8648 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8649 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8650}
8651
8652EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8653 unsigned SrcAlign, bool IsMemset,
8654 bool ZeroMemset,
8655 bool MemcpyStrSrc,
8656 MachineFunction &MF) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008657 const Function &F = MF.getFunction();
JF Bastien29200612018-09-06 16:03:32 +00008658 bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8659 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8660 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8661 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8662 // taken one instruction to materialize the v2i64 zero and one store (with
8663 // restrictive addressing mode). Just do i64 stores.
8664 bool IsSmallMemset = IsMemset && Size < 32;
8665 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8666 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8667 return true;
8668 bool Fast;
8669 return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8670 };
8671
8672 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8673 AlignmentIsAcceptable(MVT::v2i64, 16))
8674 return MVT::v2i64;
8675 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008676 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008677 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008678 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008679 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008680 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008681 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008682}
8683
8684// 12-bit optionally shifted immediates are legal for adds.
8685bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008686 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008687 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8688 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008689 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008690 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008691 // Same encoding for add/sub, just flip the sign.
8692 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008693 bool IsLegal = ((Immed >> 12) == 0 ||
8694 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008695 LLVM_DEBUG(dbgs() << "Is " << Immed
8696 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008697 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008698}
8699
8700// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8701// immediates is the same as for an add or a sub.
8702bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008703 return isLegalAddImmediate(Immed);
8704}
8705
8706/// isLegalAddressingMode - Return true if the addressing mode represented
8707/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008708bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8709 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008710 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008711 // AArch64 has five basic addressing modes:
8712 // reg
8713 // reg + 9-bit signed offset
8714 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8715 // reg1 + reg2
8716 // reg + SIZE_IN_BYTES * reg
8717
8718 // No global is ever allowed as a base.
8719 if (AM.BaseGV)
8720 return false;
8721
8722 // No reg+reg+imm addressing.
8723 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8724 return false;
8725
8726 // check reg + imm case:
8727 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8728 uint64_t NumBytes = 0;
8729 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008730 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008731 NumBytes = NumBits / 8;
8732 if (!isPowerOf2_64(NumBits))
8733 NumBytes = 0;
8734 }
8735
8736 if (!AM.Scale) {
8737 int64_t Offset = AM.BaseOffs;
8738
8739 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008740 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008741 return true;
8742
8743 // 12-bit unsigned offset
8744 unsigned shift = Log2_64(NumBytes);
8745 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8746 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8747 (Offset >> shift) << shift == Offset)
8748 return true;
8749 return false;
8750 }
8751
8752 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8753
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008754 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008755}
8756
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008757bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8758 // Consider splitting large offset of struct or array.
8759 return true;
8760}
8761
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008762int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8763 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008764 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008765 // Scaling factors are not free at all.
8766 // Operands | Rt Latency
8767 // -------------------------------------------
8768 // Rt, [Xn, Xm] | 4
8769 // -------------------------------------------
8770 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8771 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008772 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008773 // Scale represents reg2 * scale, thus account for 1 if
8774 // it is not equal to 0 or 1.
8775 return AM.Scale != 0 && AM.Scale != 1;
8776 return -1;
8777}
8778
8779bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8780 VT = VT.getScalarType();
8781
8782 if (!VT.isSimple())
8783 return false;
8784
8785 switch (VT.getSimpleVT().SimpleTy) {
8786 case MVT::f32:
8787 case MVT::f64:
8788 return true;
8789 default:
8790 break;
8791 }
8792
8793 return false;
8794}
8795
8796const MCPhysReg *
8797AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8798 // LR is a callee-save register, but we must treat it as clobbered by any call
8799 // site. Hence we include LR in the scratch registers, which are in turn added
8800 // as implicit-defs for stackmaps and patchpoints.
8801 static const MCPhysReg ScratchRegs[] = {
8802 AArch64::X16, AArch64::X17, AArch64::LR, 0
8803 };
8804 return ScratchRegs;
8805}
8806
8807bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008808AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8809 CombineLevel Level) const {
8810 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008811 EVT VT = N->getValueType(0);
8812 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8813 // it with shift to let it be lowered to UBFX.
8814 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8815 isa<ConstantSDNode>(N->getOperand(1))) {
8816 uint64_t TruncMask = N->getConstantOperandVal(1);
8817 if (isMask_64(TruncMask) &&
8818 N->getOperand(0).getOpcode() == ISD::SRL &&
8819 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8820 return false;
8821 }
8822 return true;
8823}
8824
8825bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8826 Type *Ty) const {
8827 assert(Ty->isIntegerTy());
8828
8829 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8830 if (BitSize == 0)
8831 return false;
8832
8833 int64_t Val = Imm.getSExtValue();
8834 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8835 return true;
8836
8837 if ((int64_t)Val < 0)
8838 Val = ~Val;
8839 if (BitSize == 32)
8840 Val &= (1LL << 32) - 1;
8841
8842 unsigned LZ = countLeadingZeros((uint64_t)Val);
8843 unsigned Shift = (63 - LZ) / 16;
8844 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008845 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008846}
8847
Sebastian Pop41073e82018-03-06 16:54:55 +00008848bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8849 unsigned Index) const {
8850 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8851 return false;
8852
8853 return (Index == 0 || Index == ResVT.getVectorNumElements());
8854}
8855
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008856/// Turn vector tests of the signbit in the form of:
8857/// xor (sra X, elt_size(X)-1), -1
8858/// into:
8859/// cmge X, X, #0
8860static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8861 const AArch64Subtarget *Subtarget) {
8862 EVT VT = N->getValueType(0);
8863 if (!Subtarget->hasNEON() || !VT.isVector())
8864 return SDValue();
8865
8866 // There must be a shift right algebraic before the xor, and the xor must be a
8867 // 'not' operation.
8868 SDValue Shift = N->getOperand(0);
8869 SDValue Ones = N->getOperand(1);
8870 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8871 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8872 return SDValue();
8873
8874 // The shift should be smearing the sign bit across each vector element.
8875 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8876 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8877 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8878 return SDValue();
8879
8880 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8881}
8882
Tim Northover3b0846e2014-05-24 12:50:23 +00008883// Generate SUBS and CSEL for integer abs.
8884static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8885 EVT VT = N->getValueType(0);
8886
8887 SDValue N0 = N->getOperand(0);
8888 SDValue N1 = N->getOperand(1);
8889 SDLoc DL(N);
8890
8891 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8892 // and change it to SUB and CSEL.
8893 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8894 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8895 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8896 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8897 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008898 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008899 N0.getOperand(0));
8900 // Generate SUBS & CSEL.
8901 SDValue Cmp =
8902 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008903 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008904 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008905 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008906 SDValue(Cmp.getNode(), 1));
8907 }
8908 return SDValue();
8909}
8910
Tim Northover3b0846e2014-05-24 12:50:23 +00008911static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8912 TargetLowering::DAGCombinerInfo &DCI,
8913 const AArch64Subtarget *Subtarget) {
8914 if (DCI.isBeforeLegalizeOps())
8915 return SDValue();
8916
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008917 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8918 return Cmp;
8919
Tim Northover3b0846e2014-05-24 12:50:23 +00008920 return performIntegerAbsCombine(N, DAG);
8921}
8922
Chad Rosier17020f92014-07-23 14:57:52 +00008923SDValue
8924AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8925 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00008926 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008927 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008928 if (isIntDivCheap(N->getValueType(0), Attr))
8929 return SDValue(N,0); // Lower SDIV as SDIV
8930
Chad Rosier17020f92014-07-23 14:57:52 +00008931 // fold (sdiv X, pow2)
8932 EVT VT = N->getValueType(0);
8933 if ((VT != MVT::i32 && VT != MVT::i64) ||
8934 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8935 return SDValue();
8936
8937 SDLoc DL(N);
8938 SDValue N0 = N->getOperand(0);
8939 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008940 SDValue Zero = DAG.getConstant(0, DL, VT);
8941 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008942
8943 // Add (N0 < 0) ? Pow2 - 1 : 0;
8944 SDValue CCVal;
8945 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8946 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8947 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8948
Craig Toppera568a272018-07-30 21:04:34 +00008949 Created.push_back(Cmp.getNode());
8950 Created.push_back(Add.getNode());
8951 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00008952
8953 // Divide by pow2.
8954 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008955 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008956
8957 // If we're dividing by a positive value, we're done. Otherwise, we must
8958 // negate the result.
8959 if (Divisor.isNonNegative())
8960 return SRA;
8961
Craig Toppera568a272018-07-30 21:04:34 +00008962 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008963 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008964}
8965
Tim Northover3b0846e2014-05-24 12:50:23 +00008966static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8967 TargetLowering::DAGCombinerInfo &DCI,
8968 const AArch64Subtarget *Subtarget) {
8969 if (DCI.isBeforeLegalizeOps())
8970 return SDValue();
8971
Chad Rosier31ee8132016-11-11 17:07:37 +00008972 // The below optimizations require a constant RHS.
8973 if (!isa<ConstantSDNode>(N->getOperand(1)))
8974 return SDValue();
8975
8976 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8977 const APInt &ConstValue = C->getAPIntValue();
8978
Tim Northover3b0846e2014-05-24 12:50:23 +00008979 // Multiplication of a power of two plus/minus one can be done more
8980 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8981 // future CPUs have a cheaper MADD instruction, this may need to be
8982 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8983 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008984 // More aggressively, some multiplications N0 * C can be lowered to
8985 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8986 // e.g. 6=3*2=(2+1)*2.
8987 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8988 // which equals to (1+2)*16-(1+2).
8989 SDValue N0 = N->getOperand(0);
8990 // TrailingZeroes is used to test if the mul can be lowered to
8991 // shift+add+shift.
8992 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8993 if (TrailingZeroes) {
8994 // Conservatively do not lower to shift+add+shift if the mul might be
8995 // folded into smul or umul.
8996 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8997 isZeroExtended(N0.getNode(), DAG)))
8998 return SDValue();
8999 // Conservatively do not lower to shift+add+shift if the mul might be
9000 // folded into madd or msub.
9001 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9002 N->use_begin()->getOpcode() == ISD::SUB))
9003 return SDValue();
9004 }
9005 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9006 // and shift+add+shift.
9007 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9008
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009009 unsigned ShiftAmt, AddSubOpc;
9010 // Is the shifted value the LHS operand of the add/sub?
9011 bool ShiftValUseIsN0 = true;
9012 // Do we need to negate the result?
9013 bool NegateResult = false;
9014
Chad Rosier31ee8132016-11-11 17:07:37 +00009015 if (ConstValue.isNonNegative()) {
9016 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00009017 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00009018 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9019 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009020 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00009021 if (SCVMinus1.isPowerOf2()) {
9022 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009023 AddSubOpc = ISD::ADD;
9024 } else if (CVPlus1.isPowerOf2()) {
9025 ShiftAmt = CVPlus1.logBase2();
9026 AddSubOpc = ISD::SUB;
9027 } else
9028 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00009029 } else {
9030 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00009031 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009032 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009033 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009034 if (CVNegPlus1.isPowerOf2()) {
9035 ShiftAmt = CVNegPlus1.logBase2();
9036 AddSubOpc = ISD::SUB;
9037 ShiftValUseIsN0 = false;
9038 } else if (CVNegMinus1.isPowerOf2()) {
9039 ShiftAmt = CVNegMinus1.logBase2();
9040 AddSubOpc = ISD::ADD;
9041 NegateResult = true;
9042 } else
9043 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009044 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009045
9046 SDLoc DL(N);
9047 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009048 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009049 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9050
9051 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9052 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9053 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009054 assert(!(NegateResult && TrailingZeroes) &&
9055 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009056 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009057 if (NegateResult)
9058 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9059 // Shift the result.
9060 if (TrailingZeroes)
9061 return DAG.getNode(ISD::SHL, DL, VT, Res,
9062 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9063 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00009064}
9065
Jim Grosbachf7502c42014-07-18 00:40:52 +00009066static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9067 SelectionDAG &DAG) {
9068 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9069 // optimize away operation when it's from a constant.
9070 //
9071 // The general transformation is:
9072 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9073 // AND(VECTOR_CMP(x,y), constant2)
9074 // constant2 = UNARYOP(constant)
9075
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009076 // Early exit if this isn't a vector operation, the operand of the
9077 // unary operation isn't a bitwise AND, or if the sizes of the operations
9078 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009079 EVT VT = N->getValueType(0);
9080 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009081 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9082 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009083 return SDValue();
9084
Jim Grosbach724e4382014-07-23 20:41:43 +00009085 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009086 // make the transformation for non-constant splats as well, but it's unclear
9087 // that would be a benefit as it would not eliminate any operations, just
9088 // perform one more step in scalar code before moving to the vector unit.
9089 if (BuildVectorSDNode *BV =
9090 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009091 // Bail out if the vector isn't a constant.
9092 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009093 return SDValue();
9094
9095 // Everything checks out. Build up the new and improved node.
9096 SDLoc DL(N);
9097 EVT IntVT = BV->getValueType(0);
9098 // Create a new constant of the appropriate type for the transformed
9099 // DAG.
9100 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9101 // The AND node needs bitcasts to/from an integer vector type around it.
9102 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9103 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9104 N->getOperand(0)->getOperand(0), MaskConst);
9105 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9106 return Res;
9107 }
9108
9109 return SDValue();
9110}
9111
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009112static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9113 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009114 // First try to optimize away the conversion when it's conditionally from
9115 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009116 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009117 return Res;
9118
Tim Northover3b0846e2014-05-24 12:50:23 +00009119 EVT VT = N->getValueType(0);
9120 if (VT != MVT::f32 && VT != MVT::f64)
9121 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009122
Tim Northover3b0846e2014-05-24 12:50:23 +00009123 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009124 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009125 return SDValue();
9126
9127 // If the result of an integer load is only used by an integer-to-float
9128 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009129 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009130 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009131 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009132 // Do not change the width of a volatile load.
9133 !cast<LoadSDNode>(N0)->isVolatile()) {
9134 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9135 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009136 LN0->getPointerInfo(), LN0->getAlignment(),
9137 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009138
9139 // Make sure successors of the original load stay after it by updating them
9140 // to use the new Chain.
9141 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9142
9143 unsigned Opcode =
9144 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9145 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9146 }
9147
9148 return SDValue();
9149}
9150
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009151/// Fold a floating-point multiply by power of two into floating-point to
9152/// fixed-point conversion.
9153static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009154 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009155 const AArch64Subtarget *Subtarget) {
9156 if (!Subtarget->hasNEON())
9157 return SDValue();
9158
9159 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009160 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9161 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009162 return SDValue();
9163
9164 SDValue ConstVec = Op->getOperand(1);
9165 if (!isa<BuildVectorSDNode>(ConstVec))
9166 return SDValue();
9167
9168 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9169 uint32_t FloatBits = FloatTy.getSizeInBits();
9170 if (FloatBits != 32 && FloatBits != 64)
9171 return SDValue();
9172
9173 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9174 uint32_t IntBits = IntTy.getSizeInBits();
9175 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9176 return SDValue();
9177
9178 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9179 if (IntBits > FloatBits)
9180 return SDValue();
9181
9182 BitVector UndefElements;
9183 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9184 int32_t Bits = IntBits == 64 ? 64 : 32;
9185 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9186 if (C == -1 || C == 0 || C > Bits)
9187 return SDValue();
9188
9189 MVT ResTy;
9190 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9191 switch (NumLanes) {
9192 default:
9193 return SDValue();
9194 case 2:
9195 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9196 break;
9197 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009198 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009199 break;
9200 }
9201
Silviu Barangafa00ba32016-08-08 13:13:57 +00009202 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9203 return SDValue();
9204
9205 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9206 "Illegal vector type after legalization");
9207
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009208 SDLoc DL(N);
9209 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9210 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9211 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9212 SDValue FixConv =
9213 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9214 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9215 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9216 // We can handle smaller integers by generating an extra trunc.
9217 if (IntBits < FloatBits)
9218 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9219
9220 return FixConv;
9221}
9222
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009223/// Fold a floating-point divide by power of two into fixed-point to
9224/// floating-point conversion.
9225static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009226 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009227 const AArch64Subtarget *Subtarget) {
9228 if (!Subtarget->hasNEON())
9229 return SDValue();
9230
9231 SDValue Op = N->getOperand(0);
9232 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009233 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9234 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009235 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9236 return SDValue();
9237
9238 SDValue ConstVec = N->getOperand(1);
9239 if (!isa<BuildVectorSDNode>(ConstVec))
9240 return SDValue();
9241
9242 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9243 int32_t IntBits = IntTy.getSizeInBits();
9244 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9245 return SDValue();
9246
9247 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9248 int32_t FloatBits = FloatTy.getSizeInBits();
9249 if (FloatBits != 32 && FloatBits != 64)
9250 return SDValue();
9251
9252 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9253 if (IntBits > FloatBits)
9254 return SDValue();
9255
9256 BitVector UndefElements;
9257 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9258 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9259 if (C == -1 || C == 0 || C > FloatBits)
9260 return SDValue();
9261
9262 MVT ResTy;
9263 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9264 switch (NumLanes) {
9265 default:
9266 return SDValue();
9267 case 2:
9268 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9269 break;
9270 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009271 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009272 break;
9273 }
9274
Tim Northover85cf5642016-08-26 18:52:31 +00009275 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9276 return SDValue();
9277
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009278 SDLoc DL(N);
9279 SDValue ConvInput = Op.getOperand(0);
9280 bool IsSigned = Opc == ISD::SINT_TO_FP;
9281 if (IntBits < FloatBits)
9282 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9283 ResTy, ConvInput);
9284
9285 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9286 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9287 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9288 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9289 DAG.getConstant(C, DL, MVT::i32));
9290}
9291
Tim Northover3b0846e2014-05-24 12:50:23 +00009292/// An EXTR instruction is made up of two shifts, ORed together. This helper
9293/// searches for and classifies those shifts.
9294static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9295 bool &FromHi) {
9296 if (N.getOpcode() == ISD::SHL)
9297 FromHi = false;
9298 else if (N.getOpcode() == ISD::SRL)
9299 FromHi = true;
9300 else
9301 return false;
9302
9303 if (!isa<ConstantSDNode>(N.getOperand(1)))
9304 return false;
9305
9306 ShiftAmount = N->getConstantOperandVal(1);
9307 Src = N->getOperand(0);
9308 return true;
9309}
9310
9311/// EXTR instruction extracts a contiguous chunk of bits from two existing
9312/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009313/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9314/// with an EXTR. Can't quite be done in TableGen because the two immediates
9315/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009316static SDValue tryCombineToEXTR(SDNode *N,
9317 TargetLowering::DAGCombinerInfo &DCI) {
9318 SelectionDAG &DAG = DCI.DAG;
9319 SDLoc DL(N);
9320 EVT VT = N->getValueType(0);
9321
9322 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9323
9324 if (VT != MVT::i32 && VT != MVT::i64)
9325 return SDValue();
9326
9327 SDValue LHS;
9328 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009329 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009330 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9331 return SDValue();
9332
9333 SDValue RHS;
9334 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009335 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009336 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9337 return SDValue();
9338
9339 // If they're both trying to come from the high part of the register, they're
9340 // not really an EXTR.
9341 if (LHSFromHi == RHSFromHi)
9342 return SDValue();
9343
9344 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9345 return SDValue();
9346
9347 if (LHSFromHi) {
9348 std::swap(LHS, RHS);
9349 std::swap(ShiftLHS, ShiftRHS);
9350 }
9351
9352 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009353 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009354}
9355
9356static SDValue tryCombineToBSL(SDNode *N,
9357 TargetLowering::DAGCombinerInfo &DCI) {
9358 EVT VT = N->getValueType(0);
9359 SelectionDAG &DAG = DCI.DAG;
9360 SDLoc DL(N);
9361
9362 if (!VT.isVector())
9363 return SDValue();
9364
9365 SDValue N0 = N->getOperand(0);
9366 if (N0.getOpcode() != ISD::AND)
9367 return SDValue();
9368
9369 SDValue N1 = N->getOperand(1);
9370 if (N1.getOpcode() != ISD::AND)
9371 return SDValue();
9372
9373 // We only have to look for constant vectors here since the general, variable
9374 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009375 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009376 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9377 for (int i = 1; i >= 0; --i)
9378 for (int j = 1; j >= 0; --j) {
9379 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9380 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9381 if (!BVN0 || !BVN1)
9382 continue;
9383
9384 bool FoundMatch = true;
9385 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9386 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9387 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9388 if (!CN0 || !CN1 ||
9389 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9390 FoundMatch = false;
9391 break;
9392 }
9393 }
9394
9395 if (FoundMatch)
9396 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9397 N0->getOperand(1 - i), N1->getOperand(1 - j));
9398 }
9399
9400 return SDValue();
9401}
9402
9403static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9404 const AArch64Subtarget *Subtarget) {
9405 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009406 SelectionDAG &DAG = DCI.DAG;
9407 EVT VT = N->getValueType(0);
9408
9409 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9410 return SDValue();
9411
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009412 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009413 return Res;
9414
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009415 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009416 return Res;
9417
9418 return SDValue();
9419}
9420
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009421static SDValue performSRLCombine(SDNode *N,
9422 TargetLowering::DAGCombinerInfo &DCI) {
9423 SelectionDAG &DAG = DCI.DAG;
9424 EVT VT = N->getValueType(0);
9425 if (VT != MVT::i32 && VT != MVT::i64)
9426 return SDValue();
9427
9428 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9429 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9430 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9431 SDValue N0 = N->getOperand(0);
9432 if (N0.getOpcode() == ISD::BSWAP) {
9433 SDLoc DL(N);
9434 SDValue N1 = N->getOperand(1);
9435 SDValue N00 = N0.getOperand(0);
9436 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9437 uint64_t ShiftAmt = C->getZExtValue();
9438 if (VT == MVT::i32 && ShiftAmt == 16 &&
9439 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9440 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9441 if (VT == MVT::i64 && ShiftAmt == 32 &&
9442 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9443 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9444 }
9445 }
9446 return SDValue();
9447}
9448
Tim Northover3b0846e2014-05-24 12:50:23 +00009449static SDValue performBitcastCombine(SDNode *N,
9450 TargetLowering::DAGCombinerInfo &DCI,
9451 SelectionDAG &DAG) {
9452 // Wait 'til after everything is legalized to try this. That way we have
9453 // legal vector types and such.
9454 if (DCI.isBeforeLegalizeOps())
9455 return SDValue();
9456
9457 // Remove extraneous bitcasts around an extract_subvector.
9458 // For example,
9459 // (v4i16 (bitconvert
9460 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9461 // becomes
9462 // (extract_subvector ((v8i16 ...), (i64 4)))
9463
9464 // Only interested in 64-bit vectors as the ultimate result.
9465 EVT VT = N->getValueType(0);
9466 if (!VT.isVector())
9467 return SDValue();
9468 if (VT.getSimpleVT().getSizeInBits() != 64)
9469 return SDValue();
9470 // Is the operand an extract_subvector starting at the beginning or halfway
9471 // point of the vector? A low half may also come through as an
9472 // EXTRACT_SUBREG, so look for that, too.
9473 SDValue Op0 = N->getOperand(0);
9474 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9475 !(Op0->isMachineOpcode() &&
9476 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9477 return SDValue();
9478 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9479 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9480 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9481 return SDValue();
9482 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9483 if (idx != AArch64::dsub)
9484 return SDValue();
9485 // The dsub reference is equivalent to a lane zero subvector reference.
9486 idx = 0;
9487 }
9488 // Look through the bitcast of the input to the extract.
9489 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9490 return SDValue();
9491 SDValue Source = Op0->getOperand(0)->getOperand(0);
9492 // If the source type has twice the number of elements as our destination
9493 // type, we know this is an extract of the high or low half of the vector.
9494 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009495 if (!SVT.isVector() ||
9496 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009497 return SDValue();
9498
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009499 LLVM_DEBUG(
9500 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009501
9502 // Create the simplified form to just extract the low or high half of the
9503 // vector directly rather than bothering with the bitcasts.
9504 SDLoc dl(N);
9505 unsigned NumElements = VT.getVectorNumElements();
9506 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009507 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009508 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9509 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009510 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009511 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9512 Source, SubReg),
9513 0);
9514 }
9515}
9516
9517static SDValue performConcatVectorsCombine(SDNode *N,
9518 TargetLowering::DAGCombinerInfo &DCI,
9519 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009520 SDLoc dl(N);
9521 EVT VT = N->getValueType(0);
9522 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9523
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009524 // Optimize concat_vectors of truncated vectors, where the intermediate
9525 // type is illegal, to avoid said illegality, e.g.,
9526 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9527 // (v2i16 (truncate (v2i64)))))
9528 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009529 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9530 // (v4i32 (bitcast (v2i64))),
9531 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009532 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9533 // on both input and result type, so we might generate worse code.
9534 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9535 if (N->getNumOperands() == 2 &&
9536 N0->getOpcode() == ISD::TRUNCATE &&
9537 N1->getOpcode() == ISD::TRUNCATE) {
9538 SDValue N00 = N0->getOperand(0);
9539 SDValue N10 = N1->getOperand(0);
9540 EVT N00VT = N00.getValueType();
9541
9542 if (N00VT == N10.getValueType() &&
9543 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9544 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009545 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9546 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9547 for (size_t i = 0; i < Mask.size(); ++i)
9548 Mask[i] = i * 2;
9549 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9550 DAG.getVectorShuffle(
9551 MidVT, dl,
9552 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9553 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009554 }
9555 }
9556
Tim Northover3b0846e2014-05-24 12:50:23 +00009557 // Wait 'til after everything is legalized to try this. That way we have
9558 // legal vector types and such.
9559 if (DCI.isBeforeLegalizeOps())
9560 return SDValue();
9561
Tim Northover3b0846e2014-05-24 12:50:23 +00009562 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9563 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9564 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009565 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009566 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009567 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009568 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009569 }
9570
9571 // Canonicalise concat_vectors so that the right-hand vector has as few
9572 // bit-casts as possible before its real operation. The primary matching
9573 // destination for these operations will be the narrowing "2" instructions,
9574 // which depend on the operation being performed on this right-hand vector.
9575 // For example,
9576 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9577 // becomes
9578 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9579
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009580 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009581 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009582 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009583 MVT RHSTy = RHS.getValueType().getSimpleVT();
9584 // If the RHS is not a vector, this is not the pattern we're looking for.
9585 if (!RHSTy.isVector())
9586 return SDValue();
9587
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009588 LLVM_DEBUG(
9589 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009590
9591 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9592 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009593 return DAG.getNode(ISD::BITCAST, dl, VT,
9594 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9595 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9596 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009597}
9598
9599static SDValue tryCombineFixedPointConvert(SDNode *N,
9600 TargetLowering::DAGCombinerInfo &DCI,
9601 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009602 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009603 // legal vector types and such.
9604 if (DCI.isBeforeLegalizeOps())
9605 return SDValue();
9606 // Transform a scalar conversion of a value from a lane extract into a
9607 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9608 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9609 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9610 //
9611 // The second form interacts better with instruction selection and the
9612 // register allocator to avoid cross-class register copies that aren't
9613 // coalescable due to a lane reference.
9614
9615 // Check the operand and see if it originates from a lane extract.
9616 SDValue Op1 = N->getOperand(1);
9617 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9618 // Yep, no additional predication needed. Perform the transform.
9619 SDValue IID = N->getOperand(0);
9620 SDValue Shift = N->getOperand(2);
9621 SDValue Vec = Op1.getOperand(0);
9622 SDValue Lane = Op1.getOperand(1);
9623 EVT ResTy = N->getValueType(0);
9624 EVT VecResTy;
9625 SDLoc DL(N);
9626
9627 // The vector width should be 128 bits by the time we get here, even
9628 // if it started as 64 bits (the extract_vector handling will have
9629 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009630 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009631 "unexpected vector size on extract_vector_elt!");
9632 if (Vec.getValueType() == MVT::v4i32)
9633 VecResTy = MVT::v4f32;
9634 else if (Vec.getValueType() == MVT::v2i64)
9635 VecResTy = MVT::v2f64;
9636 else
Craig Topper2a30d782014-06-18 05:05:13 +00009637 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009638
9639 SDValue Convert =
9640 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9641 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9642 }
9643 return SDValue();
9644}
9645
9646// AArch64 high-vector "long" operations are formed by performing the non-high
9647// version on an extract_subvector of each operand which gets the high half:
9648//
9649// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9650//
9651// However, there are cases which don't have an extract_high explicitly, but
9652// have another operation that can be made compatible with one for free. For
9653// example:
9654//
9655// (dupv64 scalar) --> (extract_high (dup128 scalar))
9656//
9657// This routine does the actual conversion of such DUPs, once outer routines
9658// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009659// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9660// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009661static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009662 switch (N.getOpcode()) {
9663 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009664 case AArch64ISD::DUPLANE8:
9665 case AArch64ISD::DUPLANE16:
9666 case AArch64ISD::DUPLANE32:
9667 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009668 case AArch64ISD::MOVI:
9669 case AArch64ISD::MOVIshift:
9670 case AArch64ISD::MOVIedit:
9671 case AArch64ISD::MOVImsl:
9672 case AArch64ISD::MVNIshift:
9673 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009674 break;
9675 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009676 // FMOV could be supported, but isn't very useful, as it would only occur
9677 // if you passed a bitcast' floating point immediate to an eligible long
9678 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009679 return SDValue();
9680 }
9681
9682 MVT NarrowTy = N.getSimpleValueType();
9683 if (!NarrowTy.is64BitVector())
9684 return SDValue();
9685
9686 MVT ElementTy = NarrowTy.getVectorElementType();
9687 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009688 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009689
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009690 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009691 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9692 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009693 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009694}
9695
Eli Friedman29c06092019-02-08 00:23:35 +00009696static bool isEssentiallyExtractHighSubvector(SDValue N) {
9697 if (N.getOpcode() == ISD::BITCAST)
9698 N = N.getOperand(0);
9699 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9700 return false;
9701 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9702 N.getOperand(0).getValueType().getVectorNumElements() / 2;
Tim Northover3b0846e2014-05-24 12:50:23 +00009703}
9704
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009705/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009706struct GenericSetCCInfo {
9707 const SDValue *Opnd0;
9708 const SDValue *Opnd1;
9709 ISD::CondCode CC;
9710};
9711
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009712/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009713struct AArch64SetCCInfo {
9714 const SDValue *Cmp;
9715 AArch64CC::CondCode CC;
9716};
9717
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009718/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009719union SetCCInfo {
9720 GenericSetCCInfo Generic;
9721 AArch64SetCCInfo AArch64;
9722};
9723
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009724/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009725/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9726/// GenericSetCCInfo.
9727struct SetCCInfoAndKind {
9728 SetCCInfo Info;
9729 bool IsAArch64;
9730};
9731
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009732/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009733/// an
9734/// AArch64 lowered one.
9735/// \p SetCCInfo is filled accordingly.
9736/// \post SetCCInfo is meanginfull only when this function returns true.
9737/// \return True when Op is a kind of SET_CC operation.
9738static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9739 // If this is a setcc, this is straight forward.
9740 if (Op.getOpcode() == ISD::SETCC) {
9741 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9742 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9743 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9744 SetCCInfo.IsAArch64 = false;
9745 return true;
9746 }
9747 // Otherwise, check if this is a matching csel instruction.
9748 // In other words:
9749 // - csel 1, 0, cc
9750 // - csel 0, 1, !cc
9751 if (Op.getOpcode() != AArch64ISD::CSEL)
9752 return false;
9753 // Set the information about the operands.
9754 // TODO: we want the operands of the Cmp not the csel
9755 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9756 SetCCInfo.IsAArch64 = true;
9757 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9758 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9759
9760 // Check that the operands matches the constraints:
9761 // (1) Both operands must be constants.
9762 // (2) One must be 1 and the other must be 0.
9763 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9764 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9765
9766 // Check (1).
9767 if (!TValue || !FValue)
9768 return false;
9769
9770 // Check (2).
9771 if (!TValue->isOne()) {
9772 // Update the comparison when we are interested in !cc.
9773 std::swap(TValue, FValue);
9774 SetCCInfo.Info.AArch64.CC =
9775 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9776 }
9777 return TValue->isOne() && FValue->isNullValue();
9778}
9779
9780// Returns true if Op is setcc or zext of setcc.
9781static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9782 if (isSetCC(Op, Info))
9783 return true;
9784 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9785 isSetCC(Op->getOperand(0), Info));
9786}
9787
9788// The folding we want to perform is:
9789// (add x, [zext] (setcc cc ...) )
9790// -->
9791// (csel x, (add x, 1), !cc ...)
9792//
9793// The latter will get matched to a CSINC instruction.
9794static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9795 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9796 SDValue LHS = Op->getOperand(0);
9797 SDValue RHS = Op->getOperand(1);
9798 SetCCInfoAndKind InfoAndKind;
9799
9800 // If neither operand is a SET_CC, give up.
9801 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9802 std::swap(LHS, RHS);
9803 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9804 return SDValue();
9805 }
9806
9807 // FIXME: This could be generatized to work for FP comparisons.
9808 EVT CmpVT = InfoAndKind.IsAArch64
9809 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9810 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9811 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9812 return SDValue();
9813
9814 SDValue CCVal;
9815 SDValue Cmp;
9816 SDLoc dl(Op);
9817 if (InfoAndKind.IsAArch64) {
9818 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009819 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9820 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009821 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9822 } else
9823 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9824 *InfoAndKind.Info.Generic.Opnd1,
9825 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9826 CCVal, DAG, dl);
9827
9828 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009829 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009830 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9831}
9832
9833// The basic add/sub long vector instructions have variants with "2" on the end
9834// which act on the high-half of their inputs. They are normally matched by
9835// patterns like:
9836//
9837// (add (zeroext (extract_high LHS)),
9838// (zeroext (extract_high RHS)))
9839// -> uaddl2 vD, vN, vM
9840//
9841// However, if one of the extracts is something like a duplicate, this
9842// instruction can still be used profitably. This function puts the DAG into a
9843// more appropriate form for those patterns to trigger.
9844static SDValue performAddSubLongCombine(SDNode *N,
9845 TargetLowering::DAGCombinerInfo &DCI,
9846 SelectionDAG &DAG) {
9847 if (DCI.isBeforeLegalizeOps())
9848 return SDValue();
9849
9850 MVT VT = N->getSimpleValueType(0);
9851 if (!VT.is128BitVector()) {
9852 if (N->getOpcode() == ISD::ADD)
9853 return performSetccAddFolding(N, DAG);
9854 return SDValue();
9855 }
9856
9857 // Make sure both branches are extended in the same way.
9858 SDValue LHS = N->getOperand(0);
9859 SDValue RHS = N->getOperand(1);
9860 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9861 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9862 LHS.getOpcode() != RHS.getOpcode())
9863 return SDValue();
9864
9865 unsigned ExtType = LHS.getOpcode();
9866
9867 // It's not worth doing if at least one of the inputs isn't already an
9868 // extract, but we don't know which it'll be so we have to try both.
Eli Friedman29c06092019-02-08 00:23:35 +00009869 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009870 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9871 if (!RHS.getNode())
9872 return SDValue();
9873
9874 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
Eli Friedman29c06092019-02-08 00:23:35 +00009875 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009876 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9877 if (!LHS.getNode())
9878 return SDValue();
9879
9880 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9881 }
9882
9883 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9884}
9885
9886// Massage DAGs which we can use the high-half "long" operations on into
9887// something isel will recognize better. E.g.
9888//
9889// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9890// (aarch64_neon_umull (extract_high (v2i64 vec)))
9891// (extract_high (v2i64 (dup128 scalar)))))
9892//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009893static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009894 TargetLowering::DAGCombinerInfo &DCI,
9895 SelectionDAG &DAG) {
9896 if (DCI.isBeforeLegalizeOps())
9897 return SDValue();
9898
Hal Finkelcd8664c2015-12-11 23:11:52 +00009899 SDValue LHS = N->getOperand(1);
9900 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009901 assert(LHS.getValueType().is64BitVector() &&
9902 RHS.getValueType().is64BitVector() &&
9903 "unexpected shape for long operation");
9904
9905 // Either node could be a DUP, but it's not worth doing both of them (you'd
9906 // just as well use the non-high version) so look for a corresponding extract
9907 // operation on the other "wing".
Eli Friedman29c06092019-02-08 00:23:35 +00009908 if (isEssentiallyExtractHighSubvector(LHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009909 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9910 if (!RHS.getNode())
9911 return SDValue();
Eli Friedman29c06092019-02-08 00:23:35 +00009912 } else if (isEssentiallyExtractHighSubvector(RHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009913 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9914 if (!LHS.getNode())
9915 return SDValue();
9916 }
9917
Hal Finkelcd8664c2015-12-11 23:11:52 +00009918 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9919 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009920}
9921
9922static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9923 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9924 unsigned ElemBits = ElemTy.getSizeInBits();
9925
9926 int64_t ShiftAmount;
9927 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9928 APInt SplatValue, SplatUndef;
9929 unsigned SplatBitSize;
9930 bool HasAnyUndefs;
9931 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9932 HasAnyUndefs, ElemBits) ||
9933 SplatBitSize != ElemBits)
9934 return SDValue();
9935
9936 ShiftAmount = SplatValue.getSExtValue();
9937 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9938 ShiftAmount = CVN->getSExtValue();
9939 } else
9940 return SDValue();
9941
9942 unsigned Opcode;
9943 bool IsRightShift;
9944 switch (IID) {
9945 default:
9946 llvm_unreachable("Unknown shift intrinsic");
9947 case Intrinsic::aarch64_neon_sqshl:
9948 Opcode = AArch64ISD::SQSHL_I;
9949 IsRightShift = false;
9950 break;
9951 case Intrinsic::aarch64_neon_uqshl:
9952 Opcode = AArch64ISD::UQSHL_I;
9953 IsRightShift = false;
9954 break;
9955 case Intrinsic::aarch64_neon_srshl:
9956 Opcode = AArch64ISD::SRSHR_I;
9957 IsRightShift = true;
9958 break;
9959 case Intrinsic::aarch64_neon_urshl:
9960 Opcode = AArch64ISD::URSHR_I;
9961 IsRightShift = true;
9962 break;
9963 case Intrinsic::aarch64_neon_sqshlu:
9964 Opcode = AArch64ISD::SQSHLU_I;
9965 IsRightShift = false;
9966 break;
9967 }
9968
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009969 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9970 SDLoc dl(N);
9971 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9972 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9973 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9974 SDLoc dl(N);
9975 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9976 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9977 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009978
9979 return SDValue();
9980}
9981
9982// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9983// the intrinsics must be legal and take an i32, this means there's almost
9984// certainly going to be a zext in the DAG which we can eliminate.
9985static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9986 SDValue AndN = N->getOperand(2);
9987 if (AndN.getOpcode() != ISD::AND)
9988 return SDValue();
9989
9990 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9991 if (!CMask || CMask->getZExtValue() != Mask)
9992 return SDValue();
9993
9994 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9995 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9996}
9997
Ahmed Bougachafab58922015-03-10 20:45:38 +00009998static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9999 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010000 SDLoc dl(N);
10001 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10002 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +000010003 N->getOperand(1).getSimpleValueType(),
10004 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010005 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +000010006}
10007
Tim Northover3b0846e2014-05-24 12:50:23 +000010008static SDValue performIntrinsicCombine(SDNode *N,
10009 TargetLowering::DAGCombinerInfo &DCI,
10010 const AArch64Subtarget *Subtarget) {
10011 SelectionDAG &DAG = DCI.DAG;
10012 unsigned IID = getIntrinsicID(N);
10013 switch (IID) {
10014 default:
10015 break;
10016 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10017 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10018 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +000010019 case Intrinsic::aarch64_neon_saddv:
10020 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10021 case Intrinsic::aarch64_neon_uaddv:
10022 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10023 case Intrinsic::aarch64_neon_sminv:
10024 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10025 case Intrinsic::aarch64_neon_uminv:
10026 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10027 case Intrinsic::aarch64_neon_smaxv:
10028 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10029 case Intrinsic::aarch64_neon_umaxv:
10030 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010031 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +000010032 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010033 N->getOperand(1), N->getOperand(2));
10034 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +000010035 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010036 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +000010037 case Intrinsic::aarch64_neon_fmaxnm:
10038 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10039 N->getOperand(1), N->getOperand(2));
10040 case Intrinsic::aarch64_neon_fminnm:
10041 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10042 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010043 case Intrinsic::aarch64_neon_smull:
10044 case Intrinsic::aarch64_neon_umull:
10045 case Intrinsic::aarch64_neon_pmull:
10046 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +000010047 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010048 case Intrinsic::aarch64_neon_sqshl:
10049 case Intrinsic::aarch64_neon_uqshl:
10050 case Intrinsic::aarch64_neon_sqshlu:
10051 case Intrinsic::aarch64_neon_srshl:
10052 case Intrinsic::aarch64_neon_urshl:
10053 return tryCombineShiftImm(IID, N, DAG);
10054 case Intrinsic::aarch64_crc32b:
10055 case Intrinsic::aarch64_crc32cb:
10056 return tryCombineCRC32(0xff, N, DAG);
10057 case Intrinsic::aarch64_crc32h:
10058 case Intrinsic::aarch64_crc32ch:
10059 return tryCombineCRC32(0xffff, N, DAG);
10060 }
10061 return SDValue();
10062}
10063
10064static SDValue performExtendCombine(SDNode *N,
10065 TargetLowering::DAGCombinerInfo &DCI,
10066 SelectionDAG &DAG) {
10067 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10068 // we can convert that DUP into another extract_high (of a bigger DUP), which
10069 // helps the backend to decide that an sabdl2 would be useful, saving a real
10070 // extract_high operation.
10071 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +000010072 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010073 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010074 unsigned IID = getIntrinsicID(ABDNode);
10075 if (IID == Intrinsic::aarch64_neon_sabd ||
10076 IID == Intrinsic::aarch64_neon_uabd) {
10077 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10078 if (!NewABD.getNode())
10079 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010080
Hal Finkelcd8664c2015-12-11 23:11:52 +000010081 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10082 NewABD);
10083 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010084 }
10085
10086 // This is effectively a custom type legalization for AArch64.
10087 //
10088 // Type legalization will split an extend of a small, legal, type to a larger
10089 // illegal type by first splitting the destination type, often creating
10090 // illegal source types, which then get legalized in isel-confusing ways,
10091 // leading to really terrible codegen. E.g.,
10092 // %result = v8i32 sext v8i8 %value
10093 // becomes
10094 // %losrc = extract_subreg %value, ...
10095 // %hisrc = extract_subreg %value, ...
10096 // %lo = v4i32 sext v4i8 %losrc
10097 // %hi = v4i32 sext v4i8 %hisrc
10098 // Things go rapidly downhill from there.
10099 //
10100 // For AArch64, the [sz]ext vector instructions can only go up one element
10101 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10102 // take two instructions.
10103 //
10104 // This implies that the most efficient way to do the extend from v8i8
10105 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10106 // the normal splitting to happen for the v8i16->v8i32.
10107
10108 // This is pre-legalization to catch some cases where the default
10109 // type legalization will create ill-tempered code.
10110 if (!DCI.isBeforeLegalizeOps())
10111 return SDValue();
10112
10113 // We're only interested in cleaning things up for non-legal vector types
10114 // here. If both the source and destination are legal, things will just
10115 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010116 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010117 EVT ResVT = N->getValueType(0);
10118 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10119 return SDValue();
10120 // If the vector type isn't a simple VT, it's beyond the scope of what
10121 // we're worried about here. Let legalization do its thing and hope for
10122 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010123 SDValue Src = N->getOperand(0);
10124 EVT SrcVT = Src->getValueType(0);
10125 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010126 return SDValue();
10127
Tim Northover3b0846e2014-05-24 12:50:23 +000010128 // If the source VT is a 64-bit vector, we can play games and get the
10129 // better results we want.
10130 if (SrcVT.getSizeInBits() != 64)
10131 return SDValue();
10132
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010133 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010134 unsigned ElementCount = SrcVT.getVectorNumElements();
10135 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10136 SDLoc DL(N);
10137 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10138
10139 // Now split the rest of the operation into two halves, each with a 64
10140 // bit source.
10141 EVT LoVT, HiVT;
10142 SDValue Lo, Hi;
10143 unsigned NumElements = ResVT.getVectorNumElements();
10144 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10145 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10146 ResVT.getVectorElementType(), NumElements / 2);
10147
10148 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10149 LoVT.getVectorNumElements());
10150 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010151 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010152 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010153 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010154 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10155 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10156
10157 // Now combine the parts back together so we still have a single result
10158 // like the combiner expects.
10159 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10160}
10161
Geoff Berry8301c642016-11-16 19:35:19 +000010162static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10163 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010164 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010165 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010166 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010167
10168 // Create scalar stores. This is at least as good as the code sequence for a
10169 // split unaligned store which is a dup.s, ext.b, and two stores.
10170 // Most of the time the three stores should be replaced by store pair
10171 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010172 SDLoc DL(&St);
10173 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010174 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010175
John Brawn3a9c8422017-02-06 18:07:20 +000010176 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010177 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010178 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010179 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010180
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010181 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010182 if (BasePtr->getOpcode() == ISD::ADD &&
10183 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10184 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10185 BasePtr = BasePtr->getOperand(0);
10186 }
10187
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010188 unsigned Offset = EltOffset;
10189 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010190 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010191 SDValue OffsetPtr =
10192 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10193 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010194 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010195 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010196 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010197 Offset += EltOffset;
10198 }
10199 return NewST1;
10200}
10201
Geoff Berry526c5052016-11-14 19:39:04 +000010202/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10203/// load store optimizer pass will merge them to store pair stores. This should
10204/// be better than a movi to create the vector zero followed by a vector store
10205/// if the zero constant is not re-used, since one instructions and one register
10206/// live range will be removed.
10207///
10208/// For example, the final generated code should be:
10209///
10210/// stp xzr, xzr, [x0]
10211///
10212/// instead of:
10213///
10214/// movi v0.2d, #0
10215/// str q0, [x0]
10216///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010217static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10218 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010219 EVT VT = StVal.getValueType();
10220
Geoff Berry8301c642016-11-16 19:35:19 +000010221 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10222 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010223 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010224 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10225 VT.getVectorElementType().getSizeInBits() == 64) ||
10226 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10227 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010228 return SDValue();
10229
10230 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10231 return SDValue();
10232
10233 // If the zero constant has more than one use then the vector store could be
10234 // better since the constant mov will be amortized and stp q instructions
10235 // should be able to be formed.
10236 if (!StVal.hasOneUse())
10237 return SDValue();
10238
Tim Northover964eea72019-01-08 13:30:27 +000010239 // If the store is truncating then it's going down to i16 or smaller, which
10240 // means it can be implemented in a single store anyway.
10241 if (St.isTruncatingStore())
10242 return SDValue();
10243
Geoff Berry526c5052016-11-14 19:39:04 +000010244 // If the immediate offset of the address operand is too large for the stp
10245 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010246 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10247 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010248 if (Offset < -512 || Offset > 504)
10249 return SDValue();
10250 }
10251
10252 for (int I = 0; I < NumVecElts; ++I) {
10253 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010254 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010255 return SDValue();
10256 }
Geoff Berry8301c642016-11-16 19:35:19 +000010257
Geoff Berrybb23df92017-09-21 21:10:06 +000010258 // Use a CopyFromReg WZR/XZR here to prevent
10259 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10260 SDLoc DL(&St);
10261 unsigned ZeroReg;
10262 EVT ZeroVT;
10263 if (VT.getVectorElementType().getSizeInBits() == 32) {
10264 ZeroReg = AArch64::WZR;
10265 ZeroVT = MVT::i32;
10266 } else {
10267 ZeroReg = AArch64::XZR;
10268 ZeroVT = MVT::i64;
10269 }
10270 SDValue SplatVal =
10271 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010272 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010273}
10274
Tim Northover3b0846e2014-05-24 12:50:23 +000010275/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10276/// value. The load store optimizer pass will merge them to store pair stores.
10277/// This has better performance than a splat of the scalar followed by a split
10278/// vector store. Even if the stores are not merged it is four stores vs a dup,
10279/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010280static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10281 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010282 EVT VT = StVal.getValueType();
10283
10284 // Don't replace floating point stores, they possibly won't be transformed to
10285 // stp because of the store pair suppress pass.
10286 if (VT.isFloatingPoint())
10287 return SDValue();
10288
Tim Northover3b0846e2014-05-24 12:50:23 +000010289 // We can express a splat as store pair(s) for 2 or 4 elements.
10290 unsigned NumVecElts = VT.getVectorNumElements();
10291 if (NumVecElts != 4 && NumVecElts != 2)
10292 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010293
Tim Northover964eea72019-01-08 13:30:27 +000010294 // If the store is truncating then it's going down to i16 or smaller, which
10295 // means it can be implemented in a single store anyway.
10296 if (St.isTruncatingStore())
10297 return SDValue();
10298
Tim Northover3b0846e2014-05-24 12:50:23 +000010299 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010300 // Make sure that each of the relevant vector element locations are inserted
10301 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10302 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10303 SDValue SplatVal;
10304 for (unsigned I = 0; I < NumVecElts; ++I) {
10305 // Check for insert vector elements.
10306 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010307 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010308
10309 // Check that same value is inserted at each vector element.
10310 if (I == 0)
10311 SplatVal = StVal.getOperand(1);
10312 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010313 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010314
10315 // Check insert element index.
10316 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10317 if (!CIndex)
10318 return SDValue();
10319 uint64_t IndexVal = CIndex->getZExtValue();
10320 if (IndexVal >= NumVecElts)
10321 return SDValue();
10322 IndexNotInserted.reset(IndexVal);
10323
10324 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010325 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010326 // Check that all vector element locations were inserted to.
10327 if (IndexNotInserted.any())
10328 return SDValue();
10329
Geoff Berry8301c642016-11-16 19:35:19 +000010330 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010331}
10332
Geoff Berry8301c642016-11-16 19:35:19 +000010333static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10334 SelectionDAG &DAG,
10335 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010336
10337 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010338 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010339 return SDValue();
10340
Geoff Berry526c5052016-11-14 19:39:04 +000010341 SDValue StVal = S->getValue();
10342 EVT VT = StVal.getValueType();
10343 if (!VT.isVector())
10344 return SDValue();
10345
10346 // If we get a splat of zeros, convert this vector store to a store of
10347 // scalars. They will be merged into store pairs of xzr thereby removing one
10348 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010349 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010350 return ReplacedZeroSplat;
10351
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010352 // FIXME: The logic for deciding if an unaligned store should be split should
10353 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10354 // a call to that function here.
10355
Matthias Braun651cff42016-06-02 18:03:53 +000010356 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010357 return SDValue();
10358
Sanjay Patel924879a2015-08-04 15:49:57 +000010359 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +000010360 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010361 return SDValue();
10362
Tim Northover3b0846e2014-05-24 12:50:23 +000010363 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10364 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010365 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010366 return SDValue();
10367
10368 // Split unaligned 16B stores. They are terrible for performance.
10369 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10370 // extensions can use this to mark that it does not want splitting to happen
10371 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10372 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10373 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10374 S->getAlignment() <= 2)
10375 return SDValue();
10376
10377 // If we get a splat of a scalar convert this vector store to a store of
10378 // scalars. They will be merged into store pairs thereby removing two
10379 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010380 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010381 return ReplacedSplat;
10382
10383 SDLoc DL(S);
10384 unsigned NumElts = VT.getVectorNumElements() / 2;
10385 // Split VT into two.
10386 EVT HalfVT =
10387 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10388 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010389 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010390 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010391 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010392 SDValue BasePtr = S->getBasePtr();
10393 SDValue NewST1 =
10394 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010395 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010396 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010397 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010398 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010399 S->getPointerInfo(), S->getAlignment(),
10400 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010401}
10402
10403/// Target-specific DAG combine function for post-increment LD1 (lane) and
10404/// post-increment LD1R.
10405static SDValue performPostLD1Combine(SDNode *N,
10406 TargetLowering::DAGCombinerInfo &DCI,
10407 bool IsLaneOp) {
10408 if (DCI.isBeforeLegalizeOps())
10409 return SDValue();
10410
10411 SelectionDAG &DAG = DCI.DAG;
10412 EVT VT = N->getValueType(0);
10413
10414 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10415 SDNode *LD = N->getOperand(LoadIdx).getNode();
10416 // If it is not LOAD, can not do such combine.
10417 if (LD->getOpcode() != ISD::LOAD)
10418 return SDValue();
10419
Geoff Berry60460262018-05-11 16:25:06 +000010420 // The vector lane must be a constant in the LD1LANE opcode.
10421 SDValue Lane;
10422 if (IsLaneOp) {
10423 Lane = N->getOperand(2);
10424 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10425 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10426 return SDValue();
10427 }
10428
Tim Northover3b0846e2014-05-24 12:50:23 +000010429 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10430 EVT MemVT = LoadSDN->getMemoryVT();
10431 // Check if memory operand is the same type as the vector element.
10432 if (MemVT != VT.getVectorElementType())
10433 return SDValue();
10434
10435 // Check if there are other uses. If so, do not combine as it will introduce
10436 // an extra load.
10437 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10438 ++UI) {
10439 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10440 continue;
10441 if (*UI != N)
10442 return SDValue();
10443 }
10444
10445 SDValue Addr = LD->getOperand(1);
10446 SDValue Vector = N->getOperand(0);
10447 // Search for a use of the address operand that is an increment.
10448 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10449 Addr.getNode()->use_end(); UI != UE; ++UI) {
10450 SDNode *User = *UI;
10451 if (User->getOpcode() != ISD::ADD
10452 || UI.getUse().getResNo() != Addr.getResNo())
10453 continue;
10454
Tim Northover3b0846e2014-05-24 12:50:23 +000010455 // If the increment is a constant, it must match the memory ref size.
10456 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10457 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10458 uint32_t IncVal = CInc->getZExtValue();
10459 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10460 if (IncVal != NumBytes)
10461 continue;
10462 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10463 }
10464
Nirav Davee40e2bb2018-09-25 15:30:22 +000010465 // To avoid cycle construction make sure that neither the load nor the add
10466 // are predecessors to each other or the Vector.
10467 SmallPtrSet<const SDNode *, 32> Visited;
10468 SmallVector<const SDNode *, 16> Worklist;
10469 Visited.insert(N);
10470 Worklist.push_back(User);
10471 Worklist.push_back(LD);
10472 Worklist.push_back(Vector.getNode());
10473 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10474 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010475 continue;
10476
Tim Northover3b0846e2014-05-24 12:50:23 +000010477 SmallVector<SDValue, 8> Ops;
10478 Ops.push_back(LD->getOperand(0)); // Chain
10479 if (IsLaneOp) {
10480 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010481 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010482 }
10483 Ops.push_back(Addr);
10484 Ops.push_back(Inc);
10485
10486 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010487 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010488 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10489 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10490 MemVT,
10491 LoadSDN->getMemOperand());
10492
10493 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010494 SDValue NewResults[] = {
10495 SDValue(LD, 0), // The result of load
10496 SDValue(UpdN.getNode(), 2) // Chain
10497 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010498 DCI.CombineTo(LD, NewResults);
10499 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10500 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10501
10502 break;
10503 }
10504 return SDValue();
10505}
10506
Joel Jones7466ccf2017-07-10 22:11:50 +000010507/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010508/// address translation.
10509static bool performTBISimplification(SDValue Addr,
10510 TargetLowering::DAGCombinerInfo &DCI,
10511 SelectionDAG &DAG) {
10512 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010513 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010514 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10515 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010516 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010517 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010518 DCI.CommitTargetLoweringOpt(TLO);
10519 return true;
10520 }
10521 return false;
10522}
10523
10524static SDValue performSTORECombine(SDNode *N,
10525 TargetLowering::DAGCombinerInfo &DCI,
10526 SelectionDAG &DAG,
10527 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010528 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010529 return Split;
10530
10531 if (Subtarget->supportsAddressTopByteIgnored() &&
10532 performTBISimplification(N->getOperand(2), DCI, DAG))
10533 return SDValue(N, 0);
10534
10535 return SDValue();
10536}
10537
Chad Rosier6c36eff2015-09-03 18:13:57 +000010538
Tim Northover3b0846e2014-05-24 12:50:23 +000010539/// Target-specific DAG combine function for NEON load/store intrinsics
10540/// to merge base address updates.
10541static SDValue performNEONPostLDSTCombine(SDNode *N,
10542 TargetLowering::DAGCombinerInfo &DCI,
10543 SelectionDAG &DAG) {
10544 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10545 return SDValue();
10546
10547 unsigned AddrOpIdx = N->getNumOperands() - 1;
10548 SDValue Addr = N->getOperand(AddrOpIdx);
10549
10550 // Search for a use of the address operand that is an increment.
10551 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10552 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10553 SDNode *User = *UI;
10554 if (User->getOpcode() != ISD::ADD ||
10555 UI.getUse().getResNo() != Addr.getResNo())
10556 continue;
10557
10558 // Check that the add is independent of the load/store. Otherwise, folding
10559 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010560 SmallPtrSet<const SDNode *, 32> Visited;
10561 SmallVector<const SDNode *, 16> Worklist;
10562 Visited.insert(Addr.getNode());
10563 Worklist.push_back(N);
10564 Worklist.push_back(User);
10565 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10566 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010567 continue;
10568
10569 // Find the new opcode for the updating load/store.
10570 bool IsStore = false;
10571 bool IsLaneOp = false;
10572 bool IsDupOp = false;
10573 unsigned NewOpc = 0;
10574 unsigned NumVecs = 0;
10575 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10576 switch (IntNo) {
10577 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10578 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10579 NumVecs = 2; break;
10580 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10581 NumVecs = 3; break;
10582 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10583 NumVecs = 4; break;
10584 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10585 NumVecs = 2; IsStore = true; break;
10586 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10587 NumVecs = 3; IsStore = true; break;
10588 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10589 NumVecs = 4; IsStore = true; break;
10590 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10591 NumVecs = 2; break;
10592 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10593 NumVecs = 3; break;
10594 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10595 NumVecs = 4; break;
10596 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10597 NumVecs = 2; IsStore = true; break;
10598 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10599 NumVecs = 3; IsStore = true; break;
10600 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10601 NumVecs = 4; IsStore = true; break;
10602 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10603 NumVecs = 2; IsDupOp = true; break;
10604 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10605 NumVecs = 3; IsDupOp = true; break;
10606 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10607 NumVecs = 4; IsDupOp = true; break;
10608 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10609 NumVecs = 2; IsLaneOp = true; break;
10610 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10611 NumVecs = 3; IsLaneOp = true; break;
10612 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10613 NumVecs = 4; IsLaneOp = true; break;
10614 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10615 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10616 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10617 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10618 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10619 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10620 }
10621
10622 EVT VecTy;
10623 if (IsStore)
10624 VecTy = N->getOperand(2).getValueType();
10625 else
10626 VecTy = N->getValueType(0);
10627
10628 // If the increment is a constant, it must match the memory ref size.
10629 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10630 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10631 uint32_t IncVal = CInc->getZExtValue();
10632 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10633 if (IsLaneOp || IsDupOp)
10634 NumBytes /= VecTy.getVectorNumElements();
10635 if (IncVal != NumBytes)
10636 continue;
10637 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10638 }
10639 SmallVector<SDValue, 8> Ops;
10640 Ops.push_back(N->getOperand(0)); // Incoming chain
10641 // Load lane and store have vector list as input.
10642 if (IsLaneOp || IsStore)
10643 for (unsigned i = 2; i < AddrOpIdx; ++i)
10644 Ops.push_back(N->getOperand(i));
10645 Ops.push_back(Addr); // Base register
10646 Ops.push_back(Inc);
10647
10648 // Return Types.
10649 EVT Tys[6];
10650 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10651 unsigned n;
10652 for (n = 0; n < NumResultVecs; ++n)
10653 Tys[n] = VecTy;
10654 Tys[n++] = MVT::i64; // Type of write back register
10655 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010656 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010657
10658 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10659 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10660 MemInt->getMemoryVT(),
10661 MemInt->getMemOperand());
10662
10663 // Update the uses.
10664 std::vector<SDValue> NewResults;
10665 for (unsigned i = 0; i < NumResultVecs; ++i) {
10666 NewResults.push_back(SDValue(UpdN.getNode(), i));
10667 }
10668 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10669 DCI.CombineTo(N, NewResults);
10670 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10671
10672 break;
10673 }
10674 return SDValue();
10675}
10676
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010677// Checks to see if the value is the prescribed width and returns information
10678// about its extension mode.
10679static
10680bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10681 ExtType = ISD::NON_EXTLOAD;
10682 switch(V.getNode()->getOpcode()) {
10683 default:
10684 return false;
10685 case ISD::LOAD: {
10686 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10687 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10688 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10689 ExtType = LoadNode->getExtensionType();
10690 return true;
10691 }
10692 return false;
10693 }
10694 case ISD::AssertSext: {
10695 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10696 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10697 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10698 ExtType = ISD::SEXTLOAD;
10699 return true;
10700 }
10701 return false;
10702 }
10703 case ISD::AssertZext: {
10704 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10705 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10706 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10707 ExtType = ISD::ZEXTLOAD;
10708 return true;
10709 }
10710 return false;
10711 }
10712 case ISD::Constant:
10713 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010714 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10715 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010716 }
10717 }
10718
10719 return true;
10720}
10721
10722// This function does a whole lot of voodoo to determine if the tests are
10723// equivalent without and with a mask. Essentially what happens is that given a
10724// DAG resembling:
10725//
10726// +-------------+ +-------------+ +-------------+ +-------------+
10727// | Input | | AddConstant | | CompConstant| | CC |
10728// +-------------+ +-------------+ +-------------+ +-------------+
10729// | | | |
10730// V V | +----------+
10731// +-------------+ +----+ | |
10732// | ADD | |0xff| | |
10733// +-------------+ +----+ | |
10734// | | | |
10735// V V | |
10736// +-------------+ | |
10737// | AND | | |
10738// +-------------+ | |
10739// | | |
10740// +-----+ | |
10741// | | |
10742// V V V
10743// +-------------+
10744// | CMP |
10745// +-------------+
10746//
10747// The AND node may be safely removed for some combinations of inputs. In
10748// particular we need to take into account the extension type of the Input,
10749// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10750// width of the input (this can work for any width inputs, the above graph is
10751// specific to 8 bits.
10752//
10753// The specific equations were worked out by generating output tables for each
10754// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10755// problem was simplified by working with 4 bit inputs, which means we only
10756// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10757// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10758// patterns present in both extensions (0,7). For every distinct set of
10759// AddConstant and CompConstants bit patterns we can consider the masked and
10760// unmasked versions to be equivalent if the result of this function is true for
10761// all 16 distinct bit patterns of for the current extension type of Input (w0).
10762//
10763// sub w8, w0, w1
10764// and w10, w8, #0x0f
10765// cmp w8, w2
10766// cset w9, AArch64CC
10767// cmp w10, w2
10768// cset w11, AArch64CC
10769// cmp w9, w11
10770// cset w0, eq
10771// ret
10772//
10773// Since the above function shows when the outputs are equivalent it defines
10774// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10775// would be expensive to run during compiles. The equations below were written
10776// in a test harness that confirmed they gave equivalent outputs to the above
10777// for all inputs function, so they can be used determine if the removal is
10778// legal instead.
10779//
10780// isEquivalentMaskless() is the code for testing if the AND can be removed
10781// factored out of the DAG recognition as the DAG can take several forms.
10782
David Majnemere61e4bf2016-06-21 05:10:24 +000010783static bool isEquivalentMaskless(unsigned CC, unsigned width,
10784 ISD::LoadExtType ExtType, int AddConstant,
10785 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010786 // By being careful about our equations and only writing the in term
10787 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10788 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010789 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010790
10791 // For the purposes of these comparisons sign extending the type is
10792 // equivalent to zero extending the add and displacing it by half the integer
10793 // width. Provided we are careful and make sure our equations are valid over
10794 // the whole range we can just adjust the input and avoid writing equations
10795 // for sign extended inputs.
10796 if (ExtType == ISD::SEXTLOAD)
10797 AddConstant -= (1 << (width-1));
10798
10799 switch(CC) {
10800 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010801 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010802 if ((AddConstant == 0) ||
10803 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10804 (AddConstant >= 0 && CompConstant < 0) ||
10805 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10806 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010807 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010808 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010809 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010810 if ((AddConstant == 0) ||
10811 (AddConstant >= 0 && CompConstant <= 0) ||
10812 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10813 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010814 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010815 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010816 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010817 if ((AddConstant >= 0 && CompConstant < 0) ||
10818 (AddConstant <= 0 && CompConstant >= -1 &&
10819 CompConstant < AddConstant + MaxUInt))
10820 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010821 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010822 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010823 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010824 if ((AddConstant == 0) ||
10825 (AddConstant > 0 && CompConstant <= 0) ||
10826 (AddConstant < 0 && CompConstant <= AddConstant))
10827 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010828 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010829 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010830 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010831 if ((AddConstant >= 0 && CompConstant <= 0) ||
10832 (AddConstant <= 0 && CompConstant >= 0 &&
10833 CompConstant <= AddConstant + MaxUInt))
10834 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010835 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010836 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010837 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010838 if ((AddConstant > 0 && CompConstant < 0) ||
10839 (AddConstant < 0 && CompConstant >= 0 &&
10840 CompConstant < AddConstant + MaxUInt) ||
10841 (AddConstant >= 0 && CompConstant >= 0 &&
10842 CompConstant >= AddConstant) ||
10843 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010844 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010845 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010846 case AArch64CC::VS:
10847 case AArch64CC::VC:
10848 case AArch64CC::AL:
10849 case AArch64CC::NV:
10850 return true;
10851 case AArch64CC::Invalid:
10852 break;
10853 }
10854
10855 return false;
10856}
10857
10858static
10859SDValue performCONDCombine(SDNode *N,
10860 TargetLowering::DAGCombinerInfo &DCI,
10861 SelectionDAG &DAG, unsigned CCIndex,
10862 unsigned CmpIndex) {
10863 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10864 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10865 unsigned CondOpcode = SubsNode->getOpcode();
10866
10867 if (CondOpcode != AArch64ISD::SUBS)
10868 return SDValue();
10869
10870 // There is a SUBS feeding this condition. Is it fed by a mask we can
10871 // use?
10872
10873 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10874 unsigned MaskBits = 0;
10875
10876 if (AndNode->getOpcode() != ISD::AND)
10877 return SDValue();
10878
10879 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10880 uint32_t CNV = CN->getZExtValue();
10881 if (CNV == 255)
10882 MaskBits = 8;
10883 else if (CNV == 65535)
10884 MaskBits = 16;
10885 }
10886
10887 if (!MaskBits)
10888 return SDValue();
10889
10890 SDValue AddValue = AndNode->getOperand(0);
10891
10892 if (AddValue.getOpcode() != ISD::ADD)
10893 return SDValue();
10894
10895 // The basic dag structure is correct, grab the inputs and validate them.
10896
10897 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10898 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10899 SDValue SubsInputValue = SubsNode->getOperand(1);
10900
10901 // The mask is present and the provenance of all the values is a smaller type,
10902 // lets see if the mask is superfluous.
10903
10904 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10905 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10906 return SDValue();
10907
10908 ISD::LoadExtType ExtType;
10909
10910 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10911 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10912 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10913 return SDValue();
10914
10915 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10916 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10917 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10918 return SDValue();
10919
10920 // The AND is not necessary, remove it.
10921
10922 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10923 SubsNode->getValueType(1));
10924 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10925
10926 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10927 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10928
10929 return SDValue(N, 0);
10930}
10931
Tim Northover3b0846e2014-05-24 12:50:23 +000010932// Optimize compare with zero and branch.
10933static SDValue performBRCONDCombine(SDNode *N,
10934 TargetLowering::DAGCombinerInfo &DCI,
10935 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000010936 MachineFunction &MF = DAG.getMachineFunction();
10937 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
10938 // will not be produced, as they are conditional branch instructions that do
10939 // not set flags.
10940 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
10941 return SDValue();
10942
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010943 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010944 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010945 SDValue Chain = N->getOperand(0);
10946 SDValue Dest = N->getOperand(1);
10947 SDValue CCVal = N->getOperand(2);
10948 SDValue Cmp = N->getOperand(3);
10949
10950 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10951 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10952 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10953 return SDValue();
10954
10955 unsigned CmpOpc = Cmp.getOpcode();
10956 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10957 return SDValue();
10958
10959 // Only attempt folding if there is only one use of the flag and no use of the
10960 // value.
10961 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10962 return SDValue();
10963
10964 SDValue LHS = Cmp.getOperand(0);
10965 SDValue RHS = Cmp.getOperand(1);
10966
10967 assert(LHS.getValueType() == RHS.getValueType() &&
10968 "Expected the value type to be the same for both operands!");
10969 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10970 return SDValue();
10971
Artyom Skrobov314ee042015-11-25 19:41:11 +000010972 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010973 std::swap(LHS, RHS);
10974
Artyom Skrobov314ee042015-11-25 19:41:11 +000010975 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010976 return SDValue();
10977
10978 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10979 LHS.getOpcode() == ISD::SRL)
10980 return SDValue();
10981
10982 // Fold the compare into the branch instruction.
10983 SDValue BR;
10984 if (CC == AArch64CC::EQ)
10985 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10986 else
10987 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10988
10989 // Do not add new nodes to DAG combiner worklist.
10990 DCI.CombineTo(N, BR, false);
10991
10992 return SDValue();
10993}
10994
Geoff Berry9e934b02016-01-04 18:55:47 +000010995// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10996// as well as whether the test should be inverted. This code is required to
10997// catch these cases (as opposed to standard dag combines) because
10998// AArch64ISD::TBZ is matched during legalization.
10999static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11000 SelectionDAG &DAG) {
11001
11002 if (!Op->hasOneUse())
11003 return Op;
11004
11005 // We don't handle undef/constant-fold cases below, as they should have
11006 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11007 // etc.)
11008
11009 // (tbz (trunc x), b) -> (tbz x, b)
11010 // This case is just here to enable more of the below cases to be caught.
11011 if (Op->getOpcode() == ISD::TRUNCATE &&
11012 Bit < Op->getValueType(0).getSizeInBits()) {
11013 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11014 }
11015
11016 if (Op->getNumOperands() != 2)
11017 return Op;
11018
11019 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11020 if (!C)
11021 return Op;
11022
11023 switch (Op->getOpcode()) {
11024 default:
11025 return Op;
11026
11027 // (tbz (and x, m), b) -> (tbz x, b)
11028 case ISD::AND:
11029 if ((C->getZExtValue() >> Bit) & 1)
11030 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11031 return Op;
11032
11033 // (tbz (shl x, c), b) -> (tbz x, b-c)
11034 case ISD::SHL:
11035 if (C->getZExtValue() <= Bit &&
11036 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11037 Bit = Bit - C->getZExtValue();
11038 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11039 }
11040 return Op;
11041
11042 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11043 case ISD::SRA:
11044 Bit = Bit + C->getZExtValue();
11045 if (Bit >= Op->getValueType(0).getSizeInBits())
11046 Bit = Op->getValueType(0).getSizeInBits() - 1;
11047 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11048
11049 // (tbz (srl x, c), b) -> (tbz x, b+c)
11050 case ISD::SRL:
11051 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11052 Bit = Bit + C->getZExtValue();
11053 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11054 }
11055 return Op;
11056
11057 // (tbz (xor x, -1), b) -> (tbnz x, b)
11058 case ISD::XOR:
11059 if ((C->getZExtValue() >> Bit) & 1)
11060 Invert = !Invert;
11061 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11062 }
11063}
11064
11065// Optimize test single bit zero/non-zero and branch.
11066static SDValue performTBZCombine(SDNode *N,
11067 TargetLowering::DAGCombinerInfo &DCI,
11068 SelectionDAG &DAG) {
11069 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11070 bool Invert = false;
11071 SDValue TestSrc = N->getOperand(1);
11072 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11073
11074 if (TestSrc == NewTestSrc)
11075 return SDValue();
11076
11077 unsigned NewOpc = N->getOpcode();
11078 if (Invert) {
11079 if (NewOpc == AArch64ISD::TBZ)
11080 NewOpc = AArch64ISD::TBNZ;
11081 else {
11082 assert(NewOpc == AArch64ISD::TBNZ);
11083 NewOpc = AArch64ISD::TBZ;
11084 }
11085 }
11086
11087 SDLoc DL(N);
11088 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11089 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11090}
11091
Tim Northover3b0846e2014-05-24 12:50:23 +000011092// vselect (v1i1 setcc) ->
11093// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11094// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11095// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11096// such VSELECT.
11097static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11098 SDValue N0 = N->getOperand(0);
11099 EVT CCVT = N0.getValueType();
11100
11101 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11102 CCVT.getVectorElementType() != MVT::i1)
11103 return SDValue();
11104
11105 EVT ResVT = N->getValueType(0);
11106 EVT CmpVT = N0.getOperand(0).getValueType();
11107 // Only combine when the result type is of the same size as the compared
11108 // operands.
11109 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11110 return SDValue();
11111
11112 SDValue IfTrue = N->getOperand(1);
11113 SDValue IfFalse = N->getOperand(2);
11114 SDValue SetCC =
11115 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11116 N0.getOperand(0), N0.getOperand(1),
11117 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11118 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11119 IfTrue, IfFalse);
11120}
11121
11122/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11123/// the compare-mask instructions rather than going via NZCV, even if LHS and
11124/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11125/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011126static SDValue performSelectCombine(SDNode *N,
11127 TargetLowering::DAGCombinerInfo &DCI) {
11128 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011129 SDValue N0 = N->getOperand(0);
11130 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011131
Ahmed Bougachac004c602015-04-27 21:43:12 +000011132 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011133 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011134
Ahmed Bougachac004c602015-04-27 21:43:12 +000011135 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11136 // scalar SetCCResultType. We also don't expect vectors, because we assume
11137 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11138 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11139 "Scalar-SETCC feeding SELECT has unexpected result type!");
11140
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011141 // If NumMaskElts == 0, the comparison is larger than select result. The
11142 // largest real NEON comparison is 64-bits per lane, which means the result is
11143 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011144 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011145
11146 // Don't try to do this optimization when the setcc itself has i1 operands.
11147 // There are no legal vectors of i1, so this would be pointless.
11148 if (SrcVT == MVT::i1)
11149 return SDValue();
11150
Tim Northover3c0915e2014-08-29 15:34:58 +000011151 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011152 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011153 return SDValue();
11154
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011155 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011156 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11157
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011158 // Also bail out if the vector CCVT isn't the same size as ResVT.
11159 // This can happen if the SETCC operand size doesn't divide the ResVT size
11160 // (e.g., f64 vs v3f32).
11161 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11162 return SDValue();
11163
Ahmed Bougachac004c602015-04-27 21:43:12 +000011164 // Make sure we didn't create illegal types, if we're not supposed to.
11165 assert(DCI.isBeforeLegalize() ||
11166 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11167
Tim Northover3b0846e2014-05-24 12:50:23 +000011168 // First perform a vector comparison, where lane 0 is the one we're interested
11169 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011170 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011171 SDValue LHS =
11172 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11173 SDValue RHS =
11174 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11175 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11176
11177 // Now duplicate the comparison mask we want across all other lanes.
11178 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011179 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011180 Mask = DAG.getNode(ISD::BITCAST, DL,
11181 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011182
11183 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11184}
11185
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011186/// Get rid of unnecessary NVCASTs (that don't change the type).
11187static SDValue performNVCASTCombine(SDNode *N) {
11188 if (N->getValueType(0) == N->getOperand(0).getValueType())
11189 return N->getOperand(0);
11190
11191 return SDValue();
11192}
11193
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011194// If all users of the globaladdr are of the form (globaladdr + constant), find
11195// the smallest constant, fold it into the globaladdr's offset and rewrite the
11196// globaladdr as (globaladdr + constant) - constant.
11197static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11198 const AArch64Subtarget *Subtarget,
11199 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011200 auto *GN = cast<GlobalAddressSDNode>(N);
11201 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11202 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011203 return SDValue();
11204
11205 uint64_t MinOffset = -1ull;
11206 for (SDNode *N : GN->uses()) {
11207 if (N->getOpcode() != ISD::ADD)
11208 return SDValue();
11209 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11210 if (!C)
11211 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11212 if (!C)
11213 return SDValue();
11214 MinOffset = std::min(MinOffset, C->getZExtValue());
11215 }
11216 uint64_t Offset = MinOffset + GN->getOffset();
11217
11218 // Require that the new offset is larger than the existing one. Otherwise, we
11219 // can end up oscillating between two possible DAGs, for example,
11220 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11221 if (Offset <= uint64_t(GN->getOffset()))
11222 return SDValue();
11223
11224 // Check whether folding this offset is legal. It must not go out of bounds of
11225 // the referenced object to avoid violating the code model, and must be
11226 // smaller than 2^21 because this is the largest offset expressible in all
11227 // object formats.
11228 //
11229 // This check also prevents us from folding negative offsets, which will end
11230 // up being treated in the same way as large positive ones. They could also
11231 // cause code model violations, and aren't really common enough to matter.
11232 if (Offset >= (1 << 21))
11233 return SDValue();
11234
11235 const GlobalValue *GV = GN->getGlobal();
11236 Type *T = GV->getValueType();
11237 if (!T->isSized() ||
11238 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11239 return SDValue();
11240
11241 SDLoc DL(GN);
11242 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11243 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11244 DAG.getConstant(MinOffset, DL, MVT::i64));
11245}
11246
Tim Northover3b0846e2014-05-24 12:50:23 +000011247SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11248 DAGCombinerInfo &DCI) const {
11249 SelectionDAG &DAG = DCI.DAG;
11250 switch (N->getOpcode()) {
11251 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011252 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011253 break;
11254 case ISD::ADD:
11255 case ISD::SUB:
11256 return performAddSubLongCombine(N, DCI, DAG);
11257 case ISD::XOR:
11258 return performXorCombine(N, DAG, DCI, Subtarget);
11259 case ISD::MUL:
11260 return performMulCombine(N, DAG, DCI, Subtarget);
11261 case ISD::SINT_TO_FP:
11262 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011263 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011264 case ISD::FP_TO_SINT:
11265 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011266 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011267 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011268 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011269 case ISD::OR:
11270 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011271 case ISD::SRL:
11272 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011273 case ISD::INTRINSIC_WO_CHAIN:
11274 return performIntrinsicCombine(N, DCI, Subtarget);
11275 case ISD::ANY_EXTEND:
11276 case ISD::ZERO_EXTEND:
11277 case ISD::SIGN_EXTEND:
11278 return performExtendCombine(N, DCI, DAG);
11279 case ISD::BITCAST:
11280 return performBitcastCombine(N, DCI, DAG);
11281 case ISD::CONCAT_VECTORS:
11282 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011283 case ISD::SELECT:
11284 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011285 case ISD::VSELECT:
11286 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011287 case ISD::LOAD:
11288 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11289 return SDValue(N, 0);
11290 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011291 case ISD::STORE:
11292 return performSTORECombine(N, DCI, DAG, Subtarget);
11293 case AArch64ISD::BRCOND:
11294 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011295 case AArch64ISD::TBNZ:
11296 case AArch64ISD::TBZ:
11297 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011298 case AArch64ISD::CSEL:
11299 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011300 case AArch64ISD::DUP:
11301 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011302 case AArch64ISD::NVCAST:
11303 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011304 case ISD::INSERT_VECTOR_ELT:
11305 return performPostLD1Combine(N, DCI, true);
11306 case ISD::INTRINSIC_VOID:
11307 case ISD::INTRINSIC_W_CHAIN:
11308 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11309 case Intrinsic::aarch64_neon_ld2:
11310 case Intrinsic::aarch64_neon_ld3:
11311 case Intrinsic::aarch64_neon_ld4:
11312 case Intrinsic::aarch64_neon_ld1x2:
11313 case Intrinsic::aarch64_neon_ld1x3:
11314 case Intrinsic::aarch64_neon_ld1x4:
11315 case Intrinsic::aarch64_neon_ld2lane:
11316 case Intrinsic::aarch64_neon_ld3lane:
11317 case Intrinsic::aarch64_neon_ld4lane:
11318 case Intrinsic::aarch64_neon_ld2r:
11319 case Intrinsic::aarch64_neon_ld3r:
11320 case Intrinsic::aarch64_neon_ld4r:
11321 case Intrinsic::aarch64_neon_st2:
11322 case Intrinsic::aarch64_neon_st3:
11323 case Intrinsic::aarch64_neon_st4:
11324 case Intrinsic::aarch64_neon_st1x2:
11325 case Intrinsic::aarch64_neon_st1x3:
11326 case Intrinsic::aarch64_neon_st1x4:
11327 case Intrinsic::aarch64_neon_st2lane:
11328 case Intrinsic::aarch64_neon_st3lane:
11329 case Intrinsic::aarch64_neon_st4lane:
11330 return performNEONPostLDSTCombine(N, DCI, DAG);
11331 default:
11332 break;
11333 }
Reid Klecknereb568942018-11-01 18:02:27 +000011334 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011335 case ISD::GlobalAddress:
11336 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011337 }
11338 return SDValue();
11339}
11340
11341// Check if the return value is used as only a return value, as otherwise
11342// we can't perform a tail-call. In particular, we need to check for
11343// target ISD nodes that are returns and any other "odd" constructs
11344// that the generic analysis code won't necessarily catch.
11345bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11346 SDValue &Chain) const {
11347 if (N->getNumValues() != 1)
11348 return false;
11349 if (!N->hasNUsesOfValue(1, 0))
11350 return false;
11351
11352 SDValue TCChain = Chain;
11353 SDNode *Copy = *N->use_begin();
11354 if (Copy->getOpcode() == ISD::CopyToReg) {
11355 // If the copy has a glue operand, we conservatively assume it isn't safe to
11356 // perform a tail call.
11357 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11358 MVT::Glue)
11359 return false;
11360 TCChain = Copy->getOperand(0);
11361 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11362 return false;
11363
11364 bool HasRet = false;
11365 for (SDNode *Node : Copy->uses()) {
11366 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11367 return false;
11368 HasRet = true;
11369 }
11370
11371 if (!HasRet)
11372 return false;
11373
11374 Chain = TCChain;
11375 return true;
11376}
11377
11378// Return whether the an instruction can potentially be optimized to a tail
11379// call. This will cause the optimizers to attempt to move, or duplicate,
11380// return instructions to help enable tail call optimizations for this
11381// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011382bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011383 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011384}
11385
11386bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11387 SDValue &Offset,
11388 ISD::MemIndexedMode &AM,
11389 bool &IsInc,
11390 SelectionDAG &DAG) const {
11391 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11392 return false;
11393
11394 Base = Op->getOperand(0);
11395 // All of the indexed addressing mode instructions take a signed
11396 // 9 bit immediate offset.
11397 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011398 int64_t RHSC = RHS->getSExtValue();
11399 if (Op->getOpcode() == ISD::SUB)
11400 RHSC = -(uint64_t)RHSC;
11401 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011402 return false;
11403 IsInc = (Op->getOpcode() == ISD::ADD);
11404 Offset = Op->getOperand(1);
11405 return true;
11406 }
11407 return false;
11408}
11409
11410bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11411 SDValue &Offset,
11412 ISD::MemIndexedMode &AM,
11413 SelectionDAG &DAG) const {
11414 EVT VT;
11415 SDValue Ptr;
11416 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11417 VT = LD->getMemoryVT();
11418 Ptr = LD->getBasePtr();
11419 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11420 VT = ST->getMemoryVT();
11421 Ptr = ST->getBasePtr();
11422 } else
11423 return false;
11424
11425 bool IsInc;
11426 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11427 return false;
11428 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11429 return true;
11430}
11431
11432bool AArch64TargetLowering::getPostIndexedAddressParts(
11433 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11434 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11435 EVT VT;
11436 SDValue Ptr;
11437 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11438 VT = LD->getMemoryVT();
11439 Ptr = LD->getBasePtr();
11440 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11441 VT = ST->getMemoryVT();
11442 Ptr = ST->getBasePtr();
11443 } else
11444 return false;
11445
11446 bool IsInc;
11447 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11448 return false;
11449 // Post-indexing updates the base, so it's not a valid transform
11450 // if that's not the same as the load's pointer.
11451 if (Ptr != Base)
11452 return false;
11453 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11454 return true;
11455}
11456
Tim Northoverf8bfe212014-07-18 13:07:05 +000011457static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11458 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011459 SDLoc DL(N);
11460 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011461
11462 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11463 return;
11464
Tim Northoverf8bfe212014-07-18 13:07:05 +000011465 Op = SDValue(
11466 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11467 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011468 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011469 0);
11470 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11471 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11472}
11473
Charlie Turner434d4592015-10-16 15:38:25 +000011474static void ReplaceReductionResults(SDNode *N,
11475 SmallVectorImpl<SDValue> &Results,
11476 SelectionDAG &DAG, unsigned InterOp,
11477 unsigned AcrossOp) {
11478 EVT LoVT, HiVT;
11479 SDValue Lo, Hi;
11480 SDLoc dl(N);
11481 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11482 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11483 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11484 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11485 Results.push_back(SplitVal);
11486}
11487
Tim Northover2f32e7f2016-08-04 19:32:28 +000011488static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11489 SDLoc DL(N);
11490 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11491 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11492 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11493 DAG.getConstant(64, DL, MVT::i64)));
11494 return std::make_pair(Lo, Hi);
11495}
11496
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011497// Create an even/odd pair of X registers holding integer value V.
11498static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11499 SDLoc dl(V.getNode());
11500 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11501 SDValue VHi = DAG.getAnyExtOrTrunc(
11502 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11503 dl, MVT::i64);
11504 if (DAG.getDataLayout().isBigEndian())
11505 std::swap (VLo, VHi);
11506 SDValue RegClass =
11507 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11508 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11509 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11510 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11511 return SDValue(
11512 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11513}
11514
Tim Northovercdf15292016-04-14 17:03:29 +000011515static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011516 SmallVectorImpl<SDValue> &Results,
11517 SelectionDAG &DAG,
11518 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011519 assert(N->getValueType(0) == MVT::i128 &&
11520 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011521
11522 if (Subtarget->hasLSE()) {
11523 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11524 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11525 SDValue Ops[] = {
11526 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11527 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11528 N->getOperand(1), // Ptr
11529 N->getOperand(0), // Chain in
11530 };
11531
Chandler Carruth66654b72018-08-14 23:30:32 +000011532 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011533
11534 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011535 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011536 case AtomicOrdering::Monotonic:
11537 Opcode = AArch64::CASPX;
11538 break;
11539 case AtomicOrdering::Acquire:
11540 Opcode = AArch64::CASPAX;
11541 break;
11542 case AtomicOrdering::Release:
11543 Opcode = AArch64::CASPLX;
11544 break;
11545 case AtomicOrdering::AcquireRelease:
11546 case AtomicOrdering::SequentiallyConsistent:
11547 Opcode = AArch64::CASPALX;
11548 break;
11549 default:
11550 llvm_unreachable("Unexpected ordering!");
11551 }
11552
11553 MachineSDNode *CmpSwap = DAG.getMachineNode(
11554 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011555 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011556
11557 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11558 if (DAG.getDataLayout().isBigEndian())
11559 std::swap(SubReg1, SubReg2);
11560 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11561 SDValue(CmpSwap, 0)));
11562 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11563 SDValue(CmpSwap, 0)));
11564 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11565 return;
11566 }
11567
Tim Northover2f32e7f2016-08-04 19:32:28 +000011568 auto Desired = splitInt128(N->getOperand(2), DAG);
11569 auto New = splitInt128(N->getOperand(3), DAG);
11570 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11571 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011572 SDNode *CmpSwap = DAG.getMachineNode(
11573 AArch64::CMP_SWAP_128, SDLoc(N),
11574 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11575
Chandler Carruth66654b72018-08-14 23:30:32 +000011576 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11577 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011578
11579 Results.push_back(SDValue(CmpSwap, 0));
11580 Results.push_back(SDValue(CmpSwap, 1));
11581 Results.push_back(SDValue(CmpSwap, 3));
11582}
11583
Tim Northover3b0846e2014-05-24 12:50:23 +000011584void AArch64TargetLowering::ReplaceNodeResults(
11585 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11586 switch (N->getOpcode()) {
11587 default:
11588 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011589 case ISD::BITCAST:
11590 ReplaceBITCASTResults(N, Results, DAG);
11591 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011592 case ISD::VECREDUCE_ADD:
11593 case ISD::VECREDUCE_SMAX:
11594 case ISD::VECREDUCE_SMIN:
11595 case ISD::VECREDUCE_UMAX:
11596 case ISD::VECREDUCE_UMIN:
11597 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11598 return;
11599
Charlie Turner434d4592015-10-16 15:38:25 +000011600 case AArch64ISD::SADDV:
11601 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11602 return;
11603 case AArch64ISD::UADDV:
11604 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11605 return;
11606 case AArch64ISD::SMINV:
11607 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11608 return;
11609 case AArch64ISD::UMINV:
11610 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11611 return;
11612 case AArch64ISD::SMAXV:
11613 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11614 return;
11615 case AArch64ISD::UMAXV:
11616 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11617 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011618 case ISD::FP_TO_UINT:
11619 case ISD::FP_TO_SINT:
11620 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11621 // Let normal code take care of it by not adding anything to Results.
11622 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011623 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011624 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011625 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011626 }
11627}
11628
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011629bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011630 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11631 return TargetLowering::useLoadStackGuardNode();
11632 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011633}
11634
Sanjay Patel1dd15592015-07-28 23:05:48 +000011635unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011636 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11637 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011638 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011639}
11640
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011641TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011642AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011643 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11644 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011645 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11646 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011647 return TypeWidenVector;
11648
11649 return TargetLoweringBase::getPreferredVectorAction(VT);
11650}
11651
Robin Morisseted3d48f2014-09-03 21:29:59 +000011652// Loads and stores less than 128-bits are already atomic; ones above that
11653// are doomed anyway, so defer to the default libcall and blame the OS when
11654// things go wrong.
11655bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11656 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11657 return Size == 128;
11658}
11659
11660// Loads and stores less than 128-bits are already atomic; ones above that
11661// are doomed anyway, so defer to the default libcall and blame the OS when
11662// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011663TargetLowering::AtomicExpansionKind
11664AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011665 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011666 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011667}
11668
11669// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011670TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011671AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000011672 if (AI->isFloatingPointOperation())
11673 return AtomicExpansionKind::CmpXChg;
11674
Robin Morisseted3d48f2014-09-03 21:29:59 +000011675 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011676 if (Size > 128) return AtomicExpansionKind::None;
11677 // Nand not supported in LSE.
11678 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011679 // Leave 128 bits to LLSC.
11680 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011681}
11682
Alex Bradbury79518b02018-09-19 14:51:42 +000011683TargetLowering::AtomicExpansionKind
11684AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011685 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011686 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011687 if (Subtarget->hasLSE())
11688 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011689 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11690 // implement cmpxchg without spilling. If the address being exchanged is also
11691 // on the stack and close enough to the spill slot, this can lead to a
11692 // situation where the monitor always gets cleared and the atomic operation
11693 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011694 if (getTargetMachine().getOptLevel() == 0)
11695 return AtomicExpansionKind::None;
11696 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011697}
11698
Tim Northover3b0846e2014-05-24 12:50:23 +000011699Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11700 AtomicOrdering Ord) const {
11701 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11702 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011703 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011704
11705 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11706 // intrinsic must return {i64, i64} and we have to recombine them into a
11707 // single i128 here.
11708 if (ValTy->getPrimitiveSizeInBits() == 128) {
11709 Intrinsic::ID Int =
11710 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011711 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011712
11713 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11714 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11715
11716 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11717 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11718 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11719 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11720 return Builder.CreateOr(
11721 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11722 }
11723
11724 Type *Tys[] = { Addr->getType() };
11725 Intrinsic::ID Int =
11726 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011727 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011728
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011729 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11730
11731 const DataLayout &DL = M->getDataLayout();
11732 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11733 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11734
11735 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000011736}
11737
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011738void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11739 IRBuilder<> &Builder) const {
11740 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011741 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011742}
11743
Tim Northover3b0846e2014-05-24 12:50:23 +000011744Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11745 Value *Val, Value *Addr,
11746 AtomicOrdering Ord) const {
11747 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011748 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011749
11750 // Since the intrinsics must have legal type, the i128 intrinsics take two
11751 // parameters: "i64, i64". We must marshal Val into the appropriate form
11752 // before the call.
11753 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11754 Intrinsic::ID Int =
11755 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11756 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11757 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11758
11759 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11760 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11761 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011762 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011763 }
11764
11765 Intrinsic::ID Int =
11766 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11767 Type *Tys[] = { Addr->getType() };
11768 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11769
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011770 const DataLayout &DL = M->getDataLayout();
11771 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
11772 Val = Builder.CreateBitCast(Val, IntValTy);
11773
David Blaikieff6409d2015-05-18 22:13:54 +000011774 return Builder.CreateCall(Stxr,
11775 {Builder.CreateZExtOrBitCast(
11776 Val, Stxr->getFunctionType()->getParamType(0)),
11777 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011778}
Tim Northover3c55cca2014-11-27 21:02:42 +000011779
11780bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11781 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11782 return Ty->isArrayTy();
11783}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011784
11785bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11786 EVT) const {
11787 return false;
11788}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011789
Petr Hoseka7d59162017-02-24 03:10:10 +000011790static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011791 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11792 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011793 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011794 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000011795 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
11796 Offset),
11797 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011798}
11799
Petr Hoseka7d59162017-02-24 03:10:10 +000011800Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11801 // Android provides a fixed TLS slot for the stack cookie. See the definition
11802 // of TLS_SLOT_STACK_GUARD in
11803 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11804 if (Subtarget->isTargetAndroid())
11805 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011806
Petr Hoseka7d59162017-02-24 03:10:10 +000011807 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011808 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011809 if (Subtarget->isTargetFuchsia())
11810 return UseTlsOffset(IRB, -0x10);
11811
11812 return TargetLowering::getIRStackGuard(IRB);
11813}
11814
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011815void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11816 // MSVC CRT provides functionalities for stack protection.
11817 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11818 // MSVC CRT has a global variable holding security cookie.
11819 M.getOrInsertGlobal("__security_cookie",
11820 Type::getInt8PtrTy(M.getContext()));
11821
11822 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000011823 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
11824 "__security_check_cookie", Type::getVoidTy(M.getContext()),
11825 Type::getInt8PtrTy(M.getContext()));
11826 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
11827 F->setCallingConv(CallingConv::Win64);
11828 F->addAttribute(1, Attribute::AttrKind::InReg);
11829 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011830 return;
11831 }
11832 TargetLowering::insertSSPDeclarations(M);
11833}
11834
11835Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
11836 // MSVC CRT has a global variable holding security cookie.
11837 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11838 return M.getGlobalVariable("__security_cookie");
11839 return TargetLowering::getSDagStackGuard(M);
11840}
11841
James Y Knight7976eb52019-02-01 20:43:25 +000011842Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011843 // MSVC CRT has a function to validate security cookie.
11844 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11845 return M.getFunction("__security_check_cookie");
11846 return TargetLowering::getSSPStackGuardCheck(M);
11847}
11848
Petr Hoseka7d59162017-02-24 03:10:10 +000011849Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011850 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11851 // definition of TLS_SLOT_SAFESTACK in
11852 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011853 if (Subtarget->isTargetAndroid())
11854 return UseTlsOffset(IRB, 0x48);
11855
11856 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011857 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011858 if (Subtarget->isTargetFuchsia())
11859 return UseTlsOffset(IRB, -0x8);
11860
11861 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011862}
Manman Rencbe4f942015-12-16 21:04:19 +000011863
Geoff Berry5d534b62017-02-21 18:53:14 +000011864bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11865 const Instruction &AndI) const {
11866 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11867 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11868 // may be beneficial to sink in other cases, but we would have to check that
11869 // the cmp would not get folded into the br to form a cbz for these to be
11870 // beneficial.
11871 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11872 if (!Mask)
11873 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011874 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011875}
11876
Manman Rencbe4f942015-12-16 21:04:19 +000011877void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11878 // Update IsSplitCSR in AArch64unctionInfo.
11879 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11880 AFI->setIsSplitCSR(true);
11881}
11882
11883void AArch64TargetLowering::insertCopiesSplitCSR(
11884 MachineBasicBlock *Entry,
11885 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11886 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11887 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11888 if (!IStart)
11889 return;
11890
11891 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11892 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011893 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011894 for (const MCPhysReg *I = IStart; *I; ++I) {
11895 const TargetRegisterClass *RC = nullptr;
11896 if (AArch64::GPR64RegClass.contains(*I))
11897 RC = &AArch64::GPR64RegClass;
11898 else if (AArch64::FPR64RegClass.contains(*I))
11899 RC = &AArch64::FPR64RegClass;
11900 else
11901 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11902
11903 unsigned NewVR = MRI->createVirtualRegister(RC);
11904 // Create copy from CSR to a virtual register.
11905 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11906 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11907 // nounwind. If we want to generalize this later, we may need to emit
11908 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011909 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011910 Attribute::NoUnwind) &&
11911 "Function should be nounwind in insertCopiesSplitCSR!");
11912 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011913 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011914 .addReg(*I);
11915
Manman Ren4632e8e2016-01-15 20:13:28 +000011916 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011917 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011918 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11919 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011920 .addReg(NewVR);
11921 }
11922}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011923
Reid Klecknerb5180542017-03-21 16:57:19 +000011924bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011925 // Integer division on AArch64 is expensive. However, when aggressively
11926 // optimizing for code size, we prefer to use a div instruction, as it is
11927 // usually smaller than the alternative sequence.
11928 // The exception to this is vector division. Since AArch64 doesn't have vector
11929 // integer division, leaving the division as-is is a loss even in terms of
11930 // size, because it will have to be scalarized, while the alternative code
11931 // sequence can be performed in vector form.
11932 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011933 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011934 return OptSize && !VT.isVector();
11935}
Tim Northoverf19d4672017-02-08 17:57:20 +000011936
Joel Jones07150922018-01-25 21:55:39 +000011937bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11938 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11939}
11940
Tim Northoverf19d4672017-02-08 17:57:20 +000011941unsigned
11942AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011943 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011944 return getPointerTy(DL).getSizeInBits();
11945
11946 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11947}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011948
11949void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11950 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11951 TargetLoweringBase::finalizeLowering(MF);
11952}
Eli Friedmanad1151c2018-11-09 23:33:30 +000011953
11954// Unlike X86, we let frame lowering assign offsets to all catch objects.
11955bool AArch64TargetLowering::needsFixedCatchObjects() const {
11956 return false;
11957}