blob: 72a35493f9aad5f08638a4c2714e4fcbfb3d2710 [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);
663 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
664 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000665 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
666 // -> v8f16 conversions.
Craig Toppera4f99972018-01-01 19:21:35 +0000667 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
668 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
669 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
670 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000671 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
672 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
673 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
674 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
675 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000676 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
677 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
678 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
679 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000680
Craig Topperc5551bf2016-04-26 05:26:51 +0000681 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
682 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
683
Craig Topper3b4842b2016-04-28 01:58:21 +0000684 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
685 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
686 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
687 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
688 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
689 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
690 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
691 setOperationAction(ISD::CTTZ, 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);
Tim Northover3b0846e2014-05-24 12:50:23 +0000731
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000732 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000733 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000734 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
735 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
736 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
737 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000738 }
739
740 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000741 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000742 setOperationAction(ISD::FFLOOR, Ty, Legal);
743 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
744 setOperationAction(ISD::FCEIL, Ty, Legal);
745 setOperationAction(ISD::FRINT, Ty, Legal);
746 setOperationAction(ISD::FTRUNC, Ty, Legal);
747 setOperationAction(ISD::FROUND, Ty, Legal);
748 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000749
750 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000751 }
James Molloyf089ab72014-08-06 10:42:18 +0000752
Matthias Braun651cff42016-06-02 18:03:53 +0000753 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000754}
755
Craig Topper18e69f42016-04-15 06:20:21 +0000756void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000757 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000758
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000759 if (VT.isFloatingPoint()) {
760 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
761 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
762 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000763 }
764
765 // Mark vector float intrinsics as expand.
766 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000767 setOperationAction(ISD::FSIN, VT, Expand);
768 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000769 setOperationAction(ISD::FPOW, VT, Expand);
770 setOperationAction(ISD::FLOG, VT, Expand);
771 setOperationAction(ISD::FLOG2, VT, Expand);
772 setOperationAction(ISD::FLOG10, VT, Expand);
773 setOperationAction(ISD::FEXP, VT, Expand);
774 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000775
776 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000777 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000778 }
779
Craig Topper18e69f42016-04-15 06:20:21 +0000780 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
781 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
782 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
783 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
784 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
785 setOperationAction(ISD::SRA, VT, Custom);
786 setOperationAction(ISD::SRL, VT, Custom);
787 setOperationAction(ISD::SHL, VT, Custom);
788 setOperationAction(ISD::AND, VT, Custom);
789 setOperationAction(ISD::OR, VT, Custom);
790 setOperationAction(ISD::SETCC, VT, Custom);
791 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000792
Craig Topper18e69f42016-04-15 06:20:21 +0000793 setOperationAction(ISD::SELECT, VT, Expand);
794 setOperationAction(ISD::SELECT_CC, VT, Expand);
795 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000796 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000797 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000798
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000799 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000800 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000801 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000802
Craig Topper18e69f42016-04-15 06:20:21 +0000803 setOperationAction(ISD::UDIV, VT, Expand);
804 setOperationAction(ISD::SDIV, VT, Expand);
805 setOperationAction(ISD::UREM, VT, Expand);
806 setOperationAction(ISD::SREM, VT, Expand);
807 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000808
Craig Topper18e69f42016-04-15 06:20:21 +0000809 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
810 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000811
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000812 if (!VT.isFloatingPoint())
813 setOperationAction(ISD::ABS, VT, Legal);
814
Hal Finkelcd8664c2015-12-11 23:11:52 +0000815 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000816 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000817 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000818 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000819
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000820 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
821 if (VT.isFloatingPoint() &&
822 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000823 for (unsigned Opcode :
824 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000825 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000826
Tim Northover3b0846e2014-05-24 12:50:23 +0000827 if (Subtarget->isLittleEndian()) {
828 for (unsigned im = (unsigned)ISD::PRE_INC;
829 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000830 setIndexedLoadAction(im, VT, Legal);
831 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000832 }
833 }
834}
835
836void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
837 addRegisterClass(VT, &AArch64::FPR64RegClass);
838 addTypeForNEON(VT, MVT::v2i32);
839}
840
841void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
842 addRegisterClass(VT, &AArch64::FPR128RegClass);
843 addTypeForNEON(VT, MVT::v4i32);
844}
845
Mehdi Amini44ede332015-07-09 02:09:04 +0000846EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
847 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000848 if (!VT.isVector())
849 return MVT::i32;
850 return VT.changeVectorElementTypeToInteger();
851}
852
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000853static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
854 const APInt &Demanded,
855 TargetLowering::TargetLoweringOpt &TLO,
856 unsigned NewOpc) {
857 uint64_t OldImm = Imm, NewImm, Enc;
858 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
859
860 // Return if the immediate is already all zeros, all ones, a bimm32 or a
861 // bimm64.
862 if (Imm == 0 || Imm == Mask ||
863 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
864 return false;
865
866 unsigned EltSize = Size;
867 uint64_t DemandedBits = Demanded.getZExtValue();
868
869 // Clear bits that are not demanded.
870 Imm &= DemandedBits;
871
872 while (true) {
873 // The goal here is to set the non-demanded bits in a way that minimizes
874 // the number of switching between 0 and 1. In order to achieve this goal,
875 // we set the non-demanded bits to the value of the preceding demanded bits.
876 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
877 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
878 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
879 // The final result is 0b11000011.
880 uint64_t NonDemandedBits = ~DemandedBits;
881 uint64_t InvertedImm = ~Imm & DemandedBits;
882 uint64_t RotatedImm =
883 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
884 NonDemandedBits;
885 uint64_t Sum = RotatedImm + NonDemandedBits;
886 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
887 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
888 NewImm = (Imm | Ones) & Mask;
889
890 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
891 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
892 // we halve the element size and continue the search.
893 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
894 break;
895
896 // We cannot shrink the element size any further if it is 2-bits.
897 if (EltSize == 2)
898 return false;
899
900 EltSize /= 2;
901 Mask >>= EltSize;
902 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
903
904 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
905 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
906 return false;
907
908 // Merge the upper and lower halves of Imm and DemandedBits.
909 Imm |= Hi;
910 DemandedBits |= DemandedBitsHi;
911 }
912
913 ++NumOptimizedImms;
914
915 // Replicate the element across the register width.
916 while (EltSize < Size) {
917 NewImm |= NewImm << EltSize;
918 EltSize *= 2;
919 }
920
921 (void)OldImm;
922 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
923 "demanded bits should never be altered");
924 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
925
926 // Create the new constant immediate node.
927 EVT VT = Op.getValueType();
928 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000929 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000930
931 // If the new constant immediate is all-zeros or all-ones, let the target
932 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000933 if (NewImm == 0 || NewImm == OrigMask) {
934 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
935 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000936 // Otherwise, create a machine node so that target independent DAG combine
937 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000938 } else {
939 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
940 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
941 New = SDValue(
942 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
943 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000944
945 return TLO.CombineTo(Op, New);
946}
947
948bool AArch64TargetLowering::targetShrinkDemandedConstant(
949 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
950 // Delay this optimization to as late as possible.
951 if (!TLO.LegalOps)
952 return false;
953
954 if (!EnableOptimizeLogicalImm)
955 return false;
956
957 EVT VT = Op.getValueType();
958 if (VT.isVector())
959 return false;
960
961 unsigned Size = VT.getSizeInBits();
962 assert((Size == 32 || Size == 64) &&
963 "i32 or i64 is expected after legalization.");
964
965 // Exit early if we demand all bits.
966 if (Demanded.countPopulation() == Size)
967 return false;
968
969 unsigned NewOpc;
970 switch (Op.getOpcode()) {
971 default:
972 return false;
973 case ISD::AND:
974 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
975 break;
976 case ISD::OR:
977 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
978 break;
979 case ISD::XOR:
980 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
981 break;
982 }
983 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
984 if (!C)
985 return false;
986 uint64_t Imm = C->getZExtValue();
987 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
988}
989
Tim Northover3b0846e2014-05-24 12:50:23 +0000990/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000991/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000992void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000993 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000994 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000995 switch (Op.getOpcode()) {
996 default:
997 break;
998 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000999 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +00001000 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1001 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +00001002 Known.Zero &= Known2.Zero;
1003 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001004 break;
1005 }
1006 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001007 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001008 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1009 switch (IntID) {
1010 default: return;
1011 case Intrinsic::aarch64_ldaxr:
1012 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001013 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001014 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001015 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001016 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001017 return;
1018 }
1019 }
1020 break;
1021 }
1022 case ISD::INTRINSIC_WO_CHAIN:
1023 case ISD::INTRINSIC_VOID: {
1024 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1025 switch (IntNo) {
1026 default:
1027 break;
1028 case Intrinsic::aarch64_neon_umaxv:
1029 case Intrinsic::aarch64_neon_uminv: {
1030 // Figure out the datatype of the vector operand. The UMINV instruction
1031 // will zero extend the result, so we can mark as known zero all the
1032 // bits larger than the element datatype. 32-bit or larget doesn't need
1033 // this as those are legal types and will be handled by isel directly.
1034 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001035 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001036 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1037 assert(BitWidth >= 8 && "Unexpected width!");
1038 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001039 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001040 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1041 assert(BitWidth >= 16 && "Unexpected width!");
1042 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001043 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001044 }
1045 break;
1046 } break;
1047 }
1048 }
1049 }
1050}
1051
Mehdi Aminieaabc512015-07-09 15:12:23 +00001052MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1053 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001054 return MVT::i64;
1055}
1056
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001057bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1058 unsigned AddrSpace,
1059 unsigned Align,
1060 bool *Fast) const {
1061 if (Subtarget->requiresStrictAlign())
1062 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001063
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001064 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001065 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1066 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001067 // See comments in performSTORECombine() for more details about
1068 // these conditions.
1069
1070 // Code that uses clang vector extensions can mark that it
1071 // wants unaligned accesses to be treated as fast by
1072 // underspecifying alignment to be 1 or 2.
1073 Align <= 2 ||
1074
1075 // Disregard v2i64. Memcpy lowering produces those and splitting
1076 // them regresses performance on micro-benchmarks and olden/bh.
1077 VT == MVT::v2i64;
1078 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001079 return true;
1080}
1081
Tim Northover3b0846e2014-05-24 12:50:23 +00001082FastISel *
1083AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1084 const TargetLibraryInfo *libInfo) const {
1085 return AArch64::createFastISel(funcInfo, libInfo);
1086}
1087
1088const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001089 switch ((AArch64ISD::NodeType)Opcode) {
1090 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001091 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1092 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001093 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001094 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1095 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1096 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1097 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1098 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1099 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1100 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1101 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1102 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1103 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001104 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001105 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1106 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1107 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1108 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1109 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1110 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1111 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001112 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1113 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1114 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001115 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001116 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1117 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1118 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1119 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1120 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1121 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1122 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1123 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1124 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1125 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1126 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1127 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1128 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1129 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1130 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1131 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1132 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1133 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1134 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1135 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1136 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1137 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1138 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1139 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1140 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1141 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1142 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1143 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1144 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1145 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1146 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1147 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1148 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1149 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1150 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1151 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1152 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1153 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1154 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1155 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1156 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1157 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1158 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1159 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1160 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1161 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1162 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1163 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001164 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1165 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1166 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1167 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1168 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1169 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001170 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1171 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1172 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1173 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1174 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1175 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1176 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001177 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001178 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1179 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001180 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001181 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1182 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1183 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1184 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1185 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1186 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1187 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1188 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1189 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1190 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1191 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1192 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1193 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1194 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1195 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1196 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1197 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1198 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1199 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1200 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1201 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1202 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1203 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1204 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1205 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1206 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1207 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1208 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1209 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001210 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1211 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001212 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001213 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1214 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1215 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001216 }
Matthias Braund04893f2015-05-07 21:33:59 +00001217 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001218}
1219
1220MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001221AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001222 MachineBasicBlock *MBB) const {
1223 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1224 // phi node:
1225
1226 // OrigBB:
1227 // [... previous instrs leading to comparison ...]
1228 // b.ne TrueBB
1229 // b EndBB
1230 // TrueBB:
1231 // ; Fallthrough
1232 // EndBB:
1233 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1234
Tim Northover3b0846e2014-05-24 12:50:23 +00001235 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001236 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001237 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001238 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001239 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001240
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001241 unsigned DestReg = MI.getOperand(0).getReg();
1242 unsigned IfTrueReg = MI.getOperand(1).getReg();
1243 unsigned IfFalseReg = MI.getOperand(2).getReg();
1244 unsigned CondCode = MI.getOperand(3).getImm();
1245 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001246
1247 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1248 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1249 MF->insert(It, TrueBB);
1250 MF->insert(It, EndBB);
1251
1252 // Transfer rest of current basic-block to EndBB
1253 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1254 MBB->end());
1255 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1256
1257 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1258 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1259 MBB->addSuccessor(TrueBB);
1260 MBB->addSuccessor(EndBB);
1261
1262 // TrueBB falls through to the end.
1263 TrueBB->addSuccessor(EndBB);
1264
1265 if (!NZCVKilled) {
1266 TrueBB->addLiveIn(AArch64::NZCV);
1267 EndBB->addLiveIn(AArch64::NZCV);
1268 }
1269
1270 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1271 .addReg(IfTrueReg)
1272 .addMBB(TrueBB)
1273 .addReg(IfFalseReg)
1274 .addMBB(MBB);
1275
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001276 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001277 return EndBB;
1278}
1279
Eli Friedmanad1151c2018-11-09 23:33:30 +00001280MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1281 MachineInstr &MI, MachineBasicBlock *BB) const {
1282 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1283 BB->getParent()->getFunction().getPersonalityFn())) &&
1284 "SEH does not use catchret!");
1285 return BB;
1286}
1287
1288MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1289 MachineInstr &MI, MachineBasicBlock *BB) const {
1290 MI.eraseFromParent();
1291 return BB;
1292}
1293
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001294MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1295 MachineInstr &MI, MachineBasicBlock *BB) const {
1296 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001297 default:
1298#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001299 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001300#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001301 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001302
1303 case AArch64::F128CSEL:
1304 return EmitF128CSEL(MI, BB);
1305
1306 case TargetOpcode::STACKMAP:
1307 case TargetOpcode::PATCHPOINT:
1308 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001309
1310 case AArch64::CATCHRET:
1311 return EmitLoweredCatchRet(MI, BB);
1312 case AArch64::CATCHPAD:
1313 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001314 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001315}
1316
1317//===----------------------------------------------------------------------===//
1318// AArch64 Lowering private implementation.
1319//===----------------------------------------------------------------------===//
1320
1321//===----------------------------------------------------------------------===//
1322// Lowering Code
1323//===----------------------------------------------------------------------===//
1324
1325/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1326/// CC
1327static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1328 switch (CC) {
1329 default:
1330 llvm_unreachable("Unknown condition code!");
1331 case ISD::SETNE:
1332 return AArch64CC::NE;
1333 case ISD::SETEQ:
1334 return AArch64CC::EQ;
1335 case ISD::SETGT:
1336 return AArch64CC::GT;
1337 case ISD::SETGE:
1338 return AArch64CC::GE;
1339 case ISD::SETLT:
1340 return AArch64CC::LT;
1341 case ISD::SETLE:
1342 return AArch64CC::LE;
1343 case ISD::SETUGT:
1344 return AArch64CC::HI;
1345 case ISD::SETUGE:
1346 return AArch64CC::HS;
1347 case ISD::SETULT:
1348 return AArch64CC::LO;
1349 case ISD::SETULE:
1350 return AArch64CC::LS;
1351 }
1352}
1353
1354/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1355static void changeFPCCToAArch64CC(ISD::CondCode CC,
1356 AArch64CC::CondCode &CondCode,
1357 AArch64CC::CondCode &CondCode2) {
1358 CondCode2 = AArch64CC::AL;
1359 switch (CC) {
1360 default:
1361 llvm_unreachable("Unknown FP condition!");
1362 case ISD::SETEQ:
1363 case ISD::SETOEQ:
1364 CondCode = AArch64CC::EQ;
1365 break;
1366 case ISD::SETGT:
1367 case ISD::SETOGT:
1368 CondCode = AArch64CC::GT;
1369 break;
1370 case ISD::SETGE:
1371 case ISD::SETOGE:
1372 CondCode = AArch64CC::GE;
1373 break;
1374 case ISD::SETOLT:
1375 CondCode = AArch64CC::MI;
1376 break;
1377 case ISD::SETOLE:
1378 CondCode = AArch64CC::LS;
1379 break;
1380 case ISD::SETONE:
1381 CondCode = AArch64CC::MI;
1382 CondCode2 = AArch64CC::GT;
1383 break;
1384 case ISD::SETO:
1385 CondCode = AArch64CC::VC;
1386 break;
1387 case ISD::SETUO:
1388 CondCode = AArch64CC::VS;
1389 break;
1390 case ISD::SETUEQ:
1391 CondCode = AArch64CC::EQ;
1392 CondCode2 = AArch64CC::VS;
1393 break;
1394 case ISD::SETUGT:
1395 CondCode = AArch64CC::HI;
1396 break;
1397 case ISD::SETUGE:
1398 CondCode = AArch64CC::PL;
1399 break;
1400 case ISD::SETLT:
1401 case ISD::SETULT:
1402 CondCode = AArch64CC::LT;
1403 break;
1404 case ISD::SETLE:
1405 case ISD::SETULE:
1406 CondCode = AArch64CC::LE;
1407 break;
1408 case ISD::SETNE:
1409 case ISD::SETUNE:
1410 CondCode = AArch64CC::NE;
1411 break;
1412 }
1413}
1414
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001415/// Convert a DAG fp condition code to an AArch64 CC.
1416/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1417/// should be AND'ed instead of OR'ed.
1418static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1419 AArch64CC::CondCode &CondCode,
1420 AArch64CC::CondCode &CondCode2) {
1421 CondCode2 = AArch64CC::AL;
1422 switch (CC) {
1423 default:
1424 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1425 assert(CondCode2 == AArch64CC::AL);
1426 break;
1427 case ISD::SETONE:
1428 // (a one b)
1429 // == ((a olt b) || (a ogt b))
1430 // == ((a ord b) && (a une b))
1431 CondCode = AArch64CC::VC;
1432 CondCode2 = AArch64CC::NE;
1433 break;
1434 case ISD::SETUEQ:
1435 // (a ueq b)
1436 // == ((a uno b) || (a oeq b))
1437 // == ((a ule b) && (a uge b))
1438 CondCode = AArch64CC::PL;
1439 CondCode2 = AArch64CC::LE;
1440 break;
1441 }
1442}
1443
Tim Northover3b0846e2014-05-24 12:50:23 +00001444/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1445/// CC usable with the vector instructions. Fewer operations are available
1446/// without a real NZCV register, so we have to use less efficient combinations
1447/// to get the same effect.
1448static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1449 AArch64CC::CondCode &CondCode,
1450 AArch64CC::CondCode &CondCode2,
1451 bool &Invert) {
1452 Invert = false;
1453 switch (CC) {
1454 default:
1455 // Mostly the scalar mappings work fine.
1456 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1457 break;
1458 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001459 Invert = true;
1460 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001461 case ISD::SETO:
1462 CondCode = AArch64CC::MI;
1463 CondCode2 = AArch64CC::GE;
1464 break;
1465 case ISD::SETUEQ:
1466 case ISD::SETULT:
1467 case ISD::SETULE:
1468 case ISD::SETUGT:
1469 case ISD::SETUGE:
1470 // All of the compare-mask comparisons are ordered, but we can switch
1471 // between the two by a double inversion. E.g. ULE == !OGT.
1472 Invert = true;
1473 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1474 break;
1475 }
1476}
1477
1478static bool isLegalArithImmed(uint64_t C) {
1479 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001480 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001481 LLVM_DEBUG(dbgs() << "Is imm " << C
1482 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001483 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001484}
1485
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001486// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1487// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1488// can be set differently by this operation. It comes down to whether
1489// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1490// everything is fine. If not then the optimization is wrong. Thus general
1491// comparisons are only valid if op2 != 0.
1492//
1493// So, finally, the only LLVM-native comparisons that don't mention C and V
1494// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1495// the absence of information about op2.
1496static bool isCMN(SDValue Op, ISD::CondCode CC) {
1497 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1498 (CC == ISD::SETEQ || CC == ISD::SETNE);
1499}
1500
Tim Northover3b0846e2014-05-24 12:50:23 +00001501static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001502 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001503 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001504 const bool FullFP16 =
1505 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001506
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001507 if (VT.isFloatingPoint()) {
1508 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001509 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001510 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1511 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001512 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001513 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001514 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001515 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001516
1517 // The CMP instruction is just an alias for SUBS, and representing it as
1518 // SUBS means that it's possible to get CSE with subtract operations.
1519 // A later phase can perform the optimization of setting the destination
1520 // register to WZR/XZR if it ends up being unused.
1521 unsigned Opcode = AArch64ISD::SUBS;
1522
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001523 if (isCMN(RHS, CC)) {
1524 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001525 Opcode = AArch64ISD::ADDS;
1526 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001527 } else if (isCMN(LHS, CC)) {
1528 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1529 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1530 Opcode = AArch64ISD::ADDS;
1531 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001532 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001533 !isUnsignedIntSetCC(CC)) {
1534 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1535 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1536 // of the signed comparisons.
1537 Opcode = AArch64ISD::ANDS;
1538 RHS = LHS.getOperand(1);
1539 LHS = LHS.getOperand(0);
1540 }
1541
Matthias Braunaf7d7702015-07-16 20:02:37 +00001542 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001543 .getValue(1);
1544}
1545
Matthias Braunaf7d7702015-07-16 20:02:37 +00001546/// \defgroup AArch64CCMP CMP;CCMP matching
1547///
1548/// These functions deal with the formation of CMP;CCMP;... sequences.
1549/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1550/// a comparison. They set the NZCV flags to a predefined value if their
1551/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001552/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001553/// expressed as:
1554/// cmp A
1555/// ccmp B, inv(CB), CA
1556/// check for CB flags
1557///
Matthias Braund0412122018-12-06 01:40:23 +00001558/// This naturally lets us implement chains of AND operations with SETCC
1559/// operands. And we can even implement some other situations by transforming
1560/// them:
1561/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1562/// negating the flags used in a CCMP/FCCMP operations.
1563/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1564/// by negating the flags we test for afterwards. i.e.
1565/// NEG (CMP CCMP CCCMP ...) can be implemented.
1566/// - Note that we can only ever negate all previously processed results.
1567/// What we can not implement by flipping the flags to test is a negation
1568/// of two sub-trees (because the negation affects all sub-trees emitted so
1569/// far, so the 2nd sub-tree we emit would also affect the first).
1570/// With those tools we can implement some OR operations:
1571/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1572/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1573/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1574/// elimination rules from earlier to implement the whole thing as a
1575/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001576///
Matthias Braund0412122018-12-06 01:40:23 +00001577/// As complete example:
1578/// or (or (setCA (cmp A)) (setCB (cmp B)))
1579/// (and (setCC (cmp C)) (setCD (cmp D)))"
1580/// can be reassociated to:
1581/// or (and (setCC (cmp C)) setCD (cmp D))
1582// (or (setCA (cmp A)) (setCB (cmp B)))
1583/// can be transformed to:
1584/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1585/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1586/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001587/// cmp C
1588/// ccmp D, inv(CD), CC
1589/// ccmp A, CA, inv(CD)
1590/// ccmp B, CB, inv(CA)
1591/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001592///
1593/// A counterexample is "or (and A B) (and C D)" which translates to
1594/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1595/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001596/// @{
1597
Geoff Berrye41c2df2015-07-20 22:03:52 +00001598/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001599static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1600 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001601 AArch64CC::CondCode Predicate,
1602 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001603 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001604 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001605 const bool FullFP16 =
1606 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1607
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001608 if (LHS.getValueType().isFloatingPoint()) {
1609 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001610 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001611 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1612 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1613 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001614 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001615 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001616 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001617 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001618 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1619 Opcode = AArch64ISD::CCMN;
1620 RHS = RHS.getOperand(1);
1621 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001622 }
1623 if (Opcode == 0)
1624 Opcode = AArch64ISD::CCMP;
1625
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001626 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1627 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1628 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001629 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1630 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1631}
1632
Matthias Braun96d12512018-11-06 03:15:22 +00001633/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1634/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001635/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1636/// changing the conditions on the SETCC tests.
1637/// (this means we can call emitConjunctionRec() with
1638/// Negate==true on this sub-tree)
1639/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1640/// cannot do the negation naturally. We are required to
1641/// emit the subtree first in this case.
1642/// \param WillNegate Is true if are called when the result of this
1643/// subexpression must be negated. This happens when the
1644/// outer expression is an OR. We can use this fact to know
1645/// that we have a double negation (or (or ...) ...) that
1646/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001647static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001648 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001649 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001650 if (!Val.hasOneUse())
1651 return false;
1652 unsigned Opcode = Val->getOpcode();
1653 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001654 if (Val->getOperand(0).getValueType() == MVT::f128)
1655 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001656 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001657 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001658 return true;
1659 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001660 // Protect against exponential runtime and stack overflow.
1661 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001662 return false;
1663 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001664 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001665 SDValue O0 = Val->getOperand(0);
1666 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001667 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001668 bool MustBeFirstL;
1669 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001670 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001671 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001672 bool MustBeFirstR;
1673 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001674 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001675
Matthias Braund0412122018-12-06 01:40:23 +00001676 if (MustBeFirstL && MustBeFirstR)
1677 return false;
1678
1679 if (IsOR) {
1680 // For an OR expression we need to be able to naturally negate at least
1681 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001682 if (!CanNegateL && !CanNegateR)
1683 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001684 // If we the result of the OR will be negated and we can naturally negate
1685 // the leafs, then this sub-tree as a whole negates naturally.
1686 CanNegate = WillNegate && CanNegateL && CanNegateR;
1687 // If we cannot naturally negate the whole sub-tree, then this must be
1688 // emitted first.
1689 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001690 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001691 assert(Opcode == ISD::AND && "Must be OR or AND");
1692 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001693 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001694 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001695 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001696 return true;
1697 }
1698 return false;
1699}
1700
1701/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1702/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1703/// Tries to transform the given i1 producing node @p Val to a series compare
1704/// and conditional compare operations. @returns an NZCV flags producing node
1705/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1706/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001707/// \p Negate is true if we want this sub-tree being negated just by changing
1708/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001709static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001710 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001711 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001712 // We're at a tree leaf, produce a conditional comparison operation.
1713 unsigned Opcode = Val->getOpcode();
1714 if (Opcode == ISD::SETCC) {
1715 SDValue LHS = Val->getOperand(0);
1716 SDValue RHS = Val->getOperand(1);
1717 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1718 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001719 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001720 CC = getSetCCInverse(CC, isInteger);
1721 SDLoc DL(Val);
1722 // Determine OutCC and handle FP special case.
1723 if (isInteger) {
1724 OutCC = changeIntCCToAArch64CC(CC);
1725 } else {
1726 assert(LHS.getValueType().isFloatingPoint());
1727 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001728 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1729 // Some floating point conditions can't be tested with a single condition
1730 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001731 if (ExtraCC != AArch64CC::AL) {
1732 SDValue ExtraCmp;
1733 if (!CCOp.getNode())
1734 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001735 else
1736 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001737 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001738 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001739 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001740 }
1741 }
1742
1743 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001744 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001745 return emitComparison(LHS, RHS, CC, DL, DAG);
1746 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001747 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001748 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001749 }
Matthias Braund0412122018-12-06 01:40:23 +00001750 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001751
Matthias Braund0412122018-12-06 01:40:23 +00001752 bool IsOR = Opcode == ISD::OR;
1753
Matthias Braunaf7d7702015-07-16 20:02:37 +00001754 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001755 bool CanNegateL;
1756 bool MustBeFirstL;
1757 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1758 assert(ValidL && "Valid conjunction/disjunction tree");
1759 (void)ValidL;
1760
Matthias Braunaf7d7702015-07-16 20:02:37 +00001761 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001762 bool CanNegateR;
1763 bool MustBeFirstR;
1764 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1765 assert(ValidR && "Valid conjunction/disjunction tree");
1766 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001767
Matthias Braund0412122018-12-06 01:40:23 +00001768 // Swap sub-tree that must come first to the right side.
1769 if (MustBeFirstL) {
1770 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1771 std::swap(LHS, RHS);
1772 std::swap(CanNegateL, CanNegateR);
1773 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001774 }
1775
Matthias Braund0412122018-12-06 01:40:23 +00001776 bool NegateR;
1777 bool NegateAfterR;
1778 bool NegateL;
1779 bool NegateAfterAll;
1780 if (Opcode == ISD::OR) {
1781 // Swap the sub-tree that we can negate naturally to the left.
1782 if (!CanNegateL) {
1783 assert(CanNegateR && "at least one side must be negatable");
1784 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1785 assert(!Negate);
1786 std::swap(LHS, RHS);
1787 NegateR = false;
1788 NegateAfterR = true;
1789 } else {
1790 // Negate the left sub-tree if possible, otherwise negate the result.
1791 NegateR = CanNegateR;
1792 NegateAfterR = !CanNegateR;
1793 }
1794 NegateL = true;
1795 NegateAfterAll = !Negate;
1796 } else {
1797 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1798 assert(!Negate && "Valid conjunction/disjunction tree");
1799
1800 NegateL = false;
1801 NegateR = false;
1802 NegateAfterR = false;
1803 NegateAfterAll = false;
1804 }
1805
1806 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001807 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001808 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1809 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001810 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001811 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1812 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001813 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1814 return CmpL;
1815}
1816
Matthias Braun96d12512018-11-06 03:15:22 +00001817/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1818/// In some cases this is even possible with OR operations in the expression.
1819/// See \ref AArch64CCMP.
1820/// \see emitConjunctionRec().
1821static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1822 AArch64CC::CondCode &OutCC) {
1823 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001824 bool DummyMustBeFirst;
1825 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001826 return SDValue();
1827
Matthias Braun96d12512018-11-06 03:15:22 +00001828 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001829}
1830
Matthias Braunaf7d7702015-07-16 20:02:37 +00001831/// @}
1832
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001833/// Returns how profitable it is to fold a comparison's operand's shift and/or
1834/// extension operations.
1835static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1836 auto isSupportedExtend = [&](SDValue V) {
1837 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1838 return true;
1839
1840 if (V.getOpcode() == ISD::AND)
1841 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1842 uint64_t Mask = MaskCst->getZExtValue();
1843 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1844 }
1845
1846 return false;
1847 };
1848
1849 if (!Op.hasOneUse())
1850 return 0;
1851
1852 if (isSupportedExtend(Op))
1853 return 1;
1854
1855 unsigned Opc = Op.getOpcode();
1856 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1857 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1858 uint64_t Shift = ShiftCst->getZExtValue();
1859 if (isSupportedExtend(Op.getOperand(0)))
1860 return (Shift <= 4) ? 2 : 1;
1861 EVT VT = Op.getValueType();
1862 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1863 return 1;
1864 }
1865
1866 return 0;
1867}
1868
Tim Northover3b0846e2014-05-24 12:50:23 +00001869static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001870 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001871 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001872 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1873 EVT VT = RHS.getValueType();
1874 uint64_t C = RHSC->getZExtValue();
1875 if (!isLegalArithImmed(C)) {
1876 // Constant does not fit, try adjusting it by one?
1877 switch (CC) {
1878 default:
1879 break;
1880 case ISD::SETLT:
1881 case ISD::SETGE:
1882 if ((VT == MVT::i32 && C != 0x80000000 &&
1883 isLegalArithImmed((uint32_t)(C - 1))) ||
1884 (VT == MVT::i64 && C != 0x80000000ULL &&
1885 isLegalArithImmed(C - 1ULL))) {
1886 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1887 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001888 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001889 }
1890 break;
1891 case ISD::SETULT:
1892 case ISD::SETUGE:
1893 if ((VT == MVT::i32 && C != 0 &&
1894 isLegalArithImmed((uint32_t)(C - 1))) ||
1895 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1896 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1897 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001898 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001899 }
1900 break;
1901 case ISD::SETLE:
1902 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001903 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001904 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001905 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001906 isLegalArithImmed(C + 1ULL))) {
1907 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1908 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001909 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001910 }
1911 break;
1912 case ISD::SETULE:
1913 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001914 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001915 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001916 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001917 isLegalArithImmed(C + 1ULL))) {
1918 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1919 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001920 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001921 }
1922 break;
1923 }
1924 }
1925 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001926
1927 // Comparisons are canonicalized so that the RHS operand is simpler than the
1928 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1929 // can fold some shift+extend operations on the RHS operand, so swap the
1930 // operands if that can be done.
1931 //
1932 // For example:
1933 // lsl w13, w11, #1
1934 // cmp w13, w12
1935 // can be turned into:
1936 // cmp w12, w11, lsl #1
1937 if (!isa<ConstantSDNode>(RHS) ||
1938 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1939 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1940
1941 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1942 std::swap(LHS, RHS);
1943 CC = ISD::getSetCCSwappedOperands(CC);
1944 }
1945 }
1946
Matthias Braunaf7d7702015-07-16 20:02:37 +00001947 SDValue Cmp;
1948 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001949 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001950 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1951
1952 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1953 // For the i8 operand, the largest immediate is 255, so this can be easily
1954 // encoded in the compare instruction. For the i16 operand, however, the
1955 // largest immediate cannot be encoded in the compare.
1956 // Therefore, use a sign extending load and cmn to avoid materializing the
1957 // -1 constant. For example,
1958 // movz w1, #65535
1959 // ldrh w0, [x0, #0]
1960 // cmp w0, w1
1961 // >
1962 // ldrsh w0, [x0, #0]
1963 // cmn w0, #1
1964 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1965 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001966 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001967 // transformation is profitable.
1968 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1969 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1970 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1971 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1972 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1973 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1974 SDValue SExt =
1975 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1976 DAG.getValueType(MVT::i16));
1977 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1978 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001979 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001980 AArch64CC = changeIntCCToAArch64CC(CC);
1981 }
1982 }
1983
1984 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00001985 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001986 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1987 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001988 }
1989 }
1990 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001991
1992 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001993 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001994 AArch64CC = changeIntCCToAArch64CC(CC);
1995 }
1996 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001997 return Cmp;
1998}
1999
2000static std::pair<SDValue, SDValue>
2001getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2002 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2003 "Unsupported value type");
2004 SDValue Value, Overflow;
2005 SDLoc DL(Op);
2006 SDValue LHS = Op.getOperand(0);
2007 SDValue RHS = Op.getOperand(1);
2008 unsigned Opc = 0;
2009 switch (Op.getOpcode()) {
2010 default:
2011 llvm_unreachable("Unknown overflow instruction!");
2012 case ISD::SADDO:
2013 Opc = AArch64ISD::ADDS;
2014 CC = AArch64CC::VS;
2015 break;
2016 case ISD::UADDO:
2017 Opc = AArch64ISD::ADDS;
2018 CC = AArch64CC::HS;
2019 break;
2020 case ISD::SSUBO:
2021 Opc = AArch64ISD::SUBS;
2022 CC = AArch64CC::VS;
2023 break;
2024 case ISD::USUBO:
2025 Opc = AArch64ISD::SUBS;
2026 CC = AArch64CC::LO;
2027 break;
2028 // Multiply needs a little bit extra work.
2029 case ISD::SMULO:
2030 case ISD::UMULO: {
2031 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002032 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002033 if (Op.getValueType() == MVT::i32) {
2034 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2035 // For a 32 bit multiply with overflow check we want the instruction
2036 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2037 // need to generate the following pattern:
2038 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2039 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2040 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2041 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2042 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002043 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002044 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2045 // operation. We need to clear out the upper 32 bits, because we used a
2046 // widening multiply that wrote all 64 bits. In the end this should be a
2047 // noop.
2048 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2049 if (IsSigned) {
2050 // The signed overflow check requires more than just a simple check for
2051 // any bit set in the upper 32 bits of the result. These bits could be
2052 // just the sign bits of a negative number. To perform the overflow
2053 // check we have to arithmetic shift right the 32nd bit of the result by
2054 // 31 bits. Then we compare the result to the upper 32 bits.
2055 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002056 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002057 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2058 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002059 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002060 // It is important that LowerBits is last, otherwise the arithmetic
2061 // shift will not be folded into the compare (SUBS).
2062 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2063 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2064 .getValue(1);
2065 } else {
2066 // The overflow check for unsigned multiply is easy. We only need to
2067 // check if any of the upper 32 bits are set. This can be done with a
2068 // CMP (shifted register). For that we need to generate the following
2069 // pattern:
2070 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2071 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002072 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002073 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2074 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002075 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2076 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002077 UpperBits).getValue(1);
2078 }
2079 break;
2080 }
2081 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2082 // For the 64 bit multiply
2083 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2084 if (IsSigned) {
2085 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2086 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002087 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002088 // It is important that LowerBits is last, otherwise the arithmetic
2089 // shift will not be folded into the compare (SUBS).
2090 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2091 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2092 .getValue(1);
2093 } else {
2094 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2095 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2096 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002097 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2098 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002099 UpperBits).getValue(1);
2100 }
2101 break;
2102 }
2103 } // switch (...)
2104
2105 if (Opc) {
2106 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2107
2108 // Emit the AArch64 operation with overflow check.
2109 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2110 Overflow = Value.getValue(1);
2111 }
2112 return std::make_pair(Value, Overflow);
2113}
2114
2115SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2116 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002117 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002118 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002119}
2120
Amara Emerson24ca39c2017-10-09 15:15:09 +00002121// Returns true if the given Op is the overflow flag result of an overflow
2122// intrinsic operation.
2123static bool isOverflowIntrOpRes(SDValue Op) {
2124 unsigned Opc = Op.getOpcode();
2125 return (Op.getResNo() == 1 &&
2126 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2127 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2128}
2129
Tim Northover3b0846e2014-05-24 12:50:23 +00002130static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2131 SDValue Sel = Op.getOperand(0);
2132 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002133 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002134
Amara Emerson24ca39c2017-10-09 15:15:09 +00002135 // If the operand is an overflow checking operation, invert the condition
2136 // code and kill the Not operation. I.e., transform:
2137 // (xor (overflow_op_bool, 1))
2138 // -->
2139 // (csel 1, 0, invert(cc), overflow_op_bool)
2140 // ... which later gets transformed to just a cset instruction with an
2141 // inverted condition code, rather than a cset + eor sequence.
2142 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2143 // Only lower legal XALUO ops.
2144 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2145 return SDValue();
2146
2147 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2148 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2149 AArch64CC::CondCode CC;
2150 SDValue Value, Overflow;
2151 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2152 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2153 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2154 CCVal, Overflow);
2155 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002156 // If neither operand is a SELECT_CC, give up.
2157 if (Sel.getOpcode() != ISD::SELECT_CC)
2158 std::swap(Sel, Other);
2159 if (Sel.getOpcode() != ISD::SELECT_CC)
2160 return Op;
2161
2162 // The folding we want to perform is:
2163 // (xor x, (select_cc a, b, cc, 0, -1) )
2164 // -->
2165 // (csel x, (xor x, -1), cc ...)
2166 //
2167 // The latter will get matched to a CSINV instruction.
2168
2169 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2170 SDValue LHS = Sel.getOperand(0);
2171 SDValue RHS = Sel.getOperand(1);
2172 SDValue TVal = Sel.getOperand(2);
2173 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002174
2175 // FIXME: This could be generalized to non-integer comparisons.
2176 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2177 return Op;
2178
2179 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2180 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2181
Eric Christopher572e03a2015-06-19 01:53:21 +00002182 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002183 if (!CFVal || !CTVal)
2184 return Op;
2185
2186 // We can commute the SELECT_CC by inverting the condition. This
2187 // might be needed to make this fit into a CSINV pattern.
2188 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2189 std::swap(TVal, FVal);
2190 std::swap(CTVal, CFVal);
2191 CC = ISD::getSetCCInverse(CC, true);
2192 }
2193
2194 // If the constants line up, perform the transform!
2195 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2196 SDValue CCVal;
2197 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2198
2199 FVal = Other;
2200 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002201 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002202
2203 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2204 CCVal, Cmp);
2205 }
2206
2207 return Op;
2208}
2209
2210static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2211 EVT VT = Op.getValueType();
2212
2213 // Let legalize expand this if it isn't a legal type yet.
2214 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2215 return SDValue();
2216
2217 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2218
2219 unsigned Opc;
2220 bool ExtraOp = false;
2221 switch (Op.getOpcode()) {
2222 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002223 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002224 case ISD::ADDC:
2225 Opc = AArch64ISD::ADDS;
2226 break;
2227 case ISD::SUBC:
2228 Opc = AArch64ISD::SUBS;
2229 break;
2230 case ISD::ADDE:
2231 Opc = AArch64ISD::ADCS;
2232 ExtraOp = true;
2233 break;
2234 case ISD::SUBE:
2235 Opc = AArch64ISD::SBCS;
2236 ExtraOp = true;
2237 break;
2238 }
2239
2240 if (!ExtraOp)
2241 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2242 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2243 Op.getOperand(2));
2244}
2245
2246static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2247 // Let legalize expand this if it isn't a legal type yet.
2248 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2249 return SDValue();
2250
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002251 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002252 AArch64CC::CondCode CC;
2253 // The actual operation that sets the overflow or carry flag.
2254 SDValue Value, Overflow;
2255 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2256
2257 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002258 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2259 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002260
2261 // We use an inverted condition, because the conditional select is inverted
2262 // too. This will allow it to be selected to a single instruction:
2263 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002264 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2265 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002266 CCVal, Overflow);
2267
2268 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002269 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002270}
2271
2272// Prefetch operands are:
2273// 1: Address to prefetch
2274// 2: bool isWrite
2275// 3: int locality (0 = no locality ... 3 = extreme locality)
2276// 4: bool isDataCache
2277static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2278 SDLoc DL(Op);
2279 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2280 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002281 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002282
2283 bool IsStream = !Locality;
2284 // When the locality number is set
2285 if (Locality) {
2286 // The front-end should have filtered out the out-of-range values
2287 assert(Locality <= 3 && "Prefetch locality out-of-range");
2288 // The locality degree is the opposite of the cache speed.
2289 // Put the number the other way around.
2290 // The encoding starts at 0 for level 1
2291 Locality = 3 - Locality;
2292 }
2293
2294 // built the mask value encoding the expected behavior.
2295 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002296 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002297 (Locality << 1) | // Cache level bits
2298 (unsigned)IsStream; // Stream bit
2299 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002300 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002301}
2302
2303SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2304 SelectionDAG &DAG) const {
2305 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2306
2307 RTLIB::Libcall LC;
2308 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2309
2310 return LowerF128Call(Op, DAG, LC);
2311}
2312
2313SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2314 SelectionDAG &DAG) const {
2315 if (Op.getOperand(0).getValueType() != MVT::f128) {
2316 // It's legal except when f128 is involved
2317 return Op;
2318 }
2319
2320 RTLIB::Libcall LC;
2321 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2322
2323 // FP_ROUND node has a second operand indicating whether it is known to be
2324 // precise. That doesn't take part in the LibCall so we can't directly use
2325 // LowerF128Call.
2326 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002327 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2328 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002329}
2330
2331static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2332 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2333 // Any additional optimization in this function should be recorded
2334 // in the cost tables.
2335 EVT InVT = Op.getOperand(0).getValueType();
2336 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002337 unsigned NumElts = InVT.getVectorNumElements();
2338
2339 // f16 vectors are promoted to f32 before a conversion.
2340 if (InVT.getVectorElementType() == MVT::f16) {
2341 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2342 SDLoc dl(Op);
2343 return DAG.getNode(
2344 Op.getOpcode(), dl, Op.getValueType(),
2345 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2346 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002347
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002348 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002349 SDLoc dl(Op);
2350 SDValue Cv =
2351 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2352 Op.getOperand(0));
2353 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002354 }
2355
2356 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002357 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002358 MVT ExtVT =
2359 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2360 VT.getVectorNumElements());
2361 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002362 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2363 }
2364
2365 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002366 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002367}
2368
2369SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2370 SelectionDAG &DAG) const {
2371 if (Op.getOperand(0).getValueType().isVector())
2372 return LowerVectorFP_TO_INT(Op, DAG);
2373
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002374 // f16 conversions are promoted to f32 when full fp16 is not supported.
2375 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2376 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002377 SDLoc dl(Op);
2378 return DAG.getNode(
2379 Op.getOpcode(), dl, Op.getValueType(),
2380 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2381 }
2382
Tim Northover3b0846e2014-05-24 12:50:23 +00002383 if (Op.getOperand(0).getValueType() != MVT::f128) {
2384 // It's legal except when f128 is involved
2385 return Op;
2386 }
2387
2388 RTLIB::Libcall LC;
2389 if (Op.getOpcode() == ISD::FP_TO_SINT)
2390 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2391 else
2392 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2393
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002394 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002395 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002396}
2397
2398static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2399 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2400 // Any additional optimization in this function should be recorded
2401 // in the cost tables.
2402 EVT VT = Op.getValueType();
2403 SDLoc dl(Op);
2404 SDValue In = Op.getOperand(0);
2405 EVT InVT = In.getValueType();
2406
Tim Northoveref0d7602014-06-15 09:27:06 +00002407 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2408 MVT CastVT =
2409 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2410 InVT.getVectorNumElements());
2411 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002412 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002413 }
2414
Tim Northoveref0d7602014-06-15 09:27:06 +00002415 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2416 unsigned CastOpc =
2417 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2418 EVT CastVT = VT.changeVectorElementTypeToInteger();
2419 In = DAG.getNode(CastOpc, dl, CastVT, In);
2420 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002421 }
2422
Tim Northoveref0d7602014-06-15 09:27:06 +00002423 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002424}
2425
2426SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2427 SelectionDAG &DAG) const {
2428 if (Op.getValueType().isVector())
2429 return LowerVectorINT_TO_FP(Op, DAG);
2430
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002431 // f16 conversions are promoted to f32 when full fp16 is not supported.
2432 if (Op.getValueType() == MVT::f16 &&
2433 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002434 SDLoc dl(Op);
2435 return DAG.getNode(
2436 ISD::FP_ROUND, dl, MVT::f16,
2437 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002438 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002439 }
2440
Tim Northover3b0846e2014-05-24 12:50:23 +00002441 // i128 conversions are libcalls.
2442 if (Op.getOperand(0).getValueType() == MVT::i128)
2443 return SDValue();
2444
2445 // Other conversions are legal, unless it's to the completely software-based
2446 // fp128.
2447 if (Op.getValueType() != MVT::f128)
2448 return Op;
2449
2450 RTLIB::Libcall LC;
2451 if (Op.getOpcode() == ISD::SINT_TO_FP)
2452 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2453 else
2454 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2455
2456 return LowerF128Call(Op, DAG, LC);
2457}
2458
2459SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2460 SelectionDAG &DAG) const {
2461 // For iOS, we want to call an alternative entry point: __sincos_stret,
2462 // which returns the values in two S / D registers.
2463 SDLoc dl(Op);
2464 SDValue Arg = Op.getOperand(0);
2465 EVT ArgVT = Arg.getValueType();
2466 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2467
2468 ArgListTy Args;
2469 ArgListEntry Entry;
2470
2471 Entry.Node = Arg;
2472 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002473 Entry.IsSExt = false;
2474 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002475 Args.push_back(Entry);
2476
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002477 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2478 : RTLIB::SINCOS_STRET_F32;
2479 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002480 SDValue Callee =
2481 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002482
Serge Gueltone38003f2017-05-09 19:31:13 +00002483 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002484 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002485 CLI.setDebugLoc(dl)
2486 .setChain(DAG.getEntryNode())
2487 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002488
2489 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2490 return CallResult.first;
2491}
2492
Tim Northoverf8bfe212014-07-18 13:07:05 +00002493static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2494 if (Op.getValueType() != MVT::f16)
2495 return SDValue();
2496
2497 assert(Op.getOperand(0).getValueType() == MVT::i16);
2498 SDLoc DL(Op);
2499
2500 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2501 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2502 return SDValue(
2503 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002504 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002505 0);
2506}
2507
Chad Rosierd9d0f862014-10-08 02:31:24 +00002508static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2509 if (OrigVT.getSizeInBits() >= 64)
2510 return OrigVT;
2511
2512 assert(OrigVT.isSimple() && "Expecting a simple value type");
2513
2514 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2515 switch (OrigSimpleTy) {
2516 default: llvm_unreachable("Unexpected Vector Type");
2517 case MVT::v2i8:
2518 case MVT::v2i16:
2519 return MVT::v2i32;
2520 case MVT::v4i8:
2521 return MVT::v4i16;
2522 }
2523}
2524
2525static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2526 const EVT &OrigTy,
2527 const EVT &ExtTy,
2528 unsigned ExtOpcode) {
2529 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2530 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2531 // 64-bits we need to insert a new extension so that it will be 64-bits.
2532 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2533 if (OrigTy.getSizeInBits() >= 64)
2534 return N;
2535
2536 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2537 EVT NewVT = getExtensionTo64Bits(OrigTy);
2538
2539 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2540}
2541
2542static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2543 bool isSigned) {
2544 EVT VT = N->getValueType(0);
2545
2546 if (N->getOpcode() != ISD::BUILD_VECTOR)
2547 return false;
2548
Pete Cooper3af9a252015-06-26 18:17:36 +00002549 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002550 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002551 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002552 unsigned HalfSize = EltSize / 2;
2553 if (isSigned) {
2554 if (!isIntN(HalfSize, C->getSExtValue()))
2555 return false;
2556 } else {
2557 if (!isUIntN(HalfSize, C->getZExtValue()))
2558 return false;
2559 }
2560 continue;
2561 }
2562 return false;
2563 }
2564
2565 return true;
2566}
2567
2568static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2569 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2570 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2571 N->getOperand(0)->getValueType(0),
2572 N->getValueType(0),
2573 N->getOpcode());
2574
2575 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2576 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002577 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002578 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002579 unsigned NumElts = VT.getVectorNumElements();
2580 MVT TruncVT = MVT::getIntegerVT(EltSize);
2581 SmallVector<SDValue, 8> Ops;
2582 for (unsigned i = 0; i != NumElts; ++i) {
2583 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2584 const APInt &CInt = C->getAPIntValue();
2585 // Element types smaller than 32 bits are not legal, so use i32 elements.
2586 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002587 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002588 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002589 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002590}
2591
2592static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002593 return N->getOpcode() == ISD::SIGN_EXTEND ||
2594 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002595}
2596
2597static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002598 return N->getOpcode() == ISD::ZERO_EXTEND ||
2599 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002600}
2601
2602static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2603 unsigned Opcode = N->getOpcode();
2604 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2605 SDNode *N0 = N->getOperand(0).getNode();
2606 SDNode *N1 = N->getOperand(1).getNode();
2607 return N0->hasOneUse() && N1->hasOneUse() &&
2608 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2609 }
2610 return false;
2611}
2612
2613static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2614 unsigned Opcode = N->getOpcode();
2615 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2616 SDNode *N0 = N->getOperand(0).getNode();
2617 SDNode *N1 = N->getOperand(1).getNode();
2618 return N0->hasOneUse() && N1->hasOneUse() &&
2619 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2620 }
2621 return false;
2622}
2623
Tim Northover70666e72018-06-20 12:09:01 +00002624SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2625 SelectionDAG &DAG) const {
2626 // The rounding mode is in bits 23:22 of the FPSCR.
2627 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2628 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2629 // so that the shift + and get folded into a bitfield extract.
2630 SDLoc dl(Op);
2631
2632 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2633 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2634 MVT::i64));
2635 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2636 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2637 DAG.getConstant(1U << 22, dl, MVT::i32));
2638 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2639 DAG.getConstant(22, dl, MVT::i32));
2640 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2641 DAG.getConstant(3, dl, MVT::i32));
2642}
2643
Chad Rosierd9d0f862014-10-08 02:31:24 +00002644static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2645 // Multiplications are only custom-lowered for 128-bit vectors so that
2646 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2647 EVT VT = Op.getValueType();
2648 assert(VT.is128BitVector() && VT.isInteger() &&
2649 "unexpected type for custom-lowering ISD::MUL");
2650 SDNode *N0 = Op.getOperand(0).getNode();
2651 SDNode *N1 = Op.getOperand(1).getNode();
2652 unsigned NewOpc = 0;
2653 bool isMLA = false;
2654 bool isN0SExt = isSignExtended(N0, DAG);
2655 bool isN1SExt = isSignExtended(N1, DAG);
2656 if (isN0SExt && isN1SExt)
2657 NewOpc = AArch64ISD::SMULL;
2658 else {
2659 bool isN0ZExt = isZeroExtended(N0, DAG);
2660 bool isN1ZExt = isZeroExtended(N1, DAG);
2661 if (isN0ZExt && isN1ZExt)
2662 NewOpc = AArch64ISD::UMULL;
2663 else if (isN1SExt || isN1ZExt) {
2664 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2665 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2666 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2667 NewOpc = AArch64ISD::SMULL;
2668 isMLA = true;
2669 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2670 NewOpc = AArch64ISD::UMULL;
2671 isMLA = true;
2672 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2673 std::swap(N0, N1);
2674 NewOpc = AArch64ISD::UMULL;
2675 isMLA = true;
2676 }
2677 }
2678
2679 if (!NewOpc) {
2680 if (VT == MVT::v2i64)
2681 // Fall through to expand this. It is not legal.
2682 return SDValue();
2683 else
2684 // Other vector multiplications are legal.
2685 return Op;
2686 }
2687 }
2688
2689 // Legalize to a S/UMULL instruction
2690 SDLoc DL(Op);
2691 SDValue Op0;
2692 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2693 if (!isMLA) {
2694 Op0 = skipExtensionForVectorMULL(N0, DAG);
2695 assert(Op0.getValueType().is64BitVector() &&
2696 Op1.getValueType().is64BitVector() &&
2697 "unexpected types for extended operands to VMULL");
2698 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2699 }
2700 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2701 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2702 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2703 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2704 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2705 EVT Op1VT = Op1.getValueType();
2706 return DAG.getNode(N0->getOpcode(), DL, VT,
2707 DAG.getNode(NewOpc, DL, VT,
2708 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2709 DAG.getNode(NewOpc, DL, VT,
2710 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2711}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002712
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002713SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2714 SelectionDAG &DAG) const {
2715 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2716 SDLoc dl(Op);
2717 switch (IntNo) {
2718 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002719 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002720 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2721 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2722 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002723 case Intrinsic::aarch64_neon_abs: {
2724 EVT Ty = Op.getValueType();
2725 if (Ty == MVT::i64) {
2726 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2727 Op.getOperand(1));
2728 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2729 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2730 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2731 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2732 } else {
2733 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2734 }
2735 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002736 case Intrinsic::aarch64_neon_smax:
2737 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2738 Op.getOperand(1), Op.getOperand(2));
2739 case Intrinsic::aarch64_neon_umax:
2740 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2741 Op.getOperand(1), Op.getOperand(2));
2742 case Intrinsic::aarch64_neon_smin:
2743 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2744 Op.getOperand(1), Op.getOperand(2));
2745 case Intrinsic::aarch64_neon_umin:
2746 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2747 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002748
2749 case Intrinsic::localaddress: {
Mandeep Singh Grang70d484d2019-02-01 21:41:33 +00002750 const auto &MF = DAG.getMachineFunction();
2751 const auto *RegInfo = Subtarget->getRegisterInfo();
2752 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002753 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2754 Op.getSimpleValueType());
2755 }
2756
2757 case Intrinsic::eh_recoverfp: {
2758 // FIXME: This needs to be implemented to correctly handle highly aligned
2759 // stack objects. For now we simply return the incoming FP. Refer D53541
2760 // for more details.
2761 SDValue FnOp = Op.getOperand(1);
2762 SDValue IncomingFPOp = Op.getOperand(2);
2763 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2764 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2765 if (!Fn)
2766 report_fatal_error(
2767 "llvm.eh.recoverfp must take a function as the first argument");
2768 return IncomingFPOp;
2769 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002770 }
2771}
2772
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002773// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2774static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2775 EVT VT, EVT MemVT,
2776 SelectionDAG &DAG) {
2777 assert(VT.isVector() && "VT should be a vector type");
2778 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2779
2780 SDValue Value = ST->getValue();
2781
2782 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2783 // the word lane which represent the v4i8 subvector. It optimizes the store
2784 // to:
2785 //
2786 // xtn v0.8b, v0.8h
2787 // str s0, [x0]
2788
2789 SDValue Undef = DAG.getUNDEF(MVT::i16);
2790 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2791 {Undef, Undef, Undef, Undef});
2792
2793 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2794 Value, UndefVec);
2795 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2796
2797 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2798 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2799 Trunc, DAG.getConstant(0, DL, MVT::i64));
2800
2801 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2802 ST->getBasePtr(), ST->getMemOperand());
2803}
2804
2805// Custom lowering for any store, vector or scalar and/or default or with
2806// a truncate operations. Currently only custom lower truncate operation
2807// from vector v4i16 to v4i8.
2808SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2809 SelectionDAG &DAG) const {
2810 SDLoc Dl(Op);
2811 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2812 assert (StoreNode && "Can only custom lower store nodes");
2813
2814 SDValue Value = StoreNode->getValue();
2815
2816 EVT VT = Value.getValueType();
2817 EVT MemVT = StoreNode->getMemoryVT();
2818
2819 assert (VT.isVector() && "Can only custom lower vector store types");
2820
2821 unsigned AS = StoreNode->getAddressSpace();
2822 unsigned Align = StoreNode->getAlignment();
2823 if (Align < MemVT.getStoreSize() &&
2824 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2825 return scalarizeVectorStore(StoreNode, DAG);
2826 }
2827
2828 if (StoreNode->isTruncatingStore()) {
2829 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2830 }
2831
2832 return SDValue();
2833}
2834
Tim Northover3b0846e2014-05-24 12:50:23 +00002835SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2836 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002837 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2838 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002839
Tim Northover3b0846e2014-05-24 12:50:23 +00002840 switch (Op.getOpcode()) {
2841 default:
2842 llvm_unreachable("unimplemented operand");
2843 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002844 case ISD::BITCAST:
2845 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002846 case ISD::GlobalAddress:
2847 return LowerGlobalAddress(Op, DAG);
2848 case ISD::GlobalTLSAddress:
2849 return LowerGlobalTLSAddress(Op, DAG);
2850 case ISD::SETCC:
2851 return LowerSETCC(Op, DAG);
2852 case ISD::BR_CC:
2853 return LowerBR_CC(Op, DAG);
2854 case ISD::SELECT:
2855 return LowerSELECT(Op, DAG);
2856 case ISD::SELECT_CC:
2857 return LowerSELECT_CC(Op, DAG);
2858 case ISD::JumpTable:
2859 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002860 case ISD::BR_JT:
2861 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002862 case ISD::ConstantPool:
2863 return LowerConstantPool(Op, DAG);
2864 case ISD::BlockAddress:
2865 return LowerBlockAddress(Op, DAG);
2866 case ISD::VASTART:
2867 return LowerVASTART(Op, DAG);
2868 case ISD::VACOPY:
2869 return LowerVACOPY(Op, DAG);
2870 case ISD::VAARG:
2871 return LowerVAARG(Op, DAG);
2872 case ISD::ADDC:
2873 case ISD::ADDE:
2874 case ISD::SUBC:
2875 case ISD::SUBE:
2876 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2877 case ISD::SADDO:
2878 case ISD::UADDO:
2879 case ISD::SSUBO:
2880 case ISD::USUBO:
2881 case ISD::SMULO:
2882 case ISD::UMULO:
2883 return LowerXALUO(Op, DAG);
2884 case ISD::FADD:
2885 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2886 case ISD::FSUB:
2887 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2888 case ISD::FMUL:
2889 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2890 case ISD::FDIV:
2891 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2892 case ISD::FP_ROUND:
2893 return LowerFP_ROUND(Op, DAG);
2894 case ISD::FP_EXTEND:
2895 return LowerFP_EXTEND(Op, DAG);
2896 case ISD::FRAMEADDR:
2897 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002898 case ISD::SPONENTRY:
2899 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002900 case ISD::RETURNADDR:
2901 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002902 case ISD::ADDROFRETURNADDR:
2903 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002904 case ISD::INSERT_VECTOR_ELT:
2905 return LowerINSERT_VECTOR_ELT(Op, DAG);
2906 case ISD::EXTRACT_VECTOR_ELT:
2907 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2908 case ISD::BUILD_VECTOR:
2909 return LowerBUILD_VECTOR(Op, DAG);
2910 case ISD::VECTOR_SHUFFLE:
2911 return LowerVECTOR_SHUFFLE(Op, DAG);
2912 case ISD::EXTRACT_SUBVECTOR:
2913 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2914 case ISD::SRA:
2915 case ISD::SRL:
2916 case ISD::SHL:
2917 return LowerVectorSRA_SRL_SHL(Op, DAG);
2918 case ISD::SHL_PARTS:
2919 return LowerShiftLeftParts(Op, DAG);
2920 case ISD::SRL_PARTS:
2921 case ISD::SRA_PARTS:
2922 return LowerShiftRightParts(Op, DAG);
2923 case ISD::CTPOP:
2924 return LowerCTPOP(Op, DAG);
2925 case ISD::FCOPYSIGN:
2926 return LowerFCOPYSIGN(Op, DAG);
2927 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002928 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002929 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002930 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002931 case ISD::XOR:
2932 return LowerXOR(Op, DAG);
2933 case ISD::PREFETCH:
2934 return LowerPREFETCH(Op, DAG);
2935 case ISD::SINT_TO_FP:
2936 case ISD::UINT_TO_FP:
2937 return LowerINT_TO_FP(Op, DAG);
2938 case ISD::FP_TO_SINT:
2939 case ISD::FP_TO_UINT:
2940 return LowerFP_TO_INT(Op, DAG);
2941 case ISD::FSINCOS:
2942 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002943 case ISD::FLT_ROUNDS_:
2944 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002945 case ISD::MUL:
2946 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002947 case ISD::INTRINSIC_WO_CHAIN:
2948 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002949 case ISD::STORE:
2950 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002951 case ISD::VECREDUCE_ADD:
2952 case ISD::VECREDUCE_SMAX:
2953 case ISD::VECREDUCE_SMIN:
2954 case ISD::VECREDUCE_UMAX:
2955 case ISD::VECREDUCE_UMIN:
2956 case ISD::VECREDUCE_FMAX:
2957 case ISD::VECREDUCE_FMIN:
2958 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002959 case ISD::ATOMIC_LOAD_SUB:
2960 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002961 case ISD::ATOMIC_LOAD_AND:
2962 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002963 case ISD::DYNAMIC_STACKALLOC:
2964 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002965 }
2966}
2967
Tim Northover3b0846e2014-05-24 12:50:23 +00002968//===----------------------------------------------------------------------===//
2969// Calling Convention Implementation
2970//===----------------------------------------------------------------------===//
2971
Robin Morisset039781e2014-08-29 21:53:01 +00002972/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002973CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2974 bool IsVarArg) const {
2975 switch (CC) {
2976 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002977 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002978 case CallingConv::WebKit_JS:
2979 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002980 case CallingConv::GHC:
2981 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002982 case CallingConv::C:
2983 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002984 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002985 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002986 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002987 if (Subtarget->isTargetWindows() && IsVarArg)
2988 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002989 if (!Subtarget->isTargetDarwin())
2990 return CC_AArch64_AAPCS;
2991 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002992 case CallingConv::Win64:
2993 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00002994 case CallingConv::AArch64_VectorCall:
2995 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002996 }
2997}
2998
Tim Northover406024a2016-08-10 21:44:01 +00002999CCAssignFn *
3000AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3001 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3002 : RetCC_AArch64_AAPCS;
3003}
3004
Tim Northover3b0846e2014-05-24 12:50:23 +00003005SDValue AArch64TargetLowering::LowerFormalArguments(
3006 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003007 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3008 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003009 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003010 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003011 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003012
3013 // Assign locations to all of the incoming arguments.
3014 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003015 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3016 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003017
3018 // At this point, Ins[].VT may already be promoted to i32. To correctly
3019 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3020 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3021 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3022 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3023 // LocVT.
3024 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003025 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003026 unsigned CurArgIdx = 0;
3027 for (unsigned i = 0; i != NumArgs; ++i) {
3028 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003029 if (Ins[i].isOrigArg()) {
3030 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3031 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003032
Andrew Trick05938a52015-02-16 18:10:47 +00003033 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003034 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3035 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003036 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3037 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3038 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3039 ValVT = MVT::i8;
3040 else if (ActualMVT == MVT::i16)
3041 ValVT = MVT::i16;
3042 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003043 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3044 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003045 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003046 assert(!Res && "Call operand has unhandled type");
3047 (void)Res;
3048 }
3049 assert(ArgLocs.size() == Ins.size());
3050 SmallVector<SDValue, 16> ArgValues;
3051 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3052 CCValAssign &VA = ArgLocs[i];
3053
3054 if (Ins[i].Flags.isByVal()) {
3055 // Byval is used for HFAs in the PCS, but the system should work in a
3056 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003057 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003058 int Size = Ins[i].Flags.getByValSize();
3059 unsigned NumRegs = (Size + 7) / 8;
3060
3061 // FIXME: This works on big-endian for composite byvals, which are the common
3062 // case. It should also work for fundamental types too.
3063 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003064 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003065 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003066 InVals.push_back(FrameIdxN);
3067
3068 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003069 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003070
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003071 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003072 // Arguments stored in registers.
3073 EVT RegVT = VA.getLocVT();
3074
3075 SDValue ArgValue;
3076 const TargetRegisterClass *RC;
3077
3078 if (RegVT == MVT::i32)
3079 RC = &AArch64::GPR32RegClass;
3080 else if (RegVT == MVT::i64)
3081 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003082 else if (RegVT == MVT::f16)
3083 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003084 else if (RegVT == MVT::f32)
3085 RC = &AArch64::FPR32RegClass;
3086 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3087 RC = &AArch64::FPR64RegClass;
3088 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3089 RC = &AArch64::FPR128RegClass;
3090 else
3091 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3092
3093 // Transform the arguments in physical registers into virtual ones.
3094 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3095 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3096
3097 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3098 // to 64 bits. Insert an assert[sz]ext to capture this, then
3099 // truncate to the right size.
3100 switch (VA.getLocInfo()) {
3101 default:
3102 llvm_unreachable("Unknown loc info!");
3103 case CCValAssign::Full:
3104 break;
3105 case CCValAssign::BCvt:
3106 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3107 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003108 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003109 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003110 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003111 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3112 // nodes after our lowering.
3113 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003114 break;
3115 }
3116
3117 InVals.push_back(ArgValue);
3118
3119 } else { // VA.isRegLoc()
3120 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3121 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003122 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003123
3124 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003125 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3126 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003127 BEAlign = 8 - ArgSize;
3128
Matthias Braun941a7052016-07-28 18:40:00 +00003129 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003130
3131 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003132 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003133 SDValue ArgValue;
3134
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003135 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003136 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003137 MVT MemVT = VA.getValVT();
3138
Tim Northover47e003c2014-05-26 17:21:53 +00003139 switch (VA.getLocInfo()) {
3140 default:
3141 break;
Tim Northover6890add2014-06-03 13:54:53 +00003142 case CCValAssign::BCvt:
3143 MemVT = VA.getLocVT();
3144 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003145 case CCValAssign::SExt:
3146 ExtType = ISD::SEXTLOAD;
3147 break;
3148 case CCValAssign::ZExt:
3149 ExtType = ISD::ZEXTLOAD;
3150 break;
3151 case CCValAssign::AExt:
3152 ExtType = ISD::EXTLOAD;
3153 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003154 }
3155
Alex Lorenze40c8a22015-08-11 23:09:45 +00003156 ArgValue = DAG.getExtLoad(
3157 ExtType, DL, VA.getLocVT(), Chain, FIN,
3158 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003159 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003160
Tim Northover3b0846e2014-05-24 12:50:23 +00003161 InVals.push_back(ArgValue);
3162 }
3163 }
3164
3165 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003166 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003167 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003168 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003169 // The AAPCS variadic function ABI is identical to the non-variadic
3170 // one. As a result there may be more arguments in registers and we should
3171 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003172 // Win64 variadic functions also pass arguments in registers, but all float
3173 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003174 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3175 }
3176
Tim Northover3b0846e2014-05-24 12:50:23 +00003177 // This will point to the next argument passed via stack.
3178 unsigned StackOffset = CCInfo.getNextStackOffset();
3179 // We currently pass all varargs at 8-byte alignment.
3180 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003181 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003182
3183 if (MFI.hasMustTailInVarArgFunc()) {
3184 SmallVector<MVT, 2> RegParmTypes;
3185 RegParmTypes.push_back(MVT::i64);
3186 RegParmTypes.push_back(MVT::f128);
3187 // Compute the set of forwarded registers. The rest are scratch.
3188 SmallVectorImpl<ForwardedRegister> &Forwards =
3189 FuncInfo->getForwardedMustTailRegParms();
3190 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3191 CC_AArch64_AAPCS);
3192 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003193 }
3194
Tim Northover3b0846e2014-05-24 12:50:23 +00003195 unsigned StackArgSize = CCInfo.getNextStackOffset();
3196 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3197 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3198 // This is a non-standard ABI so by fiat I say we're allowed to make full
3199 // use of the stack area to be popped, which must be aligned to 16 bytes in
3200 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003201 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003202
3203 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3204 // a multiple of 16.
3205 FuncInfo->setArgumentStackToRestore(StackArgSize);
3206
3207 // This realignment carries over to the available bytes below. Our own
3208 // callers will guarantee the space is free by giving an aligned value to
3209 // CALLSEQ_START.
3210 }
3211 // Even if we're not expected to free up the space, it's useful to know how
3212 // much is there while considering tail calls (because we can reuse it).
3213 FuncInfo->setBytesInStackArgArea(StackArgSize);
3214
Tri Vo6c47c622018-09-22 22:17:50 +00003215 if (Subtarget->hasCustomCallingConv())
3216 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3217
Tim Northover3b0846e2014-05-24 12:50:23 +00003218 return Chain;
3219}
3220
3221void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003222 SelectionDAG &DAG,
3223 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003224 SDValue &Chain) const {
3225 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003226 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003227 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003228 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003229 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003230
3231 SmallVector<SDValue, 8> MemOps;
3232
3233 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3234 AArch64::X3, AArch64::X4, AArch64::X5,
3235 AArch64::X6, AArch64::X7 };
3236 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003237 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003238
3239 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3240 int GPRIdx = 0;
3241 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003242 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003243 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003244 if (GPRSaveSize & 15)
3245 // The extra size here, if triggered, will always be 8.
3246 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3247 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003248 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003249
Mehdi Amini44ede332015-07-09 02:09:04 +00003250 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003251
3252 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3253 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3254 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003255 SDValue Store = DAG.getStore(
3256 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003257 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003258 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3259 GPRIdx,
3260 (i - FirstVariadicGPR) * 8)
3261 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003262 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003263 FIN =
3264 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003265 }
3266 }
3267 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3268 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3269
Martin Storsjo2f24e932017-07-17 20:05:19 +00003270 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003271 static const MCPhysReg FPRArgRegs[] = {
3272 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3273 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3274 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003275 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003276
3277 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3278 int FPRIdx = 0;
3279 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003280 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003281
Mehdi Amini44ede332015-07-09 02:09:04 +00003282 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003283
3284 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3285 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3286 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3287
Alex Lorenze40c8a22015-08-11 23:09:45 +00003288 SDValue Store = DAG.getStore(
3289 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003290 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003291 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003292 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3293 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003294 }
3295 }
3296 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3297 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3298 }
3299
3300 if (!MemOps.empty()) {
3301 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3302 }
3303}
3304
3305/// LowerCallResult - Lower the result values of a call into the
3306/// appropriate copies out of appropriate physical registers.
3307SDValue AArch64TargetLowering::LowerCallResult(
3308 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003309 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3310 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003311 SDValue ThisVal) const {
3312 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3313 ? RetCC_AArch64_WebKit_JS
3314 : RetCC_AArch64_AAPCS;
3315 // Assign locations to each value returned by this call.
3316 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003317 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3318 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003319 CCInfo.AnalyzeCallResult(Ins, RetCC);
3320
3321 // Copy all of the result registers out of their specified physreg.
3322 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3323 CCValAssign VA = RVLocs[i];
3324
3325 // Pass 'this' value directly from the argument to return value, to avoid
3326 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003327 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003328 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3329 "unexpected return calling convention register assignment");
3330 InVals.push_back(ThisVal);
3331 continue;
3332 }
3333
3334 SDValue Val =
3335 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3336 Chain = Val.getValue(1);
3337 InFlag = Val.getValue(2);
3338
3339 switch (VA.getLocInfo()) {
3340 default:
3341 llvm_unreachable("Unknown loc info!");
3342 case CCValAssign::Full:
3343 break;
3344 case CCValAssign::BCvt:
3345 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3346 break;
3347 }
3348
3349 InVals.push_back(Val);
3350 }
3351
3352 return Chain;
3353}
3354
Matthias Braun1af14142016-09-13 19:27:38 +00003355/// Return true if the calling convention is one that we can guarantee TCO for.
3356static bool canGuaranteeTCO(CallingConv::ID CC) {
3357 return CC == CallingConv::Fast;
3358}
3359
3360/// Return true if we might ever do TCO for calls with this calling convention.
3361static bool mayTailCallThisCC(CallingConv::ID CC) {
3362 switch (CC) {
3363 case CallingConv::C:
3364 case CallingConv::PreserveMost:
3365 case CallingConv::Swift:
3366 return true;
3367 default:
3368 return canGuaranteeTCO(CC);
3369 }
3370}
3371
Tim Northover3b0846e2014-05-24 12:50:23 +00003372bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3373 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003374 const SmallVectorImpl<ISD::OutputArg> &Outs,
3375 const SmallVectorImpl<SDValue> &OutVals,
3376 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003377 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003378 return false;
3379
Matthias Braun8d414362016-03-30 22:46:04 +00003380 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003381 const Function &CallerF = MF.getFunction();
3382 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003383 bool CCMatch = CallerCC == CalleeCC;
3384
3385 // Byval parameters hand the function a pointer directly into the stack area
3386 // we want to reuse during a tail call. Working around this *is* possible (see
3387 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003388 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3389 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003390 i != e; ++i)
3391 if (i->hasByValAttr())
3392 return false;
3393
Matthias Braun1af14142016-09-13 19:27:38 +00003394 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3395 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003396
Oliver Stannard12993dd2014-08-18 12:42:15 +00003397 // Externally-defined functions with weak linkage should not be
3398 // tail-called on AArch64 when the OS does not support dynamic
3399 // pre-emption of symbols, as the AAELF spec requires normal calls
3400 // to undefined weak functions to be replaced with a NOP or jump to the
3401 // next instruction. The behaviour of branch instructions in this
3402 // situation (as used for tail calls) is implementation-defined, so we
3403 // cannot rely on the linker replacing the tail call with a return.
3404 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3405 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003406 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003407 if (GV->hasExternalWeakLinkage() &&
3408 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003409 return false;
3410 }
3411
Tim Northover3b0846e2014-05-24 12:50:23 +00003412 // Now we search for cases where we can use a tail call without changing the
3413 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3414 // concept.
3415
3416 // I want anyone implementing a new calling convention to think long and hard
3417 // about this assert.
3418 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3419 "Unexpected variadic calling convention");
3420
Matthias Braun8d414362016-03-30 22:46:04 +00003421 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003422 if (isVarArg && !Outs.empty()) {
3423 // At least two cases here: if caller is fastcc then we can't have any
3424 // memory arguments (we'd be expected to clean up the stack afterwards). If
3425 // caller is C then we could potentially use its argument area.
3426
3427 // FIXME: for now we take the most conservative of these in both cases:
3428 // disallow all variadic memory operands.
3429 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003430 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003431
3432 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003433 for (const CCValAssign &ArgLoc : ArgLocs)
3434 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003435 return false;
3436 }
3437
Matthias Braun8d414362016-03-30 22:46:04 +00003438 // Check that the call results are passed in the same way.
3439 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3440 CCAssignFnForCall(CalleeCC, isVarArg),
3441 CCAssignFnForCall(CallerCC, isVarArg)))
3442 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003443 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003444 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3445 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003446 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003447 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003448 if (Subtarget->hasCustomCallingConv()) {
3449 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3450 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3451 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003452 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003453 return false;
3454 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003455
3456 // Nothing more to check if the callee is taking no arguments
3457 if (Outs.empty())
3458 return true;
3459
3460 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003461 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003462
3463 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3464
3465 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3466
Matthias Braun74a0bd32016-04-13 21:43:16 +00003467 // If the stack arguments for this call do not fit into our own save area then
3468 // the call cannot be made tail.
3469 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3470 return false;
3471
Matthias Braun46b0f032016-04-14 01:10:42 +00003472 const MachineRegisterInfo &MRI = MF.getRegInfo();
3473 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3474 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003475
3476 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003477}
3478
3479SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3480 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003481 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003482 int ClobberedFI) const {
3483 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003484 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3485 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003486
3487 // Include the original chain at the beginning of the list. When this is
3488 // used by target LowerCall hooks, this helps legalize find the
3489 // CALLSEQ_BEGIN node.
3490 ArgChains.push_back(Chain);
3491
3492 // Add a chain value for each stack argument corresponding
3493 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3494 UE = DAG.getEntryNode().getNode()->use_end();
3495 U != UE; ++U)
3496 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3497 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3498 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003499 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003500 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003501 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003502
3503 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3504 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3505 ArgChains.push_back(SDValue(L, 1));
3506 }
3507
3508 // Build a tokenfactor for all the chains.
3509 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3510}
3511
3512bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3513 bool TailCallOpt) const {
3514 return CallCC == CallingConv::Fast && TailCallOpt;
3515}
3516
Tim Northover3b0846e2014-05-24 12:50:23 +00003517/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3518/// and add input and output parameter nodes.
3519SDValue
3520AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3521 SmallVectorImpl<SDValue> &InVals) const {
3522 SelectionDAG &DAG = CLI.DAG;
3523 SDLoc &DL = CLI.DL;
3524 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3525 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3526 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3527 SDValue Chain = CLI.Chain;
3528 SDValue Callee = CLI.Callee;
3529 bool &IsTailCall = CLI.IsTailCall;
3530 CallingConv::ID CallConv = CLI.CallConv;
3531 bool IsVarArg = CLI.IsVarArg;
3532
3533 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003534 bool IsThisReturn = false;
3535
3536 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3537 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3538 bool IsSibCall = false;
3539
3540 if (IsTailCall) {
3541 // Check if it's really possible to do a tail call.
3542 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003543 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003544 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003545 report_fatal_error("failed to perform tail call elimination on a call "
3546 "site marked musttail");
3547
3548 // A sibling call is one where we're under the usual C ABI and not planning
3549 // to change that but can still do a tail call:
3550 if (!TailCallOpt && IsTailCall)
3551 IsSibCall = true;
3552
3553 if (IsTailCall)
3554 ++NumTailCalls;
3555 }
3556
3557 // Analyze operands of the call, assigning locations to each operand.
3558 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003559 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3560 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003561
3562 if (IsVarArg) {
3563 // Handle fixed and variable vector arguments differently.
3564 // Variable vector arguments always go into memory.
3565 unsigned NumArgs = Outs.size();
3566
3567 for (unsigned i = 0; i != NumArgs; ++i) {
3568 MVT ArgVT = Outs[i].VT;
3569 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3570 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3571 /*IsVarArg=*/ !Outs[i].IsFixed);
3572 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3573 assert(!Res && "Call operand has unhandled type");
3574 (void)Res;
3575 }
3576 } else {
3577 // At this point, Outs[].VT may already be promoted to i32. To correctly
3578 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3579 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3580 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3581 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3582 // LocVT.
3583 unsigned NumArgs = Outs.size();
3584 for (unsigned i = 0; i != NumArgs; ++i) {
3585 MVT ValVT = Outs[i].VT;
3586 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003587 EVT ActualVT = getValueType(DAG.getDataLayout(),
3588 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003589 /*AllowUnknown*/ true);
3590 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3591 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3592 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003593 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003594 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003595 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003596 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003597
3598 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003599 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003600 assert(!Res && "Call operand has unhandled type");
3601 (void)Res;
3602 }
3603 }
3604
3605 // Get a count of how many bytes are to be pushed on the stack.
3606 unsigned NumBytes = CCInfo.getNextStackOffset();
3607
3608 if (IsSibCall) {
3609 // Since we're not changing the ABI to make this a tail call, the memory
3610 // operands are already available in the caller's incoming argument space.
3611 NumBytes = 0;
3612 }
3613
3614 // FPDiff is the byte offset of the call's argument area from the callee's.
3615 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3616 // by this amount for a tail call. In a sibling call it must be 0 because the
3617 // caller will deallocate the entire stack and the callee still expects its
3618 // arguments to begin at SP+0. Completely unused for non-tail calls.
3619 int FPDiff = 0;
3620
3621 if (IsTailCall && !IsSibCall) {
3622 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3623
3624 // Since callee will pop argument stack as a tail call, we must keep the
3625 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003626 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003627
3628 // FPDiff will be negative if this tail call requires more space than we
3629 // would automatically have in our incoming argument space. Positive if we
3630 // can actually shrink the stack.
3631 FPDiff = NumReusableBytes - NumBytes;
3632
3633 // The stack pointer must be 16-byte aligned at all times it's used for a
3634 // memory operation, which in practice means at *all* times and in
3635 // particular across call boundaries. Therefore our own arguments started at
3636 // a 16-byte aligned SP and the delta applied for the tail call should
3637 // satisfy the same constraint.
3638 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3639 }
3640
3641 // Adjust the stack pointer for the new arguments...
3642 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003643 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003644 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003645
Mehdi Amini44ede332015-07-09 02:09:04 +00003646 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3647 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003648
3649 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3650 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003651 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003652
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003653 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3654 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3655 for (const auto &F : Forwards) {
3656 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3657 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3658 }
3659 }
3660
Tim Northover3b0846e2014-05-24 12:50:23 +00003661 // Walk the register/memloc assignments, inserting copies/loads.
3662 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3663 ++i, ++realArgIdx) {
3664 CCValAssign &VA = ArgLocs[i];
3665 SDValue Arg = OutVals[realArgIdx];
3666 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3667
3668 // Promote the value if needed.
3669 switch (VA.getLocInfo()) {
3670 default:
3671 llvm_unreachable("Unknown loc info!");
3672 case CCValAssign::Full:
3673 break;
3674 case CCValAssign::SExt:
3675 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3676 break;
3677 case CCValAssign::ZExt:
3678 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3679 break;
3680 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003681 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3682 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3683 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3684 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3685 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003686 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3687 break;
3688 case CCValAssign::BCvt:
3689 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3690 break;
3691 case CCValAssign::FPExt:
3692 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3693 break;
3694 }
3695
3696 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003697 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3698 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003699 assert(VA.getLocVT() == MVT::i64 &&
3700 "unexpected calling convention register assignment");
3701 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3702 "unexpected use of 'returned'");
3703 IsThisReturn = true;
3704 }
3705 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3706 } else {
3707 assert(VA.isMemLoc());
3708
3709 SDValue DstAddr;
3710 MachinePointerInfo DstInfo;
3711
3712 // FIXME: This works on big-endian for composite byvals, which are the
3713 // common case. It should also work for fundamental types too.
3714 uint32_t BEAlign = 0;
3715 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003716 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003717 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003718 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3719 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003720 if (OpSize < 8)
3721 BEAlign = 8 - OpSize;
3722 }
3723 unsigned LocMemOffset = VA.getLocMemOffset();
3724 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003725 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003726 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003727
3728 if (IsTailCall) {
3729 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003730 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003731
Mehdi Amini44ede332015-07-09 02:09:04 +00003732 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003733 DstInfo =
3734 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003735
3736 // Make sure any stack arguments overlapping with where we're storing
3737 // are loaded before this eventual operation. Otherwise they'll be
3738 // clobbered.
3739 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3740 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003741 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003742
Mehdi Amini44ede332015-07-09 02:09:04 +00003743 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003744 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3745 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003746 }
3747
3748 if (Outs[i].Flags.isByVal()) {
3749 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003750 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003751 SDValue Cpy = DAG.getMemcpy(
3752 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003753 /*isVol = */ false, /*AlwaysInline = */ false,
3754 /*isTailCall = */ false,
3755 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003756
3757 MemOpChains.push_back(Cpy);
3758 } else {
3759 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3760 // promoted to a legal register type i32, we should truncate Arg back to
3761 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003762 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3763 VA.getValVT() == MVT::i16)
3764 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003765
Justin Lebar9c375812016-07-15 18:27:10 +00003766 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003767 MemOpChains.push_back(Store);
3768 }
3769 }
3770 }
3771
3772 if (!MemOpChains.empty())
3773 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3774
3775 // Build a sequence of copy-to-reg nodes chained together with token chain
3776 // and flag operands which copy the outgoing args into the appropriate regs.
3777 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003778 for (auto &RegToPass : RegsToPass) {
3779 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3780 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003781 InFlag = Chain.getValue(1);
3782 }
3783
3784 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3785 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3786 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003787 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3788 auto GV = G->getGlobal();
3789 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3790 AArch64II::MO_GOT) {
3791 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3792 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003793 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3794 assert(Subtarget->isTargetWindows() &&
3795 "Windows is the only supported COFF target");
3796 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003797 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003798 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003799 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3800 }
3801 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3802 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3803 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003804 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003805 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3806 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003807 } else {
3808 const char *Sym = S->getSymbol();
3809 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003810 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003811 }
3812
3813 // We don't usually want to end the call-sequence here because we would tidy
3814 // the frame up *after* the call, however in the ABI-changing tail-call case
3815 // we've carefully laid out the parameters so that when sp is reset they'll be
3816 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003817 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003818 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3819 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003820 InFlag = Chain.getValue(1);
3821 }
3822
3823 std::vector<SDValue> Ops;
3824 Ops.push_back(Chain);
3825 Ops.push_back(Callee);
3826
3827 if (IsTailCall) {
3828 // Each tail call may have to adjust the stack by a different amount, so
3829 // this information must travel along with the operation for eventual
3830 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003831 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003832 }
3833
3834 // Add argument registers to the end of the list so that they are known live
3835 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003836 for (auto &RegToPass : RegsToPass)
3837 Ops.push_back(DAG.getRegister(RegToPass.first,
3838 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003839
3840 // Add a register mask operand representing the call-preserved registers.
3841 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003842 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003843 if (IsThisReturn) {
3844 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003845 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003846 if (!Mask) {
3847 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003848 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003849 }
3850 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003851 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003852
Tri Vo6c47c622018-09-22 22:17:50 +00003853 if (Subtarget->hasCustomCallingConv())
3854 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3855
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003856 if (TRI->isAnyArgRegReserved(MF))
3857 TRI->emitReservedArgRegCallError(MF);
3858
Tim Northover3b0846e2014-05-24 12:50:23 +00003859 assert(Mask && "Missing call preserved mask for calling convention");
3860 Ops.push_back(DAG.getRegisterMask(Mask));
3861
3862 if (InFlag.getNode())
3863 Ops.push_back(InFlag);
3864
3865 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3866
3867 // If we're doing a tall call, use a TC_RETURN here rather than an
3868 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003869 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003870 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003871 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003872 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003873
3874 // Returns a chain and a flag for retval copy to use.
3875 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3876 InFlag = Chain.getValue(1);
3877
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003878 uint64_t CalleePopBytes =
3879 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003880
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003881 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3882 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3883 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003884 if (!Ins.empty())
3885 InFlag = Chain.getValue(1);
3886
3887 // Handle result values, copying them out of physregs into vregs that we
3888 // return.
3889 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3890 InVals, IsThisReturn,
3891 IsThisReturn ? OutVals[0] : SDValue());
3892}
3893
3894bool AArch64TargetLowering::CanLowerReturn(
3895 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3896 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3897 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3898 ? RetCC_AArch64_WebKit_JS
3899 : RetCC_AArch64_AAPCS;
3900 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003901 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003902 return CCInfo.CheckReturn(Outs, RetCC);
3903}
3904
3905SDValue
3906AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3907 bool isVarArg,
3908 const SmallVectorImpl<ISD::OutputArg> &Outs,
3909 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003910 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003911 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3912 ? RetCC_AArch64_WebKit_JS
3913 : RetCC_AArch64_AAPCS;
3914 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003915 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3916 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003917 CCInfo.AnalyzeReturn(Outs, RetCC);
3918
3919 // Copy the result values into the output registers.
3920 SDValue Flag;
3921 SmallVector<SDValue, 4> RetOps(1, Chain);
3922 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3923 ++i, ++realRVLocIdx) {
3924 CCValAssign &VA = RVLocs[i];
3925 assert(VA.isRegLoc() && "Can only return in registers!");
3926 SDValue Arg = OutVals[realRVLocIdx];
3927
3928 switch (VA.getLocInfo()) {
3929 default:
3930 llvm_unreachable("Unknown loc info!");
3931 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003932 if (Outs[i].ArgVT == MVT::i1) {
3933 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3934 // value. This is strictly redundant on Darwin (which uses "zeroext
3935 // i1"), but will be optimised out before ISel.
3936 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3937 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3938 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003939 break;
3940 case CCValAssign::BCvt:
3941 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3942 break;
3943 }
3944
3945 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3946 Flag = Chain.getValue(1);
3947 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3948 }
Manman Rencbe4f942015-12-16 21:04:19 +00003949 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3950 const MCPhysReg *I =
3951 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3952 if (I) {
3953 for (; *I; ++I) {
3954 if (AArch64::GPR64RegClass.contains(*I))
3955 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3956 else if (AArch64::FPR64RegClass.contains(*I))
3957 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3958 else
3959 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3960 }
3961 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003962
3963 RetOps[0] = Chain; // Update chain.
3964
3965 // Add the flag if we have it.
3966 if (Flag.getNode())
3967 RetOps.push_back(Flag);
3968
3969 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3970}
3971
3972//===----------------------------------------------------------------------===//
3973// Other Lowering Code
3974//===----------------------------------------------------------------------===//
3975
Joel Jonesa7c4a522017-04-21 17:31:03 +00003976SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3977 SelectionDAG &DAG,
3978 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003979 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3980 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003981}
3982
3983SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3984 SelectionDAG &DAG,
3985 unsigned Flag) const {
3986 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3987}
3988
3989SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3990 SelectionDAG &DAG,
3991 unsigned Flag) const {
3992 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3993 N->getOffset(), Flag);
3994}
3995
3996SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3997 SelectionDAG &DAG,
3998 unsigned Flag) const {
3999 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4000}
4001
4002// (loadGOT sym)
4003template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004004SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4005 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004006 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004007 SDLoc DL(N);
4008 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004009 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004010 // FIXME: Once remat is capable of dealing with instructions with register
4011 // operands, expand this into two nodes instead of using a wrapper node.
4012 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4013}
4014
4015// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4016template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004017SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4018 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004019 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004020 SDLoc DL(N);
4021 EVT Ty = getPointerTy(DAG.getDataLayout());
4022 const unsigned char MO_NC = AArch64II::MO_NC;
4023 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004024 AArch64ISD::WrapperLarge, DL, Ty,
4025 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4026 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4027 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4028 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004029}
4030
4031// (addlow (adrp %hi(sym)) %lo(sym))
4032template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004033SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4034 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004035 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004036 SDLoc DL(N);
4037 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004038 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004039 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004040 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004041 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4042 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4043}
4044
David Green9dd1d452018-08-22 11:31:39 +00004045// (adr sym)
4046template <class NodeTy>
4047SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4048 unsigned Flags) const {
4049 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4050 SDLoc DL(N);
4051 EVT Ty = getPointerTy(DAG.getDataLayout());
4052 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4053 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4054}
4055
Tim Northover3b0846e2014-05-24 12:50:23 +00004056SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4057 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004058 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004059 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00004060 unsigned char OpFlags =
4061 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004062
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004063 if (OpFlags != AArch64II::MO_NO_FLAG)
4064 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4065 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004066
David Green9dd1d452018-08-22 11:31:39 +00004067 // This also catches the large code model case for Darwin, and tiny code
4068 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004069 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004070 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004071 }
4072
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004073 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004074 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004075 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004076 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004077 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004078 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004079 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004080 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004081 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4082 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004083 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004084 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4085 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4086 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004087}
4088
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004089/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004090/// and calls to compute the variable's address (for Darwin, currently) and
4091/// return an SDValue containing the final node.
4092
4093/// Darwin only has one TLS scheme which must be capable of dealing with the
4094/// fully general situation, in the worst case. This means:
4095/// + "extern __thread" declaration.
4096/// + Defined in a possibly unknown dynamic library.
4097///
4098/// The general system is that each __thread variable has a [3 x i64] descriptor
4099/// which contains information used by the runtime to calculate the address. The
4100/// only part of this the compiler needs to know about is the first xword, which
4101/// contains a function pointer that must be called with the address of the
4102/// entire descriptor in "x0".
4103///
4104/// Since this descriptor may be in a different unit, in general even the
4105/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4106/// is:
4107/// adrp x0, _var@TLVPPAGE
4108/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4109/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4110/// ; the function pointer
4111/// blr x1 ; Uses descriptor address in x0
4112/// ; Address of _var is now in x0.
4113///
4114/// If the address of _var's descriptor *is* known to the linker, then it can
4115/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4116/// a slight efficiency gain.
4117SDValue
4118AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4119 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004120 assert(Subtarget->isTargetDarwin() &&
4121 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004122
4123 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004124 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004125 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4126
4127 SDValue TLVPAddr =
4128 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4129 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4130
4131 // The first entry in the descriptor is a function pointer that we must call
4132 // to obtain the address of the variable.
4133 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004134 SDValue FuncTLVGet = DAG.getLoad(
4135 MVT::i64, DL, Chain, DescAddr,
4136 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4137 /* Alignment = */ 8,
4138 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4139 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004140 Chain = FuncTLVGet.getValue(1);
4141
Matthias Braun941a7052016-07-28 18:40:00 +00004142 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4143 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004144
4145 // TLS calls preserve all registers except those that absolutely must be
4146 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4147 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004148 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4149 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4150 if (Subtarget->hasCustomCallingConv())
4151 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004152
4153 // Finally, we can make the call. This is just a degenerate version of a
4154 // normal AArch64 call node: x0 takes the address of the descriptor, and
4155 // returns the address of the variable in this thread.
4156 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4157 Chain =
4158 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4159 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4160 DAG.getRegisterMask(Mask), Chain.getValue(1));
4161 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4162}
4163
4164/// When accessing thread-local variables under either the general-dynamic or
4165/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4166/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004167/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004168///
Kristof Beylsaea84612015-03-04 09:12:08 +00004169/// The sequence is:
4170/// adrp x0, :tlsdesc:var
4171/// ldr x1, [x0, #:tlsdesc_lo12:var]
4172/// add x0, x0, #:tlsdesc_lo12:var
4173/// .tlsdesccall var
4174/// blr x1
4175/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004176///
Kristof Beylsaea84612015-03-04 09:12:08 +00004177/// The above sequence must be produced unscheduled, to enable the linker to
4178/// optimize/relax this sequence.
4179/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4180/// above sequence, and expanded really late in the compilation flow, to ensure
4181/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004182SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4183 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004184 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004185 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004186
Kristof Beylsaea84612015-03-04 09:12:08 +00004187 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004188 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004189
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004190 Chain =
4191 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004192 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004193
4194 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4195}
4196
4197SDValue
4198AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4199 SelectionDAG &DAG) const {
4200 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004201 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4202 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004203 // Different choices can be made for the maximum size of the TLS area for a
4204 // module. For the small address model, the default TLS size is 16MiB and the
4205 // maximum TLS size is 4GiB.
4206 // FIXME: add -mtls-size command line option and make it control the 16MiB
4207 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004208 // FIXME: add tiny codemodel support. We currently generate the same code as
4209 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004210 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4211
4212 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004213
Kristof Beylsaea84612015-03-04 09:12:08 +00004214 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4215 if (Model == TLSModel::LocalDynamic)
4216 Model = TLSModel::GeneralDynamic;
4217 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004218
4219 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004220 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004221 SDLoc DL(Op);
4222 const GlobalValue *GV = GA->getGlobal();
4223
4224 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4225
4226 if (Model == TLSModel::LocalExec) {
4227 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004228 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004229 SDValue LoVar = DAG.getTargetGlobalAddress(
4230 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004231 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004232
Kristof Beylsaea84612015-03-04 09:12:08 +00004233 SDValue TPWithOff_lo =
4234 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004235 HiVar,
4236 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004237 0);
4238 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004239 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4240 LoVar,
4241 DAG.getTargetConstant(0, DL, MVT::i32)),
4242 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004243 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004244 } else if (Model == TLSModel::InitialExec) {
4245 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4246 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4247 } else if (Model == TLSModel::LocalDynamic) {
4248 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4249 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4250 // the beginning of the module's TLS region, followed by a DTPREL offset
4251 // calculation.
4252
4253 // These accesses will need deduplicating if there's more than one.
4254 AArch64FunctionInfo *MFI =
4255 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4256 MFI->incNumLocalDynamicTLSAccesses();
4257
Tim Northover3b0846e2014-05-24 12:50:23 +00004258 // The call needs a relocation too for linker relaxation. It doesn't make
4259 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4260 // the address.
4261 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4262 AArch64II::MO_TLS);
4263
4264 // Now we can calculate the offset from TPIDR_EL0 to this module's
4265 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004266 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004267
4268 // Now use :dtprel_whatever: operations to calculate this variable's offset
4269 // in its thread-storage area.
4270 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004271 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004272 SDValue LoVar = DAG.getTargetGlobalAddress(
4273 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004274 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4275
Kristof Beylsaea84612015-03-04 09:12:08 +00004276 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004277 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004278 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004279 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4280 DAG.getTargetConstant(0, DL, MVT::i32)),
4281 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004282 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004283 // The call needs a relocation too for linker relaxation. It doesn't make
4284 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4285 // the address.
4286 SDValue SymAddr =
4287 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4288
4289 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004290 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004291 } else
4292 llvm_unreachable("Unsupported ELF TLS access model");
4293
4294 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4295}
4296
Martin Storsjocc240962018-03-10 19:05:21 +00004297SDValue
4298AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4299 SelectionDAG &DAG) const {
4300 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4301
4302 SDValue Chain = DAG.getEntryNode();
4303 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4304 SDLoc DL(Op);
4305
4306 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4307
4308 // Load the ThreadLocalStoragePointer from the TEB
4309 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4310 SDValue TLSArray =
4311 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4312 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4313 Chain = TLSArray.getValue(1);
4314
4315 // Load the TLS index from the C runtime;
4316 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4317 // This also does the same as LOADgot, but using a generic i32 load,
4318 // while LOADgot only loads i64.
4319 SDValue TLSIndexHi =
4320 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4321 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4322 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4323 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4324 SDValue TLSIndex =
4325 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4326 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4327 Chain = TLSIndex.getValue(1);
4328
4329 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4330 // offset into the TLSArray.
4331 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4332 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4333 DAG.getConstant(3, DL, PtrVT));
4334 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4335 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4336 MachinePointerInfo());
4337 Chain = TLS.getValue(1);
4338
4339 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4340 const GlobalValue *GV = GA->getGlobal();
4341 SDValue TGAHi = DAG.getTargetGlobalAddress(
4342 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4343 SDValue TGALo = DAG.getTargetGlobalAddress(
4344 GV, DL, PtrVT, 0,
4345 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4346
4347 // Add the offset from the start of the .tls section (section base).
4348 SDValue Addr =
4349 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4350 DAG.getTargetConstant(0, DL, MVT::i32)),
4351 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004352 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004353 return Addr;
4354}
4355
Tim Northover3b0846e2014-05-24 12:50:23 +00004356SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4357 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004358 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004359 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004360 return LowerToTLSEmulatedModel(GA, DAG);
4361
Tim Northover3b0846e2014-05-24 12:50:23 +00004362 if (Subtarget->isTargetDarwin())
4363 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004364 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004365 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004366 if (Subtarget->isTargetWindows())
4367 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004368
4369 llvm_unreachable("Unexpected platform trying to use TLS");
4370}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004371
Tim Northover3b0846e2014-05-24 12:50:23 +00004372SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4373 SDValue Chain = Op.getOperand(0);
4374 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4375 SDValue LHS = Op.getOperand(2);
4376 SDValue RHS = Op.getOperand(3);
4377 SDValue Dest = Op.getOperand(4);
4378 SDLoc dl(Op);
4379
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004380 MachineFunction &MF = DAG.getMachineFunction();
4381 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4382 // will not be produced, as they are conditional branch instructions that do
4383 // not set flags.
4384 bool ProduceNonFlagSettingCondBr =
4385 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4386
Tim Northover3b0846e2014-05-24 12:50:23 +00004387 // Handle f128 first, since lowering it will result in comparing the return
4388 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4389 // is expecting to deal with.
4390 if (LHS.getValueType() == MVT::f128) {
4391 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4392
4393 // If softenSetCCOperands returned a scalar, we need to compare the result
4394 // against zero to select between true and false values.
4395 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004396 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004397 CC = ISD::SETNE;
4398 }
4399 }
4400
4401 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4402 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004403 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4404 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004405 // Only lower legal XALUO ops.
4406 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4407 return SDValue();
4408
4409 // The actual operation with overflow check.
4410 AArch64CC::CondCode OFCC;
4411 SDValue Value, Overflow;
4412 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4413
4414 if (CC == ISD::SETNE)
4415 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004416 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004417
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004418 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4419 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004420 }
4421
4422 if (LHS.getValueType().isInteger()) {
4423 assert((LHS.getValueType() == RHS.getValueType()) &&
4424 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4425
4426 // If the RHS of the comparison is zero, we can potentially fold this
4427 // to a specialized branch.
4428 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004429 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004430 if (CC == ISD::SETEQ) {
4431 // See if we can use a TBZ to fold in an AND as well.
4432 // TBZ has a smaller branch displacement than CBZ. If the offset is
4433 // out of bounds, a late MI-layer pass rewrites branches.
4434 // 403.gcc is an example that hits this case.
4435 if (LHS.getOpcode() == ISD::AND &&
4436 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4437 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4438 SDValue Test = LHS.getOperand(0);
4439 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004440 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004441 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4442 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004443 }
4444
4445 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4446 } else if (CC == ISD::SETNE) {
4447 // See if we can use a TBZ to fold in an AND as well.
4448 // TBZ has a smaller branch displacement than CBZ. If the offset is
4449 // out of bounds, a late MI-layer pass rewrites branches.
4450 // 403.gcc is an example that hits this case.
4451 if (LHS.getOpcode() == ISD::AND &&
4452 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4453 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4454 SDValue Test = LHS.getOperand(0);
4455 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004456 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004457 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4458 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004459 }
4460
4461 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004462 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4463 // Don't combine AND since emitComparison converts the AND to an ANDS
4464 // (a.k.a. TST) and the test in the test bit and branch instruction
4465 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004466 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004467 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004468 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004469 }
4470 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004471 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004472 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004473 // Don't combine AND since emitComparison converts the AND to an ANDS
4474 // (a.k.a. TST) and the test in the test bit and branch instruction
4475 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004476 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004477 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004478 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004479 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004480
4481 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004482 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004483 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4484 Cmp);
4485 }
4486
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004487 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4488 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004489
4490 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4491 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004492 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004493 AArch64CC::CondCode CC1, CC2;
4494 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004495 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004496 SDValue BR1 =
4497 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4498 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004499 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004500 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4501 Cmp);
4502 }
4503
4504 return BR1;
4505}
4506
4507SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4508 SelectionDAG &DAG) const {
4509 EVT VT = Op.getValueType();
4510 SDLoc DL(Op);
4511
4512 SDValue In1 = Op.getOperand(0);
4513 SDValue In2 = Op.getOperand(1);
4514 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004515
4516 if (SrcVT.bitsLT(VT))
4517 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4518 else if (SrcVT.bitsGT(VT))
4519 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004520
4521 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004522 uint64_t EltMask;
4523 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004524
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004525 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004526 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004527 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004528 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004529 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004530 DAG.getUNDEF(VecVT), In2);
4531 } else {
4532 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4533 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4534 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004535 };
4536
4537 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4538 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4539 EltMask = 0x80000000ULL;
4540 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004541 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004542 VecVT = MVT::v2i64;
4543
Eric Christopher572e03a2015-06-19 01:53:21 +00004544 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004545 // immediate moves cannot materialize that in a single instruction for
4546 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004547 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004548
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004549 setVecVal(AArch64::dsub);
4550 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4551 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4552 EltMask = 0x8000ULL;
4553 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004554 } else {
4555 llvm_unreachable("Invalid type for copysign!");
4556 }
4557
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004558 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004559
4560 // If we couldn't materialize the mask above, then the mask vector will be
4561 // the zero vector, and we need to negate it here.
4562 if (VT == MVT::f64 || VT == MVT::v2f64) {
4563 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4564 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4565 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4566 }
4567
4568 SDValue Sel =
4569 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4570
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004571 if (VT == MVT::f16)
4572 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004573 if (VT == MVT::f32)
4574 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4575 else if (VT == MVT::f64)
4576 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4577 else
4578 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4579}
4580
4581SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004582 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004583 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004584 return SDValue();
4585
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004586 if (!Subtarget->hasNEON())
4587 return SDValue();
4588
Tim Northover3b0846e2014-05-24 12:50:23 +00004589 // While there is no integer popcount instruction, it can
4590 // be more efficiently lowered to the following sequence that uses
4591 // AdvSIMD registers/instructions as long as the copies to/from
4592 // the AdvSIMD registers are cheap.
4593 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4594 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4595 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4596 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4597 SDValue Val = Op.getOperand(0);
4598 SDLoc DL(Op);
4599 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004600
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004601 if (VT == MVT::i32 || VT == MVT::i64) {
4602 if (VT == MVT::i32)
4603 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4604 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004605
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004606 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4607 SDValue UaddLV = DAG.getNode(
4608 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4609 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004610
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004611 if (VT == MVT::i64)
4612 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4613 return UaddLV;
4614 }
4615
4616 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4617 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4618 "Unexpected type for custom ctpop lowering");
4619
4620 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4621 Val = DAG.getBitcast(VT8Bit, Val);
4622 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4623
4624 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4625 unsigned EltSize = 8;
4626 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4627 while (EltSize != VT.getScalarSizeInBits()) {
4628 EltSize *= 2;
4629 NumElts /= 2;
4630 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4631 Val = DAG.getNode(
4632 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4633 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4634 }
4635
4636 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004637}
4638
4639SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4640
4641 if (Op.getValueType().isVector())
4642 return LowerVSETCC(Op, DAG);
4643
4644 SDValue LHS = Op.getOperand(0);
4645 SDValue RHS = Op.getOperand(1);
4646 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4647 SDLoc dl(Op);
4648
4649 // We chose ZeroOrOneBooleanContents, so use zero and one.
4650 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004651 SDValue TVal = DAG.getConstant(1, dl, VT);
4652 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004653
4654 // Handle f128 first, since one possible outcome is a normal integer
4655 // comparison which gets picked up by the next if statement.
4656 if (LHS.getValueType() == MVT::f128) {
4657 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4658
4659 // If softenSetCCOperands returned a scalar, use it.
4660 if (!RHS.getNode()) {
4661 assert(LHS.getValueType() == Op.getValueType() &&
4662 "Unexpected setcc expansion!");
4663 return LHS;
4664 }
4665 }
4666
4667 if (LHS.getValueType().isInteger()) {
4668 SDValue CCVal;
4669 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004670 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004671
4672 // Note that we inverted the condition above, so we reverse the order of
4673 // the true and false operands here. This will allow the setcc to be
4674 // matched to a single CSINC instruction.
4675 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4676 }
4677
4678 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004679 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4680 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004681
4682 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4683 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004684 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004685
4686 AArch64CC::CondCode CC1, CC2;
4687 changeFPCCToAArch64CC(CC, CC1, CC2);
4688 if (CC2 == AArch64CC::AL) {
4689 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004690 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004691
4692 // Note that we inverted the condition above, so we reverse the order of
4693 // the true and false operands here. This will allow the setcc to be
4694 // matched to a single CSINC instruction.
4695 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4696 } else {
4697 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4698 // totally clean. Some of them require two CSELs to implement. As is in
4699 // this case, we emit the first CSEL and then emit a second using the output
4700 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4701
4702 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004703 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004704 SDValue CS1 =
4705 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4706
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004707 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004708 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4709 }
4710}
4711
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004712SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4713 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004714 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004715 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004716 // Handle f128 first, because it will result in a comparison of some RTLIB
4717 // call result against zero.
4718 if (LHS.getValueType() == MVT::f128) {
4719 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4720
4721 // If softenSetCCOperands returned a scalar, we need to compare the result
4722 // against zero to select between true and false values.
4723 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004724 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004725 CC = ISD::SETNE;
4726 }
4727 }
4728
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004729 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004730 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004731 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4732 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4733 }
4734
4735 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004736 if (LHS.getValueType().isInteger()) {
4737 assert((LHS.getValueType() == RHS.getValueType()) &&
4738 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4739
4740 unsigned Opcode = AArch64ISD::CSEL;
4741
4742 // If both the TVal and the FVal are constants, see if we can swap them in
4743 // order to for a CSINV or CSINC out of them.
4744 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4745 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4746
4747 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4748 std::swap(TVal, FVal);
4749 std::swap(CTVal, CFVal);
4750 CC = ISD::getSetCCInverse(CC, true);
4751 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4752 std::swap(TVal, FVal);
4753 std::swap(CTVal, CFVal);
4754 CC = ISD::getSetCCInverse(CC, true);
4755 } else if (TVal.getOpcode() == ISD::XOR) {
4756 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4757 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004758 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004759 std::swap(TVal, FVal);
4760 std::swap(CTVal, CFVal);
4761 CC = ISD::getSetCCInverse(CC, true);
4762 }
4763 } else if (TVal.getOpcode() == ISD::SUB) {
4764 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4765 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004766 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004767 std::swap(TVal, FVal);
4768 std::swap(CTVal, CFVal);
4769 CC = ISD::getSetCCInverse(CC, true);
4770 }
4771 } else if (CTVal && CFVal) {
4772 const int64_t TrueVal = CTVal->getSExtValue();
4773 const int64_t FalseVal = CFVal->getSExtValue();
4774 bool Swap = false;
4775
4776 // If both TVal and FVal are constants, see if FVal is the
4777 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4778 // instead of a CSEL in that case.
4779 if (TrueVal == ~FalseVal) {
4780 Opcode = AArch64ISD::CSINV;
4781 } else if (TrueVal == -FalseVal) {
4782 Opcode = AArch64ISD::CSNEG;
4783 } else if (TVal.getValueType() == MVT::i32) {
4784 // If our operands are only 32-bit wide, make sure we use 32-bit
4785 // arithmetic for the check whether we can use CSINC. This ensures that
4786 // the addition in the check will wrap around properly in case there is
4787 // an overflow (which would not be the case if we do the check with
4788 // 64-bit arithmetic).
4789 const uint32_t TrueVal32 = CTVal->getZExtValue();
4790 const uint32_t FalseVal32 = CFVal->getZExtValue();
4791
4792 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4793 Opcode = AArch64ISD::CSINC;
4794
4795 if (TrueVal32 > FalseVal32) {
4796 Swap = true;
4797 }
4798 }
4799 // 64-bit check whether we can use CSINC.
4800 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4801 Opcode = AArch64ISD::CSINC;
4802
4803 if (TrueVal > FalseVal) {
4804 Swap = true;
4805 }
4806 }
4807
4808 // Swap TVal and FVal if necessary.
4809 if (Swap) {
4810 std::swap(TVal, FVal);
4811 std::swap(CTVal, CFVal);
4812 CC = ISD::getSetCCInverse(CC, true);
4813 }
4814
4815 if (Opcode != AArch64ISD::CSEL) {
4816 // Drop FVal since we can get its value by simply inverting/negating
4817 // TVal.
4818 FVal = TVal;
4819 }
4820 }
4821
Chad Rosier58f505b2016-08-26 18:05:50 +00004822 // Avoid materializing a constant when possible by reusing a known value in
4823 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004824 // is one, zero or negative one in the case of a CSEL. We can always
4825 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4826 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004827 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4828 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4829 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4830 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4831 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4832 // "a != C ? x : a" to avoid materializing C.
4833 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4834 TVal = LHS;
4835 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4836 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004837 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4838 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4839 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4840 // avoid materializing C.
4841 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4842 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4843 Opcode = AArch64ISD::CSINV;
4844 TVal = LHS;
4845 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4846 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004847 }
4848
Tim Northover3b0846e2014-05-24 12:50:23 +00004849 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004850 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004851 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004852 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4853 }
4854
4855 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004856 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4857 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004858 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004859 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004860 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004861
4862 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4863 // clean. Some of them require two CSELs to implement.
4864 AArch64CC::CondCode CC1, CC2;
4865 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004866
4867 if (DAG.getTarget().Options.UnsafeFPMath) {
4868 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4869 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4870 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4871 if (RHSVal && RHSVal->isZero()) {
4872 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4873 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4874
4875 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004876 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004877 TVal = LHS;
4878 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004879 CFVal && CFVal->isZero() &&
4880 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004881 FVal = LHS;
4882 }
4883 }
4884
4885 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004886 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004887 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4888
4889 // If we need a second CSEL, emit it, using the output of the first as the
4890 // RHS. We're effectively OR'ing the two CC's together.
4891 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004892 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004893 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4894 }
4895
4896 // Otherwise, return the output of the first CSEL.
4897 return CS1;
4898}
4899
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004900SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4901 SelectionDAG &DAG) const {
4902 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4903 SDValue LHS = Op.getOperand(0);
4904 SDValue RHS = Op.getOperand(1);
4905 SDValue TVal = Op.getOperand(2);
4906 SDValue FVal = Op.getOperand(3);
4907 SDLoc DL(Op);
4908 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4909}
4910
4911SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4912 SelectionDAG &DAG) const {
4913 SDValue CCVal = Op->getOperand(0);
4914 SDValue TVal = Op->getOperand(1);
4915 SDValue FVal = Op->getOperand(2);
4916 SDLoc DL(Op);
4917
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004918 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4919 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004920 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004921 // Only lower legal XALUO ops.
4922 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4923 return SDValue();
4924
4925 AArch64CC::CondCode OFCC;
4926 SDValue Value, Overflow;
4927 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004928 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004929
4930 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4931 CCVal, Overflow);
4932 }
4933
4934 // Lower it the same way as we would lower a SELECT_CC node.
4935 ISD::CondCode CC;
4936 SDValue LHS, RHS;
4937 if (CCVal.getOpcode() == ISD::SETCC) {
4938 LHS = CCVal.getOperand(0);
4939 RHS = CCVal.getOperand(1);
4940 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4941 } else {
4942 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004943 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004944 CC = ISD::SETNE;
4945 }
4946 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4947}
4948
Tim Northover3b0846e2014-05-24 12:50:23 +00004949SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4950 SelectionDAG &DAG) const {
4951 // Jump table entries as PC relative offsets. No additional tweaking
4952 // is necessary here. Just get the address of the jump table.
4953 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004954
4955 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4956 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004957 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004958 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4959 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004960 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004961 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004962}
4963
Tim Northover1c353412018-10-24 20:19:09 +00004964SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
4965 SelectionDAG &DAG) const {
4966 // Jump table entries as PC relative offsets. No additional tweaking
4967 // is necessary here. Just get the address of the jump table.
4968 SDLoc DL(Op);
4969 SDValue JT = Op.getOperand(1);
4970 SDValue Entry = Op.getOperand(2);
4971 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
4972
4973 SDNode *Dest =
4974 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
4975 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
4976 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
4977 SDValue(Dest, 0));
4978}
4979
Tim Northover3b0846e2014-05-24 12:50:23 +00004980SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4981 SelectionDAG &DAG) const {
4982 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004983
4984 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4985 // Use the GOT for the large code model on iOS.
4986 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004987 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004988 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004989 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004990 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4991 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004992 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004993 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004994 }
4995}
4996
4997SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4998 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004999 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00005000 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5001 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00005002 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00005003 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5004 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005005 }
David Green9dd1d452018-08-22 11:31:39 +00005006 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005007}
5008
5009SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5010 SelectionDAG &DAG) const {
5011 AArch64FunctionInfo *FuncInfo =
5012 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5013
5014 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005015 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5016 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005017 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5018 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005019 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005020}
5021
Martin Storsjo68266fa2017-07-13 17:03:12 +00005022SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5023 SelectionDAG &DAG) const {
5024 AArch64FunctionInfo *FuncInfo =
5025 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5026
5027 SDLoc DL(Op);
5028 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5029 ? FuncInfo->getVarArgsGPRIndex()
5030 : FuncInfo->getVarArgsStackIndex(),
5031 getPointerTy(DAG.getDataLayout()));
5032 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5033 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5034 MachinePointerInfo(SV));
5035}
5036
Tim Northover3b0846e2014-05-24 12:50:23 +00005037SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5038 SelectionDAG &DAG) const {
5039 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5040 // Standard, section B.3.
5041 MachineFunction &MF = DAG.getMachineFunction();
5042 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005043 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005044 SDLoc DL(Op);
5045
5046 SDValue Chain = Op.getOperand(0);
5047 SDValue VAList = Op.getOperand(1);
5048 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5049 SmallVector<SDValue, 4> MemOps;
5050
5051 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005052 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005053 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005054 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005055
5056 // void *__gr_top at offset 8
5057 int GPRSize = FuncInfo->getVarArgsGPRSize();
5058 if (GPRSize > 0) {
5059 SDValue GRTop, GRTopAddr;
5060
Mehdi Amini44ede332015-07-09 02:09:04 +00005061 GRTopAddr =
5062 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005063
Mehdi Amini44ede332015-07-09 02:09:04 +00005064 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5065 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5066 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005067
5068 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005069 MachinePointerInfo(SV, 8),
5070 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005071 }
5072
5073 // void *__vr_top at offset 16
5074 int FPRSize = FuncInfo->getVarArgsFPRSize();
5075 if (FPRSize > 0) {
5076 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005077 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5078 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005079
Mehdi Amini44ede332015-07-09 02:09:04 +00005080 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5081 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5082 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005083
5084 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005085 MachinePointerInfo(SV, 16),
5086 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005087 }
5088
5089 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005090 SDValue GROffsAddr =
5091 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005092 MemOps.push_back(DAG.getStore(
5093 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5094 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005095
5096 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005097 SDValue VROffsAddr =
5098 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005099 MemOps.push_back(DAG.getStore(
5100 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5101 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005102
5103 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5104}
5105
5106SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5107 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005108 MachineFunction &MF = DAG.getMachineFunction();
5109
Matthias Braunf1caa282017-12-15 22:22:58 +00005110 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005111 return LowerWin64_VASTART(Op, DAG);
5112 else if (Subtarget->isTargetDarwin())
5113 return LowerDarwin_VASTART(Op, DAG);
5114 else
5115 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005116}
5117
5118SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5119 SelectionDAG &DAG) const {
5120 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5121 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005122 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005123 unsigned VaListSize =
5124 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005125 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5126 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5127
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005128 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5129 Op.getOperand(2),
5130 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005131 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005132 MachinePointerInfo(SrcSV));
5133}
5134
5135SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5136 assert(Subtarget->isTargetDarwin() &&
5137 "automatic va_arg instruction only works on Darwin");
5138
5139 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5140 EVT VT = Op.getValueType();
5141 SDLoc DL(Op);
5142 SDValue Chain = Op.getOperand(0);
5143 SDValue Addr = Op.getOperand(1);
5144 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005145 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005146
Justin Lebar9c375812016-07-15 18:27:10 +00005147 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005148 Chain = VAList.getValue(1);
5149
5150 if (Align > 8) {
5151 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005152 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5153 DAG.getConstant(Align - 1, DL, PtrVT));
5154 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5155 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005156 }
5157
5158 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005159 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005160
5161 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5162 // up to 64 bits. At the very least, we have to increase the striding of the
5163 // vaargs list to match this, and for FP values we need to introduce
5164 // FP_ROUND nodes as well.
5165 if (VT.isInteger() && !VT.isVector())
5166 ArgSize = 8;
5167 bool NeedFPTrunc = false;
5168 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5169 ArgSize = 8;
5170 NeedFPTrunc = true;
5171 }
5172
5173 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005174 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5175 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005176 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005177 SDValue APStore =
5178 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005179
5180 // Load the actual argument out of the pointer VAList
5181 if (NeedFPTrunc) {
5182 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005183 SDValue WideFP =
5184 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005185 // Round the value down to an f32.
5186 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005187 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005188 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5189 // Merge the rounded value with the chain output of the load.
5190 return DAG.getMergeValues(Ops, DL);
5191 }
5192
Justin Lebar9c375812016-07-15 18:27:10 +00005193 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005194}
5195
5196SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5197 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005198 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5199 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005200
5201 EVT VT = Op.getValueType();
5202 SDLoc DL(Op);
5203 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5204 SDValue FrameAddr =
5205 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5206 while (Depth--)
5207 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005208 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005209 return FrameAddr;
5210}
5211
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005212SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5213 SelectionDAG &DAG) const {
5214 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5215
5216 EVT VT = getPointerTy(DAG.getDataLayout());
5217 SDLoc DL(Op);
5218 int FI = MFI.CreateFixedObject(4, 0, false);
5219 return DAG.getFrameIndex(FI, VT);
5220}
5221
Tim Northover3b0846e2014-05-24 12:50:23 +00005222// FIXME? Maybe this could be a TableGen attribute on some registers and
5223// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005224unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5225 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005226 unsigned Reg = StringSwitch<unsigned>(RegName)
5227 .Case("sp", AArch64::SP)
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005228 .Case("x1", AArch64::X1)
5229 .Case("w1", AArch64::W1)
5230 .Case("x2", AArch64::X2)
5231 .Case("w2", AArch64::W2)
5232 .Case("x3", AArch64::X3)
5233 .Case("w3", AArch64::W3)
5234 .Case("x4", AArch64::X4)
5235 .Case("w4", AArch64::W4)
5236 .Case("x5", AArch64::X5)
5237 .Case("w5", AArch64::W5)
5238 .Case("x6", AArch64::X6)
5239 .Case("w6", AArch64::W6)
5240 .Case("x7", AArch64::X7)
5241 .Case("w7", AArch64::W7)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005242 .Case("x18", AArch64::X18)
5243 .Case("w18", AArch64::W18)
Petr Hosek72509082018-06-12 20:00:50 +00005244 .Case("x20", AArch64::X20)
5245 .Case("w20", AArch64::W20)
Tim Northover3b0846e2014-05-24 12:50:23 +00005246 .Default(0);
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005247 if (((Reg == AArch64::X1 || Reg == AArch64::W1) &&
5248 !Subtarget->isXRegisterReserved(1)) ||
5249 ((Reg == AArch64::X2 || Reg == AArch64::W2) &&
5250 !Subtarget->isXRegisterReserved(2)) ||
5251 ((Reg == AArch64::X3 || Reg == AArch64::W3) &&
5252 !Subtarget->isXRegisterReserved(3)) ||
5253 ((Reg == AArch64::X4 || Reg == AArch64::W4) &&
5254 !Subtarget->isXRegisterReserved(4)) ||
5255 ((Reg == AArch64::X5 || Reg == AArch64::W5) &&
5256 !Subtarget->isXRegisterReserved(5)) ||
5257 ((Reg == AArch64::X6 || Reg == AArch64::W6) &&
5258 !Subtarget->isXRegisterReserved(6)) ||
5259 ((Reg == AArch64::X7 || Reg == AArch64::W7) &&
5260 !Subtarget->isXRegisterReserved(7)) ||
5261 ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
5262 !Subtarget->isXRegisterReserved(18)) ||
Petr Hosek72509082018-06-12 20:00:50 +00005263 ((Reg == AArch64::X20 || Reg == AArch64::W20) &&
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005264 !Subtarget->isXRegisterReserved(20)))
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005265 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00005266 if (Reg)
5267 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005268 report_fatal_error(Twine("Invalid register name \""
5269 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005270}
5271
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005272SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5273 SelectionDAG &DAG) const {
5274 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5275
5276 EVT VT = Op.getValueType();
5277 SDLoc DL(Op);
5278
5279 SDValue FrameAddr =
5280 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5281 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5282
5283 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5284}
5285
Tim Northover3b0846e2014-05-24 12:50:23 +00005286SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5287 SelectionDAG &DAG) const {
5288 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005289 MachineFrameInfo &MFI = MF.getFrameInfo();
5290 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005291
5292 EVT VT = Op.getValueType();
5293 SDLoc DL(Op);
5294 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5295 if (Depth) {
5296 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005297 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005298 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5299 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005300 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005301 }
5302
5303 // Return LR, which contains the return address. Mark it an implicit live-in.
5304 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5305 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5306}
5307
5308/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5309/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5310SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5311 SelectionDAG &DAG) const {
5312 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5313 EVT VT = Op.getValueType();
5314 unsigned VTBits = VT.getSizeInBits();
5315 SDLoc dl(Op);
5316 SDValue ShOpLo = Op.getOperand(0);
5317 SDValue ShOpHi = Op.getOperand(1);
5318 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005319 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5320
5321 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5322
5323 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005324 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005325 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5326
5327 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5328 // is "undef". We wanted 0, so CSEL it directly.
5329 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5330 ISD::SETEQ, dl, DAG);
5331 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5332 HiBitsForLo =
5333 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5334 HiBitsForLo, CCVal, Cmp);
5335
Tim Northover3b0846e2014-05-24 12:50:23 +00005336 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005337 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005338
Tim Northoverf3be9d52015-12-02 00:33:54 +00005339 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5340 SDValue LoForNormalShift =
5341 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005342
Tim Northoverf3be9d52015-12-02 00:33:54 +00005343 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5344 dl, DAG);
5345 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5346 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5347 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5348 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005349
5350 // AArch64 shifts larger than the register width are wrapped rather than
5351 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005352 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5353 SDValue HiForBigShift =
5354 Opc == ISD::SRA
5355 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5356 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5357 : DAG.getConstant(0, dl, VT);
5358 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5359 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005360
5361 SDValue Ops[2] = { Lo, Hi };
5362 return DAG.getMergeValues(Ops, dl);
5363}
5364
5365/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5366/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5367SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005368 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005369 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5370 EVT VT = Op.getValueType();
5371 unsigned VTBits = VT.getSizeInBits();
5372 SDLoc dl(Op);
5373 SDValue ShOpLo = Op.getOperand(0);
5374 SDValue ShOpHi = Op.getOperand(1);
5375 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005376
5377 assert(Op.getOpcode() == ISD::SHL_PARTS);
5378 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005379 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005380 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5381
5382 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5383 // is "undef". We wanted 0, so CSEL it directly.
5384 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5385 ISD::SETEQ, dl, DAG);
5386 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5387 LoBitsForHi =
5388 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5389 LoBitsForHi, CCVal, Cmp);
5390
Tim Northover3b0846e2014-05-24 12:50:23 +00005391 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005392 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005393 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5394 SDValue HiForNormalShift =
5395 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005396
Tim Northoverf3be9d52015-12-02 00:33:54 +00005397 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005398
Tim Northoverf3be9d52015-12-02 00:33:54 +00005399 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5400 dl, DAG);
5401 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5402 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5403 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005404
5405 // AArch64 shifts of larger than register sizes are wrapped rather than
5406 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005407 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5408 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5409 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5410 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005411
5412 SDValue Ops[2] = { Lo, Hi };
5413 return DAG.getMergeValues(Ops, dl);
5414}
5415
5416bool AArch64TargetLowering::isOffsetFoldingLegal(
5417 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005418 // Offsets are folded in the DAG combine rather than here so that we can
5419 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005420 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005421}
5422
5423bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005424 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005425 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5426 // 16-bit case when target has full fp16 support.
5427 // FIXME: We should be able to handle f128 as well with a clever lowering.
5428 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005429 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005430 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005431 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005432 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005433 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005434 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5435 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5436 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005437
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005438 // If we can not materialize in immediate field for fmov, check if the
5439 // value can be encoded as the immediate operand of a logical instruction.
5440 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5441 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32))
5442 IsLegal = AArch64_AM::isAnyMOVWMovAlias(ImmInt.getZExtValue(),
5443 VT.getSizeInBits());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005444
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005445 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5446 << " imm value: "; Imm.dump(););
5447 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005448}
5449
5450//===----------------------------------------------------------------------===//
5451// AArch64 Optimization Hooks
5452//===----------------------------------------------------------------------===//
5453
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005454static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5455 SDValue Operand, SelectionDAG &DAG,
5456 int &ExtraSteps) {
5457 EVT VT = Operand.getValueType();
5458 if (ST->hasNEON() &&
5459 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5460 VT == MVT::f32 || VT == MVT::v1f32 ||
5461 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5462 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5463 // For the reciprocal estimates, convergence is quadratic, so the number
5464 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5465 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5466 // the result for float (23 mantissa bits) is 2 and for double (52
5467 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005468 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005469
5470 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5471 }
5472
5473 return SDValue();
5474}
5475
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005476SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5477 SelectionDAG &DAG, int Enabled,
5478 int &ExtraSteps,
5479 bool &UseOneConst,
5480 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005481 if (Enabled == ReciprocalEstimate::Enabled ||
5482 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5483 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5484 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005485 SDLoc DL(Operand);
5486 EVT VT = Operand.getValueType();
5487
5488 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005489 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005490
5491 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5492 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5493 for (int i = ExtraSteps; i > 0; --i) {
5494 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005495 Flags);
5496 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5497 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005498 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005499 if (!Reciprocal) {
5500 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5501 VT);
5502 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5503 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5504
Amara Emersond28f0cd42017-05-01 15:17:51 +00005505 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005506 // Correct the result if the operand is 0.0.
5507 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5508 VT, Eq, Operand, Estimate);
5509 }
5510
5511 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005512 return Estimate;
5513 }
5514
5515 return SDValue();
5516}
5517
5518SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5519 SelectionDAG &DAG, int Enabled,
5520 int &ExtraSteps) const {
5521 if (Enabled == ReciprocalEstimate::Enabled)
5522 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005523 DAG, ExtraSteps)) {
5524 SDLoc DL(Operand);
5525 EVT VT = Operand.getValueType();
5526
5527 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005528 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005529
5530 // Newton reciprocal iteration: E * (2 - X * E)
5531 // AArch64 reciprocal iteration instruction: (2 - M * N)
5532 for (int i = ExtraSteps; i > 0; --i) {
5533 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005534 Estimate, Flags);
5535 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005536 }
5537
5538 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005539 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005540 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005541
5542 return SDValue();
5543}
5544
Tim Northover3b0846e2014-05-24 12:50:23 +00005545//===----------------------------------------------------------------------===//
5546// AArch64 Inline Assembly Support
5547//===----------------------------------------------------------------------===//
5548
5549// Table of Constraints
5550// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005551// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005552//
5553// r - A general register
5554// w - An FP/SIMD register of some size in the range v0-v31
5555// x - An FP/SIMD register of some size in the range v0-v15
5556// I - Constant that can be used with an ADD instruction
5557// J - Constant that can be used with a SUB instruction
5558// K - Constant that can be used with a 32-bit logical instruction
5559// L - Constant that can be used with a 64-bit logical instruction
5560// M - Constant that can be used as a 32-bit MOV immediate
5561// N - Constant that can be used as a 64-bit MOV immediate
5562// Q - A memory reference with base register and no offset
5563// S - A symbolic address
5564// Y - Floating point constant zero
5565// Z - Integer constant zero
5566//
5567// Note that general register operands will be output using their 64-bit x
5568// register name, whatever the size of the variable, unless the asm operand
5569// is prefixed by the %w modifier. Floating-point and SIMD register operands
5570// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5571// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005572const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5573 // At this point, we have to lower this constraint to something else, so we
5574 // lower it to an "r" or "w". However, by doing this we will force the result
5575 // to be in register, while the X constraint is much more permissive.
5576 //
5577 // Although we are correct (we are free to emit anything, without
5578 // constraints), we might break use cases that would expect us to be more
5579 // efficient and emit something else.
5580 if (!Subtarget->hasFPARMv8())
5581 return "r";
5582
5583 if (ConstraintVT.isFloatingPoint())
5584 return "w";
5585
5586 if (ConstraintVT.isVector() &&
5587 (ConstraintVT.getSizeInBits() == 64 ||
5588 ConstraintVT.getSizeInBits() == 128))
5589 return "w";
5590
5591 return "r";
5592}
Tim Northover3b0846e2014-05-24 12:50:23 +00005593
5594/// getConstraintType - Given a constraint letter, return the type of
5595/// constraint it is for this target.
5596AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005597AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005598 if (Constraint.size() == 1) {
5599 switch (Constraint[0]) {
5600 default:
5601 break;
5602 case 'z':
5603 return C_Other;
5604 case 'x':
5605 case 'w':
5606 return C_RegisterClass;
5607 // An address with a single base register. Due to the way we
5608 // currently handle addresses it is the same as 'r'.
5609 case 'Q':
5610 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005611 case 'S': // A symbolic address
5612 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005613 }
5614 }
5615 return TargetLowering::getConstraintType(Constraint);
5616}
5617
5618/// Examine constraint type and operand type and determine a weight value.
5619/// This object must already have been set up with the operand type
5620/// and the current alternative constraint selected.
5621TargetLowering::ConstraintWeight
5622AArch64TargetLowering::getSingleConstraintMatchWeight(
5623 AsmOperandInfo &info, const char *constraint) const {
5624 ConstraintWeight weight = CW_Invalid;
5625 Value *CallOperandVal = info.CallOperandVal;
5626 // If we don't have a value, we can't do a match,
5627 // but allow it at the lowest weight.
5628 if (!CallOperandVal)
5629 return CW_Default;
5630 Type *type = CallOperandVal->getType();
5631 // Look at the constraint type.
5632 switch (*constraint) {
5633 default:
5634 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5635 break;
5636 case 'x':
5637 case 'w':
5638 if (type->isFloatingPointTy() || type->isVectorTy())
5639 weight = CW_Register;
5640 break;
5641 case 'z':
5642 weight = CW_Constant;
5643 break;
5644 }
5645 return weight;
5646}
5647
5648std::pair<unsigned, const TargetRegisterClass *>
5649AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005650 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005651 if (Constraint.size() == 1) {
5652 switch (Constraint[0]) {
5653 case 'r':
5654 if (VT.getSizeInBits() == 64)
5655 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5656 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5657 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005658 if (!Subtarget->hasFPARMv8())
5659 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005660 if (VT.getSizeInBits() == 16)
5661 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005662 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005663 return std::make_pair(0U, &AArch64::FPR32RegClass);
5664 if (VT.getSizeInBits() == 64)
5665 return std::make_pair(0U, &AArch64::FPR64RegClass);
5666 if (VT.getSizeInBits() == 128)
5667 return std::make_pair(0U, &AArch64::FPR128RegClass);
5668 break;
5669 // The instructions that this constraint is designed for can
5670 // only take 128-bit registers so just use that regclass.
5671 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005672 if (!Subtarget->hasFPARMv8())
5673 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005674 if (VT.getSizeInBits() == 128)
5675 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5676 break;
5677 }
5678 }
5679 if (StringRef("{cc}").equals_lower(Constraint))
5680 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5681
5682 // Use the default implementation in TargetLowering to convert the register
5683 // constraint into a member of a register class.
5684 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005685 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005686
5687 // Not found as a standard register?
5688 if (!Res.second) {
5689 unsigned Size = Constraint.size();
5690 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5691 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005692 int RegNo;
5693 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5694 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005695 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005696 // By default we'll emit v0-v31 for this unless there's a modifier where
5697 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005698 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5699 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5700 Res.second = &AArch64::FPR64RegClass;
5701 } else {
5702 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5703 Res.second = &AArch64::FPR128RegClass;
5704 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005705 }
5706 }
5707 }
5708
Eli Friedman071203b2018-08-24 19:12:13 +00005709 if (Res.second && !Subtarget->hasFPARMv8() &&
5710 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5711 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5712 return std::make_pair(0U, nullptr);
5713
Tim Northover3b0846e2014-05-24 12:50:23 +00005714 return Res;
5715}
5716
5717/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5718/// vector. If it is invalid, don't add anything to Ops.
5719void AArch64TargetLowering::LowerAsmOperandForConstraint(
5720 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5721 SelectionDAG &DAG) const {
5722 SDValue Result;
5723
5724 // Currently only support length 1 constraints.
5725 if (Constraint.length() != 1)
5726 return;
5727
5728 char ConstraintLetter = Constraint[0];
5729 switch (ConstraintLetter) {
5730 default:
5731 break;
5732
5733 // This set of constraints deal with valid constants for various instructions.
5734 // Validate and return a target constant for them if we can.
5735 case 'z': {
5736 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005737 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005738 return;
5739
5740 if (Op.getValueType() == MVT::i64)
5741 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5742 else
5743 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5744 break;
5745 }
Peter Smithc8117582018-05-16 09:33:25 +00005746 case 'S': {
5747 // An absolute symbolic address or label reference.
5748 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5749 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5750 GA->getValueType(0));
5751 } else if (const BlockAddressSDNode *BA =
5752 dyn_cast<BlockAddressSDNode>(Op)) {
5753 Result =
5754 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5755 } else if (const ExternalSymbolSDNode *ES =
5756 dyn_cast<ExternalSymbolSDNode>(Op)) {
5757 Result =
5758 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5759 } else
5760 return;
5761 break;
5762 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005763
5764 case 'I':
5765 case 'J':
5766 case 'K':
5767 case 'L':
5768 case 'M':
5769 case 'N':
5770 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5771 if (!C)
5772 return;
5773
5774 // Grab the value and do some validation.
5775 uint64_t CVal = C->getZExtValue();
5776 switch (ConstraintLetter) {
5777 // The I constraint applies only to simple ADD or SUB immediate operands:
5778 // i.e. 0 to 4095 with optional shift by 12
5779 // The J constraint applies only to ADD or SUB immediates that would be
5780 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5781 // instruction [or vice versa], in other words -1 to -4095 with optional
5782 // left shift by 12.
5783 case 'I':
5784 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5785 break;
5786 return;
5787 case 'J': {
5788 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005789 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5790 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005791 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005792 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005793 return;
5794 }
5795 // The K and L constraints apply *only* to logical immediates, including
5796 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5797 // been removed and MOV should be used). So these constraints have to
5798 // distinguish between bit patterns that are valid 32-bit or 64-bit
5799 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5800 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5801 // versa.
5802 case 'K':
5803 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5804 break;
5805 return;
5806 case 'L':
5807 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5808 break;
5809 return;
5810 // The M and N constraints are a superset of K and L respectively, for use
5811 // with the MOV (immediate) alias. As well as the logical immediates they
5812 // also match 32 or 64-bit immediates that can be loaded either using a
5813 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5814 // (M) or 64-bit 0x1234000000000000 (N) etc.
5815 // As a note some of this code is liberally stolen from the asm parser.
5816 case 'M': {
5817 if (!isUInt<32>(CVal))
5818 return;
5819 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5820 break;
5821 if ((CVal & 0xFFFF) == CVal)
5822 break;
5823 if ((CVal & 0xFFFF0000ULL) == CVal)
5824 break;
5825 uint64_t NCVal = ~(uint32_t)CVal;
5826 if ((NCVal & 0xFFFFULL) == NCVal)
5827 break;
5828 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5829 break;
5830 return;
5831 }
5832 case 'N': {
5833 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5834 break;
5835 if ((CVal & 0xFFFFULL) == CVal)
5836 break;
5837 if ((CVal & 0xFFFF0000ULL) == CVal)
5838 break;
5839 if ((CVal & 0xFFFF00000000ULL) == CVal)
5840 break;
5841 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5842 break;
5843 uint64_t NCVal = ~CVal;
5844 if ((NCVal & 0xFFFFULL) == NCVal)
5845 break;
5846 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5847 break;
5848 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5849 break;
5850 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5851 break;
5852 return;
5853 }
5854 default:
5855 return;
5856 }
5857
5858 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005859 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005860 break;
5861 }
5862
5863 if (Result.getNode()) {
5864 Ops.push_back(Result);
5865 return;
5866 }
5867
5868 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5869}
5870
5871//===----------------------------------------------------------------------===//
5872// AArch64 Advanced SIMD Support
5873//===----------------------------------------------------------------------===//
5874
5875/// WidenVector - Given a value in the V64 register class, produce the
5876/// equivalent value in the V128 register class.
5877static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5878 EVT VT = V64Reg.getValueType();
5879 unsigned NarrowSize = VT.getVectorNumElements();
5880 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5881 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5882 SDLoc DL(V64Reg);
5883
5884 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005885 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005886}
5887
5888/// getExtFactor - Determine the adjustment factor for the position when
5889/// generating an "extract from vector registers" instruction.
5890static unsigned getExtFactor(SDValue &V) {
5891 EVT EltType = V.getValueType().getVectorElementType();
5892 return EltType.getSizeInBits() / 8;
5893}
5894
5895/// NarrowVector - Given a value in the V128 register class, produce the
5896/// equivalent value in the V64 register class.
5897static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5898 EVT VT = V128Reg.getValueType();
5899 unsigned WideSize = VT.getVectorNumElements();
5900 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5901 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5902 SDLoc DL(V128Reg);
5903
5904 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5905}
5906
5907// Gather data to see if the operation can be modelled as a
5908// shuffle in combination with VEXTs.
5909SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5910 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005911 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005912 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005913 SDLoc dl(Op);
5914 EVT VT = Op.getValueType();
5915 unsigned NumElts = VT.getVectorNumElements();
5916
Tim Northover7324e842014-07-24 15:39:55 +00005917 struct ShuffleSourceInfo {
5918 SDValue Vec;
5919 unsigned MinElt;
5920 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005921
Tim Northover7324e842014-07-24 15:39:55 +00005922 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5923 // be compatible with the shuffle we intend to construct. As a result
5924 // ShuffleVec will be some sliding window into the original Vec.
5925 SDValue ShuffleVec;
5926
5927 // Code should guarantee that element i in Vec starts at element "WindowBase
5928 // + i * WindowScale in ShuffleVec".
5929 int WindowBase;
5930 int WindowScale;
5931
Tim Northover7324e842014-07-24 15:39:55 +00005932 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005933 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5934 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5935
5936 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005937 };
5938
5939 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5940 // node.
5941 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005942 for (unsigned i = 0; i < NumElts; ++i) {
5943 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005944 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005945 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005946 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5947 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005948 LLVM_DEBUG(
5949 dbgs() << "Reshuffle failed: "
5950 "a shuffle can only come from building a vector from "
5951 "various elements of other vectors, provided their "
5952 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005953 return SDValue();
5954 }
5955
Tim Northover7324e842014-07-24 15:39:55 +00005956 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005957 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005958 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005959 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005960 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005961
Tim Northover7324e842014-07-24 15:39:55 +00005962 // Update the minimum and maximum lane number seen.
5963 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5964 Source->MinElt = std::min(Source->MinElt, EltNo);
5965 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005966 }
5967
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005968 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005969 LLVM_DEBUG(
5970 dbgs() << "Reshuffle failed: currently only do something sane when at "
5971 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005972 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005973 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005974
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005975 // Find out the smallest element size among result and two sources, and use
5976 // it as element size to build the shuffle_vector.
5977 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005978 for (auto &Source : Sources) {
5979 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005980 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5981 SmallestEltTy = SrcEltTy;
5982 }
5983 }
5984 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005985 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005986 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5987 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005988
Tim Northover7324e842014-07-24 15:39:55 +00005989 // If the source vector is too wide or too narrow, we may nevertheless be able
5990 // to construct a compatible shuffle either by concatenating it with UNDEF or
5991 // extracting a suitable range of elements.
5992 for (auto &Src : Sources) {
5993 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005994
Tim Northover7324e842014-07-24 15:39:55 +00005995 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005996 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005997
5998 // This stage of the search produces a source with the same element type as
5999 // the original, but with a total width matching the BUILD_VECTOR output.
6000 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00006001 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6002 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00006003
6004 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6005 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006006 // We can pad out the smaller vector for free, so if it's part of a
6007 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00006008 Src.ShuffleVec =
6009 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6010 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00006011 continue;
6012 }
6013
Tim Northover7324e842014-07-24 15:39:55 +00006014 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006015
James Molloyf497d552014-10-17 17:06:31 +00006016 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006017 LLVM_DEBUG(
6018 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006019 return SDValue();
6020 }
6021
James Molloyf497d552014-10-17 17:06:31 +00006022 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006023 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00006024 Src.ShuffleVec =
6025 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006026 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00006027 Src.WindowBase = -NumSrcElts;
6028 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006029 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006030 Src.ShuffleVec =
6031 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006032 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006033 } else {
6034 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006035 SDValue VEXTSrc1 =
6036 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006037 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006038 SDValue VEXTSrc2 =
6039 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006040 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006041 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6042
6043 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006044 VEXTSrc2,
6045 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006046 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006047 }
6048 }
6049
Tim Northover7324e842014-07-24 15:39:55 +00006050 // Another possible incompatibility occurs from the vector element types. We
6051 // can fix this by bitcasting the source vectors to the same type we intend
6052 // for the shuffle.
6053 for (auto &Src : Sources) {
6054 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6055 if (SrcEltTy == SmallestEltTy)
6056 continue;
6057 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6058 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6059 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6060 Src.WindowBase *= Src.WindowScale;
6061 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006062
Tim Northover7324e842014-07-24 15:39:55 +00006063 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006064 LLVM_DEBUG(for (auto Src
6065 : Sources)
6066 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006067
6068 // The stars all align, our next step is to produce the mask for the shuffle.
6069 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006070 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006071 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006072 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006073 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006074 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006075
David Majnemer0d955d02016-08-11 22:21:41 +00006076 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006077 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6078
6079 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6080 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6081 // segment.
6082 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006083 int BitsDefined =
6084 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006085 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6086
6087 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6088 // starting at the appropriate offset.
6089 int *LaneMask = &Mask[i * ResMultiplier];
6090
6091 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6092 ExtractBase += NumElts * (Src - Sources.begin());
6093 for (int j = 0; j < LanesDefined; ++j)
6094 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006095 }
6096
6097 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006098 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006099 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006100 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006101 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006102
Tim Northover7324e842014-07-24 15:39:55 +00006103 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6104 for (unsigned i = 0; i < Sources.size(); ++i)
6105 ShuffleOps[i] = Sources[i].ShuffleVec;
6106
6107 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006108 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006109 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6110
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006111 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6112 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006113
6114 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006115}
6116
6117// check if an EXT instruction can handle the shuffle mask when the
6118// vector sources of the shuffle are the same.
6119static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6120 unsigned NumElts = VT.getVectorNumElements();
6121
6122 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6123 if (M[0] < 0)
6124 return false;
6125
6126 Imm = M[0];
6127
6128 // If this is a VEXT shuffle, the immediate value is the index of the first
6129 // element. The other shuffle indices must be the successive elements after
6130 // the first one.
6131 unsigned ExpectedElt = Imm;
6132 for (unsigned i = 1; i < NumElts; ++i) {
6133 // Increment the expected index. If it wraps around, just follow it
6134 // back to index zero and keep going.
6135 ++ExpectedElt;
6136 if (ExpectedElt == NumElts)
6137 ExpectedElt = 0;
6138
6139 if (M[i] < 0)
6140 continue; // ignore UNDEF indices
6141 if (ExpectedElt != static_cast<unsigned>(M[i]))
6142 return false;
6143 }
6144
6145 return true;
6146}
6147
6148// check if an EXT instruction can handle the shuffle mask when the
6149// vector sources of the shuffle are different.
6150static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6151 unsigned &Imm) {
6152 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006153 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006154
6155 // Benefit form APInt to handle overflow when calculating expected element.
6156 unsigned NumElts = VT.getVectorNumElements();
6157 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6158 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6159 // The following shuffle indices must be the successive elements after the
6160 // first real element.
6161 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6162 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6163 if (FirstWrongElt != M.end())
6164 return false;
6165
6166 // The index of an EXT is the first element if it is not UNDEF.
6167 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006168 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006169 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6170 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6171 // ExpectedElt is the last mask index plus 1.
6172 Imm = ExpectedElt.getZExtValue();
6173
6174 // There are two difference cases requiring to reverse input vectors.
6175 // For example, for vector <4 x i32> we have the following cases,
6176 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6177 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6178 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6179 // to reverse two input vectors.
6180 if (Imm < NumElts)
6181 ReverseEXT = true;
6182 else
6183 Imm -= NumElts;
6184
6185 return true;
6186}
6187
6188/// isREVMask - Check if a vector shuffle corresponds to a REV
6189/// instruction with the specified blocksize. (The order of the elements
6190/// within each block of the vector is reversed.)
6191static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6192 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6193 "Only possible block sizes for REV are: 16, 32, 64");
6194
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006195 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006196 if (EltSz == 64)
6197 return false;
6198
6199 unsigned NumElts = VT.getVectorNumElements();
6200 unsigned BlockElts = M[0] + 1;
6201 // If the first shuffle index is UNDEF, be optimistic.
6202 if (M[0] < 0)
6203 BlockElts = BlockSize / EltSz;
6204
6205 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6206 return false;
6207
6208 for (unsigned i = 0; i < NumElts; ++i) {
6209 if (M[i] < 0)
6210 continue; // ignore UNDEF indices
6211 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6212 return false;
6213 }
6214
6215 return true;
6216}
6217
6218static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6219 unsigned NumElts = VT.getVectorNumElements();
6220 WhichResult = (M[0] == 0 ? 0 : 1);
6221 unsigned Idx = WhichResult * NumElts / 2;
6222 for (unsigned i = 0; i != NumElts; i += 2) {
6223 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6224 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6225 return false;
6226 Idx += 1;
6227 }
6228
6229 return true;
6230}
6231
6232static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6233 unsigned NumElts = VT.getVectorNumElements();
6234 WhichResult = (M[0] == 0 ? 0 : 1);
6235 for (unsigned i = 0; i != NumElts; ++i) {
6236 if (M[i] < 0)
6237 continue; // ignore UNDEF indices
6238 if ((unsigned)M[i] != 2 * i + WhichResult)
6239 return false;
6240 }
6241
6242 return true;
6243}
6244
6245static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6246 unsigned NumElts = VT.getVectorNumElements();
6247 WhichResult = (M[0] == 0 ? 0 : 1);
6248 for (unsigned i = 0; i < NumElts; i += 2) {
6249 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6250 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6251 return false;
6252 }
6253 return true;
6254}
6255
6256/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6257/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6258/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6259static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6260 unsigned NumElts = VT.getVectorNumElements();
6261 WhichResult = (M[0] == 0 ? 0 : 1);
6262 unsigned Idx = WhichResult * NumElts / 2;
6263 for (unsigned i = 0; i != NumElts; i += 2) {
6264 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6265 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6266 return false;
6267 Idx += 1;
6268 }
6269
6270 return true;
6271}
6272
6273/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6274/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6275/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6276static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6277 unsigned Half = VT.getVectorNumElements() / 2;
6278 WhichResult = (M[0] == 0 ? 0 : 1);
6279 for (unsigned j = 0; j != 2; ++j) {
6280 unsigned Idx = WhichResult;
6281 for (unsigned i = 0; i != Half; ++i) {
6282 int MIdx = M[i + j * Half];
6283 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6284 return false;
6285 Idx += 2;
6286 }
6287 }
6288
6289 return true;
6290}
6291
6292/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6293/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6294/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6295static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6296 unsigned NumElts = VT.getVectorNumElements();
6297 WhichResult = (M[0] == 0 ? 0 : 1);
6298 for (unsigned i = 0; i < NumElts; i += 2) {
6299 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6300 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6301 return false;
6302 }
6303 return true;
6304}
6305
6306static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6307 bool &DstIsLeft, int &Anomaly) {
6308 if (M.size() != static_cast<size_t>(NumInputElements))
6309 return false;
6310
6311 int NumLHSMatch = 0, NumRHSMatch = 0;
6312 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6313
6314 for (int i = 0; i < NumInputElements; ++i) {
6315 if (M[i] == -1) {
6316 ++NumLHSMatch;
6317 ++NumRHSMatch;
6318 continue;
6319 }
6320
6321 if (M[i] == i)
6322 ++NumLHSMatch;
6323 else
6324 LastLHSMismatch = i;
6325
6326 if (M[i] == i + NumInputElements)
6327 ++NumRHSMatch;
6328 else
6329 LastRHSMismatch = i;
6330 }
6331
6332 if (NumLHSMatch == NumInputElements - 1) {
6333 DstIsLeft = true;
6334 Anomaly = LastLHSMismatch;
6335 return true;
6336 } else if (NumRHSMatch == NumInputElements - 1) {
6337 DstIsLeft = false;
6338 Anomaly = LastRHSMismatch;
6339 return true;
6340 }
6341
6342 return false;
6343}
6344
6345static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6346 if (VT.getSizeInBits() != 128)
6347 return false;
6348
6349 unsigned NumElts = VT.getVectorNumElements();
6350
6351 for (int I = 0, E = NumElts / 2; I != E; I++) {
6352 if (Mask[I] != I)
6353 return false;
6354 }
6355
6356 int Offset = NumElts / 2;
6357 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6358 if (Mask[I] != I + SplitLHS * Offset)
6359 return false;
6360 }
6361
6362 return true;
6363}
6364
6365static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6366 SDLoc DL(Op);
6367 EVT VT = Op.getValueType();
6368 SDValue V0 = Op.getOperand(0);
6369 SDValue V1 = Op.getOperand(1);
6370 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6371
6372 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6373 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6374 return SDValue();
6375
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006376 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006377
6378 if (!isConcatMask(Mask, VT, SplitV0))
6379 return SDValue();
6380
6381 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6382 VT.getVectorNumElements() / 2);
6383 if (SplitV0) {
6384 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006385 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006386 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006387 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006388 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006389 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006390 }
6391 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6392}
6393
6394/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6395/// the specified operations to build the shuffle.
6396static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6397 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006398 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006399 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6400 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6401 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6402
6403 enum {
6404 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6405 OP_VREV,
6406 OP_VDUP0,
6407 OP_VDUP1,
6408 OP_VDUP2,
6409 OP_VDUP3,
6410 OP_VEXT1,
6411 OP_VEXT2,
6412 OP_VEXT3,
6413 OP_VUZPL, // VUZP, left result
6414 OP_VUZPR, // VUZP, right result
6415 OP_VZIPL, // VZIP, left result
6416 OP_VZIPR, // VZIP, right result
6417 OP_VTRNL, // VTRN, left result
6418 OP_VTRNR // VTRN, right result
6419 };
6420
6421 if (OpNum == OP_COPY) {
6422 if (LHSID == (1 * 9 + 2) * 9 + 3)
6423 return LHS;
6424 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6425 return RHS;
6426 }
6427
6428 SDValue OpLHS, OpRHS;
6429 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6430 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6431 EVT VT = OpLHS.getValueType();
6432
6433 switch (OpNum) {
6434 default:
6435 llvm_unreachable("Unknown shuffle opcode!");
6436 case OP_VREV:
6437 // VREV divides the vector in half and swaps within the half.
6438 if (VT.getVectorElementType() == MVT::i32 ||
6439 VT.getVectorElementType() == MVT::f32)
6440 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6441 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006442 if (VT.getVectorElementType() == MVT::i16 ||
6443 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006444 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6445 // vrev <4 x i8> -> REV16
6446 assert(VT.getVectorElementType() == MVT::i8);
6447 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6448 case OP_VDUP0:
6449 case OP_VDUP1:
6450 case OP_VDUP2:
6451 case OP_VDUP3: {
6452 EVT EltTy = VT.getVectorElementType();
6453 unsigned Opcode;
6454 if (EltTy == MVT::i8)
6455 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006456 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006457 Opcode = AArch64ISD::DUPLANE16;
6458 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6459 Opcode = AArch64ISD::DUPLANE32;
6460 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6461 Opcode = AArch64ISD::DUPLANE64;
6462 else
6463 llvm_unreachable("Invalid vector element type?");
6464
6465 if (VT.getSizeInBits() == 64)
6466 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006467 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006468 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6469 }
6470 case OP_VEXT1:
6471 case OP_VEXT2:
6472 case OP_VEXT3: {
6473 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6474 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006475 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006476 }
6477 case OP_VUZPL:
6478 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6479 OpRHS);
6480 case OP_VUZPR:
6481 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6482 OpRHS);
6483 case OP_VZIPL:
6484 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6485 OpRHS);
6486 case OP_VZIPR:
6487 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6488 OpRHS);
6489 case OP_VTRNL:
6490 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6491 OpRHS);
6492 case OP_VTRNR:
6493 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6494 OpRHS);
6495 }
6496}
6497
6498static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6499 SelectionDAG &DAG) {
6500 // Check to see if we can use the TBL instruction.
6501 SDValue V1 = Op.getOperand(0);
6502 SDValue V2 = Op.getOperand(1);
6503 SDLoc DL(Op);
6504
6505 EVT EltVT = Op.getValueType().getVectorElementType();
6506 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6507
6508 SmallVector<SDValue, 8> TBLMask;
6509 for (int Val : ShuffleMask) {
6510 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6511 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006512 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006513 }
6514 }
6515
6516 MVT IndexVT = MVT::v8i8;
6517 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006518 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006519 IndexVT = MVT::v16i8;
6520 IndexLen = 16;
6521 }
6522
6523 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6524 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6525
6526 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006527 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006528 if (IndexLen == 8)
6529 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6530 Shuffle = DAG.getNode(
6531 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006532 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006533 DAG.getBuildVector(IndexVT, DL,
6534 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006535 } else {
6536 if (IndexLen == 8) {
6537 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6538 Shuffle = DAG.getNode(
6539 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006540 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006541 DAG.getBuildVector(IndexVT, DL,
6542 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006543 } else {
6544 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6545 // cannot currently represent the register constraints on the input
6546 // table registers.
6547 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006548 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6549 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006550 Shuffle = DAG.getNode(
6551 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006552 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6553 V2Cst, DAG.getBuildVector(IndexVT, DL,
6554 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006555 }
6556 }
6557 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6558}
6559
6560static unsigned getDUPLANEOp(EVT EltType) {
6561 if (EltType == MVT::i8)
6562 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006563 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006564 return AArch64ISD::DUPLANE16;
6565 if (EltType == MVT::i32 || EltType == MVT::f32)
6566 return AArch64ISD::DUPLANE32;
6567 if (EltType == MVT::i64 || EltType == MVT::f64)
6568 return AArch64ISD::DUPLANE64;
6569
6570 llvm_unreachable("Invalid vector element type?");
6571}
6572
6573SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6574 SelectionDAG &DAG) const {
6575 SDLoc dl(Op);
6576 EVT VT = Op.getValueType();
6577
6578 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6579
6580 // Convert shuffles that are directly supported on NEON to target-specific
6581 // DAG nodes, instead of keeping them as shuffles and matching them again
6582 // during code selection. This is more efficient and avoids the possibility
6583 // of inconsistencies between legalization and selection.
6584 ArrayRef<int> ShuffleMask = SVN->getMask();
6585
6586 SDValue V1 = Op.getOperand(0);
6587 SDValue V2 = Op.getOperand(1);
6588
Craig Topperbc56e3b2016-06-30 04:38:51 +00006589 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006590 int Lane = SVN->getSplatIndex();
6591 // If this is undef splat, generate it via "just" vdup, if possible.
6592 if (Lane == -1)
6593 Lane = 0;
6594
6595 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6596 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6597 V1.getOperand(0));
6598 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6599 // constant. If so, we can just reference the lane's definition directly.
6600 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6601 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6602 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6603
6604 // Otherwise, duplicate from the lane of the input vector.
6605 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6606
6607 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6608 // to make a vector of the same size as this SHUFFLE. We can ignore the
6609 // extract entirely, and canonicalise the concat using WidenVector.
6610 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6611 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6612 V1 = V1.getOperand(0);
6613 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6614 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6615 Lane -= Idx * VT.getVectorNumElements() / 2;
6616 V1 = WidenVector(V1.getOperand(Idx), DAG);
6617 } else if (VT.getSizeInBits() == 64)
6618 V1 = WidenVector(V1, DAG);
6619
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006620 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006621 }
6622
6623 if (isREVMask(ShuffleMask, VT, 64))
6624 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6625 if (isREVMask(ShuffleMask, VT, 32))
6626 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6627 if (isREVMask(ShuffleMask, VT, 16))
6628 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6629
6630 bool ReverseEXT = false;
6631 unsigned Imm;
6632 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6633 if (ReverseEXT)
6634 std::swap(V1, V2);
6635 Imm *= getExtFactor(V1);
6636 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006637 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006638 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006639 Imm *= getExtFactor(V1);
6640 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006641 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006642 }
6643
6644 unsigned WhichResult;
6645 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6646 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6647 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6648 }
6649 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6650 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6651 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6652 }
6653 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6654 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6655 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6656 }
6657
6658 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6659 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6660 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6661 }
6662 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6663 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6664 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6665 }
6666 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6667 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6668 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6669 }
6670
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006671 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006672 return Concat;
6673
6674 bool DstIsLeft;
6675 int Anomaly;
6676 int NumInputElements = V1.getValueType().getVectorNumElements();
6677 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6678 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006679 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006680
6681 SDValue SrcVec = V1;
6682 int SrcLane = ShuffleMask[Anomaly];
6683 if (SrcLane >= NumInputElements) {
6684 SrcVec = V2;
6685 SrcLane -= VT.getVectorNumElements();
6686 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006687 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006688
6689 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006690
6691 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006692 ScalarVT = MVT::i32;
6693
6694 return DAG.getNode(
6695 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6696 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6697 DstLaneV);
6698 }
6699
6700 // If the shuffle is not directly supported and it has 4 elements, use
6701 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6702 unsigned NumElts = VT.getVectorNumElements();
6703 if (NumElts == 4) {
6704 unsigned PFIndexes[4];
6705 for (unsigned i = 0; i != 4; ++i) {
6706 if (ShuffleMask[i] < 0)
6707 PFIndexes[i] = 8;
6708 else
6709 PFIndexes[i] = ShuffleMask[i];
6710 }
6711
6712 // Compute the index in the perfect shuffle table.
6713 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6714 PFIndexes[2] * 9 + PFIndexes[3];
6715 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6716 unsigned Cost = (PFEntry >> 30);
6717
6718 if (Cost <= 4)
6719 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6720 }
6721
6722 return GenerateTBL(Op, ShuffleMask, DAG);
6723}
6724
6725static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6726 APInt &UndefBits) {
6727 EVT VT = BVN->getValueType(0);
6728 APInt SplatBits, SplatUndef;
6729 unsigned SplatBitSize;
6730 bool HasAnyUndefs;
6731 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6732 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6733
6734 for (unsigned i = 0; i < NumSplats; ++i) {
6735 CnstBits <<= SplatBitSize;
6736 UndefBits <<= SplatBitSize;
6737 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6738 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6739 }
6740
6741 return true;
6742 }
6743
6744 return false;
6745}
6746
Evandro Menezes72f39832018-02-20 20:31:45 +00006747// Try 64-bit splatted SIMD immediate.
6748static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6749 const APInt &Bits) {
6750 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6751 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6752 EVT VT = Op.getValueType();
6753 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6754
6755 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6756 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6757
6758 SDLoc dl(Op);
6759 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6760 DAG.getConstant(Value, dl, MVT::i32));
6761 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6762 }
6763 }
6764
6765 return SDValue();
6766}
6767
6768// Try 32-bit splatted SIMD immediate.
6769static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6770 const APInt &Bits,
6771 const SDValue *LHS = nullptr) {
6772 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6773 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6774 EVT VT = Op.getValueType();
6775 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6776 bool isAdvSIMDModImm = false;
6777 uint64_t Shift;
6778
6779 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6780 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6781 Shift = 0;
6782 }
6783 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6784 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6785 Shift = 8;
6786 }
6787 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6788 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6789 Shift = 16;
6790 }
6791 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6792 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6793 Shift = 24;
6794 }
6795
6796 if (isAdvSIMDModImm) {
6797 SDLoc dl(Op);
6798 SDValue Mov;
6799
6800 if (LHS)
6801 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6802 DAG.getConstant(Value, dl, MVT::i32),
6803 DAG.getConstant(Shift, dl, MVT::i32));
6804 else
6805 Mov = DAG.getNode(NewOp, dl, MovTy,
6806 DAG.getConstant(Value, dl, MVT::i32),
6807 DAG.getConstant(Shift, dl, MVT::i32));
6808
6809 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6810 }
6811 }
6812
6813 return SDValue();
6814}
6815
6816// Try 16-bit splatted SIMD immediate.
6817static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6818 const APInt &Bits,
6819 const SDValue *LHS = nullptr) {
6820 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6821 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6822 EVT VT = Op.getValueType();
6823 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6824 bool isAdvSIMDModImm = false;
6825 uint64_t Shift;
6826
6827 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6828 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6829 Shift = 0;
6830 }
6831 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6832 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6833 Shift = 8;
6834 }
6835
6836 if (isAdvSIMDModImm) {
6837 SDLoc dl(Op);
6838 SDValue Mov;
6839
6840 if (LHS)
6841 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006842 DAG.getConstant(Value, dl, MVT::i32),
6843 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006844 else
6845 Mov = DAG.getNode(NewOp, dl, MovTy,
6846 DAG.getConstant(Value, dl, MVT::i32),
6847 DAG.getConstant(Shift, dl, MVT::i32));
6848
6849 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6850 }
6851 }
6852
6853 return SDValue();
6854}
6855
6856// Try 32-bit splatted SIMD immediate with shifted ones.
6857static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6858 SelectionDAG &DAG, const APInt &Bits) {
6859 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6860 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6861 EVT VT = Op.getValueType();
6862 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6863 bool isAdvSIMDModImm = false;
6864 uint64_t Shift;
6865
6866 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6867 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6868 Shift = 264;
6869 }
6870 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6871 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6872 Shift = 272;
6873 }
6874
6875 if (isAdvSIMDModImm) {
6876 SDLoc dl(Op);
6877 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6878 DAG.getConstant(Value, dl, MVT::i32),
6879 DAG.getConstant(Shift, dl, MVT::i32));
6880 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6881 }
6882 }
6883
6884 return SDValue();
6885}
6886
6887// Try 8-bit splatted SIMD immediate.
6888static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6889 const APInt &Bits) {
6890 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6891 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6892 EVT VT = Op.getValueType();
6893 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6894
6895 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6896 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6897
6898 SDLoc dl(Op);
6899 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6900 DAG.getConstant(Value, dl, MVT::i32));
6901 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6902 }
6903 }
6904
6905 return SDValue();
6906}
6907
6908// Try FP splatted SIMD immediate.
6909static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6910 const APInt &Bits) {
6911 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6912 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6913 EVT VT = Op.getValueType();
6914 bool isWide = (VT.getSizeInBits() == 128);
6915 MVT MovTy;
6916 bool isAdvSIMDModImm = false;
6917
6918 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6919 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6920 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6921 }
6922 else if (isWide &&
6923 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6924 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6925 MovTy = MVT::v2f64;
6926 }
6927
6928 if (isAdvSIMDModImm) {
6929 SDLoc dl(Op);
6930 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6931 DAG.getConstant(Value, dl, MVT::i32));
6932 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6933 }
6934 }
6935
6936 return SDValue();
6937}
6938
Tim Northover3b0846e2014-05-24 12:50:23 +00006939SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6940 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006941 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006942 EVT VT = Op.getValueType();
6943
Evandro Menezes72f39832018-02-20 20:31:45 +00006944 BuildVectorSDNode *BVN =
6945 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6946 if (!BVN) {
6947 // AND commutes, so try swapping the operands.
6948 LHS = Op.getOperand(1);
6949 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6950 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006951 if (!BVN)
6952 return Op;
6953
Evandro Menezes72f39832018-02-20 20:31:45 +00006954 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006955 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006956 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6957 SDValue NewOp;
6958
Tim Northover3b0846e2014-05-24 12:50:23 +00006959 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006960 DefBits = ~DefBits;
6961 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6962 DefBits, &LHS)) ||
6963 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6964 DefBits, &LHS)))
6965 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006966
6967 UndefBits = ~UndefBits;
6968 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6969 UndefBits, &LHS)) ||
6970 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6971 UndefBits, &LHS)))
6972 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006973 }
6974
Evandro Menezes72f39832018-02-20 20:31:45 +00006975 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006976 return Op;
6977}
6978
6979// Specialized code to quickly find if PotentialBVec is a BuildVector that
6980// consists of only the same constant int value, returned in reference arg
6981// ConstVal
6982static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6983 uint64_t &ConstVal) {
6984 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6985 if (!Bvec)
6986 return false;
6987 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6988 if (!FirstElt)
6989 return false;
6990 EVT VT = Bvec->getValueType(0);
6991 unsigned NumElts = VT.getVectorNumElements();
6992 for (unsigned i = 1; i < NumElts; ++i)
6993 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6994 return false;
6995 ConstVal = FirstElt->getZExtValue();
6996 return true;
6997}
6998
6999static unsigned getIntrinsicID(const SDNode *N) {
7000 unsigned Opcode = N->getOpcode();
7001 switch (Opcode) {
7002 default:
7003 return Intrinsic::not_intrinsic;
7004 case ISD::INTRINSIC_WO_CHAIN: {
7005 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7006 if (IID < Intrinsic::num_intrinsics)
7007 return IID;
7008 return Intrinsic::not_intrinsic;
7009 }
7010 }
7011}
7012
7013// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7014// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7015// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7016// Also, logical shift right -> sri, with the same structure.
7017static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7018 EVT VT = N->getValueType(0);
7019
7020 if (!VT.isVector())
7021 return SDValue();
7022
7023 SDLoc DL(N);
7024
7025 // Is the first op an AND?
7026 const SDValue And = N->getOperand(0);
7027 if (And.getOpcode() != ISD::AND)
7028 return SDValue();
7029
7030 // Is the second op an shl or lshr?
7031 SDValue Shift = N->getOperand(1);
7032 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7033 // or AArch64ISD::VLSHR vector, #shift
7034 unsigned ShiftOpc = Shift.getOpcode();
7035 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7036 return SDValue();
7037 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7038
7039 // Is the shift amount constant?
7040 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7041 if (!C2node)
7042 return SDValue();
7043
7044 // Is the and mask vector all constant?
7045 uint64_t C1;
7046 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7047 return SDValue();
7048
7049 // Is C1 == ~C2, taking into account how much one can shift elements of a
7050 // particular size?
7051 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007052 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007053 if (C2 > ElemSizeInBits)
7054 return SDValue();
7055 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7056 if ((C1 & ElemMask) != (~C2 & ElemMask))
7057 return SDValue();
7058
7059 SDValue X = And.getOperand(0);
7060 SDValue Y = Shift.getOperand(0);
7061
7062 unsigned Intrin =
7063 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7064 SDValue ResultSLI =
7065 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007066 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7067 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007068
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007069 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7070 LLVM_DEBUG(N->dump(&DAG));
7071 LLVM_DEBUG(dbgs() << "into: \n");
7072 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007073
7074 ++NumShiftInserts;
7075 return ResultSLI;
7076}
7077
7078SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7079 SelectionDAG &DAG) const {
7080 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7081 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007082 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007083 return Res;
7084 }
7085
Tim Northover3b0846e2014-05-24 12:50:23 +00007086 EVT VT = Op.getValueType();
7087
Evandro Menezescd855f72018-03-05 17:02:47 +00007088 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007089 BuildVectorSDNode *BVN =
7090 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007091 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007092 // OR commutes, so try swapping the operands.
7093 LHS = Op.getOperand(1);
7094 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007095 }
7096 if (!BVN)
7097 return Op;
7098
Evandro Menezes72f39832018-02-20 20:31:45 +00007099 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007100 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007101 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7102 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007103
Evandro Menezes72f39832018-02-20 20:31:45 +00007104 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7105 DefBits, &LHS)) ||
7106 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7107 DefBits, &LHS)))
7108 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007109
7110 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7111 UndefBits, &LHS)) ||
7112 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7113 UndefBits, &LHS)))
7114 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007115 }
7116
Evandro Menezes72f39832018-02-20 20:31:45 +00007117 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007118 return Op;
7119}
7120
Kevin Qin4473c192014-07-07 02:45:40 +00007121// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7122// be truncated to fit element width.
7123static SDValue NormalizeBuildVector(SDValue Op,
7124 SelectionDAG &DAG) {
7125 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007126 SDLoc dl(Op);
7127 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007128 EVT EltTy= VT.getVectorElementType();
7129
7130 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7131 return Op;
7132
7133 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007134 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007135 // For integer vectors, type legalization would have promoted the
7136 // operands already. Otherwise, if Op is a floating-point splat
7137 // (with operands cast to integers), then the only possibilities
7138 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007139 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007140 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007141 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007142 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007143 } else if (Lane.getNode()->isUndef()) {
7144 Lane = DAG.getUNDEF(MVT::i32);
7145 } else {
7146 assert(Lane.getValueType() == MVT::i32 &&
7147 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007148 }
7149 Ops.push_back(Lane);
7150 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007151 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007152}
7153
Evandro Menezescd855f72018-03-05 17:02:47 +00007154static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007155 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007156
Evandro Menezes72f39832018-02-20 20:31:45 +00007157 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007158 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007159 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007160 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007161 SDValue NewOp;
7162 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7163 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7164 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7165 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7166 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7167 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7168 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007169
Evandro Menezes72f39832018-02-20 20:31:45 +00007170 DefBits = ~DefBits;
7171 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7172 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7173 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7174 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007175
Evandro Menezes72f39832018-02-20 20:31:45 +00007176 DefBits = UndefBits;
7177 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7178 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7179 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7180 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7181 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7182 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7183 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007184
Evandro Menezes72f39832018-02-20 20:31:45 +00007185 DefBits = ~UndefBits;
7186 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7187 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7188 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7189 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007190 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007191
Evandro Menezescd855f72018-03-05 17:02:47 +00007192 return SDValue();
7193}
7194
7195SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7196 SelectionDAG &DAG) const {
7197 EVT VT = Op.getValueType();
7198
7199 // Try to build a simple constant vector.
7200 Op = NormalizeBuildVector(Op, DAG);
7201 if (VT.isInteger()) {
7202 // Certain vector constants, used to express things like logical NOT and
7203 // arithmetic NEG, are passed through unmodified. This allows special
7204 // patterns for these operations to match, which will lower these constants
7205 // to whatever is proven necessary.
7206 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7207 if (BVN->isConstant())
7208 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7209 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7210 APInt Val(BitSize,
7211 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7212 if (Val.isNullValue() || Val.isAllOnesValue())
7213 return Op;
7214 }
7215 }
7216
7217 if (SDValue V = ConstantBuildVector(Op, DAG))
7218 return V;
7219
Tim Northover3b0846e2014-05-24 12:50:23 +00007220 // Scan through the operands to find some interesting properties we can
7221 // exploit:
7222 // 1) If only one value is used, we can use a DUP, or
7223 // 2) if only the low element is not undef, we can just insert that, or
7224 // 3) if only one constant value is used (w/ some non-constant lanes),
7225 // we can splat the constant value into the whole vector then fill
7226 // in the non-constant lanes.
7227 // 4) FIXME: If different constant values are used, but we can intelligently
7228 // select the values we'll be overwriting for the non-constant
7229 // lanes such that we can directly materialize the vector
7230 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007231 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007232 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007233 unsigned NumElts = VT.getVectorNumElements();
7234 bool isOnlyLowElement = true;
7235 bool usesOnlyOneValue = true;
7236 bool usesOnlyOneConstantValue = true;
7237 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007238 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007239 unsigned NumConstantLanes = 0;
7240 SDValue Value;
7241 SDValue ConstantValue;
7242 for (unsigned i = 0; i < NumElts; ++i) {
7243 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007244 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7245 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007246 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007247 continue;
7248 if (i > 0)
7249 isOnlyLowElement = false;
7250 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7251 isConstant = false;
7252
7253 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7254 ++NumConstantLanes;
7255 if (!ConstantValue.getNode())
7256 ConstantValue = V;
7257 else if (ConstantValue != V)
7258 usesOnlyOneConstantValue = false;
7259 }
7260
7261 if (!Value.getNode())
7262 Value = V;
7263 else if (V != Value)
7264 usesOnlyOneValue = false;
7265 }
7266
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007267 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007268 LLVM_DEBUG(
7269 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007270 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007271 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007272
John Brawnd6e0ebe2018-11-22 11:45:23 +00007273 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7274 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7275 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7276 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007277 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7278 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007279 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007280 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007281
Sebastian Popc33af712018-03-01 15:47:39 +00007282 if (AllLanesExtractElt) {
7283 SDNode *Vector = nullptr;
7284 bool Even = false;
7285 bool Odd = false;
7286 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7287 // the Odd pattern <1,3,5,...>.
7288 for (unsigned i = 0; i < NumElts; ++i) {
7289 SDValue V = Op.getOperand(i);
7290 const SDNode *N = V.getNode();
7291 if (!isa<ConstantSDNode>(N->getOperand(1)))
7292 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007293 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007294
7295 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007296 if (!Vector) {
7297 Vector = N0.getNode();
7298 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7299 // BUILD_VECTOR.
7300 if (VT.getVectorElementType() !=
7301 N0.getValueType().getVectorElementType())
7302 break;
7303 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007304 Odd = false;
7305 Even = false;
7306 break;
7307 }
7308
7309 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7310 // indices <1,3,5,...>.
7311 uint64_t Val = N->getConstantOperandVal(1);
7312 if (Val == 2 * i) {
7313 Even = true;
7314 continue;
7315 }
7316 if (Val - 1 == 2 * i) {
7317 Odd = true;
7318 continue;
7319 }
7320
7321 // Something does not match: abort.
7322 Odd = false;
7323 Even = false;
7324 break;
7325 }
7326 if (Even || Odd) {
7327 SDValue LHS =
7328 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7329 DAG.getConstant(0, dl, MVT::i64));
7330 SDValue RHS =
7331 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7332 DAG.getConstant(NumElts, dl, MVT::i64));
7333
7334 if (Even && !Odd)
7335 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7336 RHS);
7337 if (Odd && !Even)
7338 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7339 RHS);
7340 }
7341 }
7342
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007343 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007344 // i32 and try again.
7345 if (usesOnlyOneValue) {
7346 if (!isConstant) {
7347 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007348 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007349 LLVM_DEBUG(
7350 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007351 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007352 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007353
7354 // This is actually a DUPLANExx operation, which keeps everything vectory.
7355
Tim Northover3b0846e2014-05-24 12:50:23 +00007356 SDValue Lane = Value.getOperand(1);
7357 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007358 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007359 LLVM_DEBUG(
7360 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7361 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007362 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007363 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007364
7365 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7366 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7367 }
7368
7369 if (VT.getVectorElementType().isFloatingPoint()) {
7370 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007371 EVT EltTy = VT.getVectorElementType();
7372 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7373 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007374 LLVM_DEBUG(
7375 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7376 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007377 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007378 for (unsigned i = 0; i < NumElts; ++i)
7379 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7380 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007381 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007382 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7383 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007384 Val = LowerBUILD_VECTOR(Val, DAG);
7385 if (Val.getNode())
7386 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7387 }
7388 }
7389
7390 // If there was only one constant value used and for more than one lane,
7391 // start by splatting that value, then replace the non-constant lanes. This
7392 // is better than the default, which will perform a separate initialization
7393 // for each lane.
7394 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007395 // Firstly, try to materialize the splat constant.
7396 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7397 Val = ConstantBuildVector(Vec, DAG);
7398 if (!Val) {
7399 // Otherwise, materialize the constant and splat it.
7400 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7401 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7402 }
7403
Tim Northover3b0846e2014-05-24 12:50:23 +00007404 // Now insert the non-constant lanes.
7405 for (unsigned i = 0; i < NumElts; ++i) {
7406 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007407 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007408 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007409 // Note that type legalization likely mucked about with the VT of the
7410 // source operand, so we may have to convert it here before inserting.
7411 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007412 }
7413 return Val;
7414 }
7415
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007416 // This will generate a load from the constant pool.
7417 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007418 LLVM_DEBUG(
7419 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7420 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007421 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007422 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007423
7424 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7425 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007426 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007427 return shuffle;
7428 }
7429
7430 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7431 // know the default expansion would otherwise fall back on something even
7432 // worse. For a vector with one or two non-undef values, that's
7433 // scalar_to_vector for the elements followed by a shuffle (provided the
7434 // shuffle is valid for the target) and materialization element by element
7435 // on the stack followed by a load for everything else.
7436 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007437 LLVM_DEBUG(
7438 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7439 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007440
Tim Northover3b0846e2014-05-24 12:50:23 +00007441 SDValue Vec = DAG.getUNDEF(VT);
7442 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007443 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007444
7445 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007446 // a) Avoid a RMW dependency on the full vector register, and
7447 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007448 // value is already in an S or D register, and we're forced to emit an
7449 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007450 //
7451 // We also allow types like i8 and i16 which are illegal scalar but legal
7452 // vector element types. After type-legalization the inserted value is
7453 // extended (i32) and it is safe to cast them to the vector type by ignoring
7454 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7455 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007456 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007457 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007458 ++i;
7459 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007460 LLVM_DEBUG(if (i < NumElts) dbgs()
7461 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007462 for (; i < NumElts; ++i) {
7463 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007464 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007465 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007466 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007467 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7468 }
7469 return Vec;
7470 }
7471
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007472 LLVM_DEBUG(
7473 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7474 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007475 return SDValue();
7476}
7477
7478SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7479 SelectionDAG &DAG) const {
7480 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7481
Tim Northovere4b8e132014-07-15 10:00:26 +00007482 // Check for non-constant or out of range lane.
7483 EVT VT = Op.getOperand(0).getValueType();
7484 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7485 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007486 return SDValue();
7487
Tim Northover3b0846e2014-05-24 12:50:23 +00007488
7489 // Insertion/extraction are legal for V128 types.
7490 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007491 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7492 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007493 return Op;
7494
7495 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007496 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007497 return SDValue();
7498
7499 // For V64 types, we perform insertion by expanding the value
7500 // to a V128 type and perform the insertion on that.
7501 SDLoc DL(Op);
7502 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7503 EVT WideTy = WideVec.getValueType();
7504
7505 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7506 Op.getOperand(1), Op.getOperand(2));
7507 // Re-narrow the resultant vector.
7508 return NarrowVector(Node, DAG);
7509}
7510
7511SDValue
7512AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7513 SelectionDAG &DAG) const {
7514 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7515
Tim Northovere4b8e132014-07-15 10:00:26 +00007516 // Check for non-constant or out of range lane.
7517 EVT VT = Op.getOperand(0).getValueType();
7518 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7519 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007520 return SDValue();
7521
Tim Northover3b0846e2014-05-24 12:50:23 +00007522
7523 // Insertion/extraction are legal for V128 types.
7524 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007525 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7526 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007527 return Op;
7528
7529 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007530 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007531 return SDValue();
7532
7533 // For V64 types, we perform extraction by expanding the value
7534 // to a V128 type and perform the extraction on that.
7535 SDLoc DL(Op);
7536 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7537 EVT WideTy = WideVec.getValueType();
7538
7539 EVT ExtrTy = WideTy.getVectorElementType();
7540 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7541 ExtrTy = MVT::i32;
7542
7543 // For extractions, we just return the result directly.
7544 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7545 Op.getOperand(1));
7546}
7547
7548SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7549 SelectionDAG &DAG) const {
7550 EVT VT = Op.getOperand(0).getValueType();
7551 SDLoc dl(Op);
7552 // Just in case...
7553 if (!VT.isVector())
7554 return SDValue();
7555
7556 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7557 if (!Cst)
7558 return SDValue();
7559 unsigned Val = Cst->getZExtValue();
7560
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007561 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007562
7563 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7564 if (Val == 0)
7565 return Op;
7566
Tim Northover3b0846e2014-05-24 12:50:23 +00007567 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7568 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007569 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007570 return Op;
7571
7572 return SDValue();
7573}
7574
Zvi Rackover1b736822017-07-26 08:06:58 +00007575bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007576 if (VT.getVectorNumElements() == 4 &&
7577 (VT.is128BitVector() || VT.is64BitVector())) {
7578 unsigned PFIndexes[4];
7579 for (unsigned i = 0; i != 4; ++i) {
7580 if (M[i] < 0)
7581 PFIndexes[i] = 8;
7582 else
7583 PFIndexes[i] = M[i];
7584 }
7585
7586 // Compute the index in the perfect shuffle table.
7587 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7588 PFIndexes[2] * 9 + PFIndexes[3];
7589 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7590 unsigned Cost = (PFEntry >> 30);
7591
7592 if (Cost <= 4)
7593 return true;
7594 }
7595
7596 bool DummyBool;
7597 int DummyInt;
7598 unsigned DummyUnsigned;
7599
7600 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7601 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7602 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7603 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7604 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7605 isZIPMask(M, VT, DummyUnsigned) ||
7606 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7607 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7608 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7609 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7610 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7611}
7612
7613/// getVShiftImm - Check if this is a valid build_vector for the immediate
7614/// operand of a vector shift operation, where all the elements of the
7615/// build_vector must have the same constant integer value.
7616static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7617 // Ignore bit_converts.
7618 while (Op.getOpcode() == ISD::BITCAST)
7619 Op = Op.getOperand(0);
7620 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7621 APInt SplatBits, SplatUndef;
7622 unsigned SplatBitSize;
7623 bool HasAnyUndefs;
7624 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7625 HasAnyUndefs, ElementBits) ||
7626 SplatBitSize > ElementBits)
7627 return false;
7628 Cnt = SplatBits.getSExtValue();
7629 return true;
7630}
7631
7632/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7633/// operand of a vector shift left operation. That value must be in the range:
7634/// 0 <= Value < ElementBits for a left shift; or
7635/// 0 <= Value <= ElementBits for a long left shift.
7636static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7637 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007638 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007639 if (!getVShiftImm(Op, ElementBits, Cnt))
7640 return false;
7641 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7642}
7643
7644/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007645/// operand of a vector shift right operation. The value must be in the range:
7646/// 1 <= Value <= ElementBits for a right shift; or
7647static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007648 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007649 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007650 if (!getVShiftImm(Op, ElementBits, Cnt))
7651 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007652 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7653}
7654
7655SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7656 SelectionDAG &DAG) const {
7657 EVT VT = Op.getValueType();
7658 SDLoc DL(Op);
7659 int64_t Cnt;
7660
7661 if (!Op.getOperand(1).getValueType().isVector())
7662 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007663 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007664
7665 switch (Op.getOpcode()) {
7666 default:
7667 llvm_unreachable("unexpected shift opcode");
7668
7669 case ISD::SHL:
7670 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007671 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7672 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007673 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007674 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7675 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007676 Op.getOperand(0), Op.getOperand(1));
7677 case ISD::SRA:
7678 case ISD::SRL:
7679 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007680 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007681 unsigned Opc =
7682 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007683 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7684 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007685 }
7686
7687 // Right shift register. Note, there is not a shift right register
7688 // instruction, but the shift left register instruction takes a signed
7689 // value, where negative numbers specify a right shift.
7690 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7691 : Intrinsic::aarch64_neon_ushl;
7692 // negate the shift amount
7693 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7694 SDValue NegShiftLeft =
7695 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007696 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7697 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007698 return NegShiftLeft;
7699 }
7700
7701 return SDValue();
7702}
7703
7704static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7705 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007706 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007707 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007708 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7709 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007710
7711 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7712 APInt CnstBits(VT.getSizeInBits(), 0);
7713 APInt UndefBits(VT.getSizeInBits(), 0);
7714 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7715 bool IsZero = IsCnst && (CnstBits == 0);
7716
7717 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7718 switch (CC) {
7719 default:
7720 return SDValue();
7721 case AArch64CC::NE: {
7722 SDValue Fcmeq;
7723 if (IsZero)
7724 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7725 else
7726 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7727 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7728 }
7729 case AArch64CC::EQ:
7730 if (IsZero)
7731 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7732 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7733 case AArch64CC::GE:
7734 if (IsZero)
7735 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7736 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7737 case AArch64CC::GT:
7738 if (IsZero)
7739 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7740 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7741 case AArch64CC::LS:
7742 if (IsZero)
7743 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7744 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7745 case AArch64CC::LT:
7746 if (!NoNans)
7747 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007748 // If we ignore NaNs then we can use to the MI implementation.
7749 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007750 case AArch64CC::MI:
7751 if (IsZero)
7752 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7753 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7754 }
7755 }
7756
7757 switch (CC) {
7758 default:
7759 return SDValue();
7760 case AArch64CC::NE: {
7761 SDValue Cmeq;
7762 if (IsZero)
7763 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7764 else
7765 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7766 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7767 }
7768 case AArch64CC::EQ:
7769 if (IsZero)
7770 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7771 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7772 case AArch64CC::GE:
7773 if (IsZero)
7774 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7775 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7776 case AArch64CC::GT:
7777 if (IsZero)
7778 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7779 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7780 case AArch64CC::LE:
7781 if (IsZero)
7782 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7783 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7784 case AArch64CC::LS:
7785 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7786 case AArch64CC::LO:
7787 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7788 case AArch64CC::LT:
7789 if (IsZero)
7790 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7791 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7792 case AArch64CC::HI:
7793 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7794 case AArch64CC::HS:
7795 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7796 }
7797}
7798
7799SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7800 SelectionDAG &DAG) const {
7801 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7802 SDValue LHS = Op.getOperand(0);
7803 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007804 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007805 SDLoc dl(Op);
7806
7807 if (LHS.getValueType().getVectorElementType().isInteger()) {
7808 assert(LHS.getValueType() == RHS.getValueType());
7809 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007810 SDValue Cmp =
7811 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7812 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007813 }
7814
Carey Williamsda15b5b2018-01-22 14:16:11 +00007815 const bool FullFP16 =
7816 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7817
7818 // Make v4f16 (only) fcmp operations utilise vector instructions
7819 // v8f16 support will be a litle more complicated
7820 if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7821 if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7822 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7823 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7824 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7825 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7826 CmpVT = MVT::v4i32;
7827 } else
7828 return SDValue();
7829 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007830
Tim Northover3b0846e2014-05-24 12:50:23 +00007831 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7832 LHS.getValueType().getVectorElementType() == MVT::f64);
7833
7834 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7835 // clean. Some of them require two branches to implement.
7836 AArch64CC::CondCode CC1, CC2;
7837 bool ShouldInvert;
7838 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7839
7840 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7841 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007842 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007843 if (!Cmp.getNode())
7844 return SDValue();
7845
7846 if (CC2 != AArch64CC::AL) {
7847 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007848 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007849 if (!Cmp2.getNode())
7850 return SDValue();
7851
Tim Northover45aa89c2015-02-08 00:50:47 +00007852 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007853 }
7854
Tim Northover45aa89c2015-02-08 00:50:47 +00007855 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7856
Tim Northover3b0846e2014-05-24 12:50:23 +00007857 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007858 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007859
7860 return Cmp;
7861}
7862
Amara Emersonc9916d72017-05-16 21:29:22 +00007863static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7864 SelectionDAG &DAG) {
7865 SDValue VecOp = ScalarOp.getOperand(0);
7866 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7867 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7868 DAG.getConstant(0, DL, MVT::i64));
7869}
7870
7871SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7872 SelectionDAG &DAG) const {
7873 SDLoc dl(Op);
7874 switch (Op.getOpcode()) {
7875 case ISD::VECREDUCE_ADD:
7876 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7877 case ISD::VECREDUCE_SMAX:
7878 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7879 case ISD::VECREDUCE_SMIN:
7880 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7881 case ISD::VECREDUCE_UMAX:
7882 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7883 case ISD::VECREDUCE_UMIN:
7884 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7885 case ISD::VECREDUCE_FMAX: {
7886 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7887 return DAG.getNode(
7888 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7889 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7890 Op.getOperand(0));
7891 }
7892 case ISD::VECREDUCE_FMIN: {
7893 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7894 return DAG.getNode(
7895 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7896 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7897 Op.getOperand(0));
7898 }
7899 default:
7900 llvm_unreachable("Unhandled reduction");
7901 }
7902}
7903
Oliver Stannard42699172018-02-12 14:22:03 +00007904SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7905 SelectionDAG &DAG) const {
7906 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7907 if (!Subtarget.hasLSE())
7908 return SDValue();
7909
7910 // LSE has an atomic load-add instruction, but not a load-sub.
7911 SDLoc dl(Op);
7912 MVT VT = Op.getSimpleValueType();
7913 SDValue RHS = Op.getOperand(2);
7914 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7915 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7916 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7917 Op.getOperand(0), Op.getOperand(1), RHS,
7918 AN->getMemOperand());
7919}
7920
Oliver Stannard02f08c92018-02-12 17:03:11 +00007921SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7922 SelectionDAG &DAG) const {
7923 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7924 if (!Subtarget.hasLSE())
7925 return SDValue();
7926
7927 // LSE has an atomic load-clear instruction, but not a load-and.
7928 SDLoc dl(Op);
7929 MVT VT = Op.getSimpleValueType();
7930 SDValue RHS = Op.getOperand(2);
7931 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7932 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7933 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7934 Op.getOperand(0), Op.getOperand(1), RHS,
7935 AN->getMemOperand());
7936}
7937
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007938SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7939 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7940 SDLoc dl(Op);
7941 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7942 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7943
Tri Vo6c47c622018-09-22 22:17:50 +00007944 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7945 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7946 if (Subtarget->hasCustomCallingConv())
7947 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007948
7949 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7950 DAG.getConstant(4, dl, MVT::i64));
7951 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7952 Chain =
7953 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7954 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7955 DAG.getRegisterMask(Mask), Chain.getValue(1));
7956 // To match the actual intent better, we should read the output from X15 here
7957 // again (instead of potentially spilling it to the stack), but rereading Size
7958 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7959 // here.
7960
7961 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7962 DAG.getConstant(4, dl, MVT::i64));
7963 return Chain;
7964}
7965
7966SDValue
7967AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7968 SelectionDAG &DAG) const {
7969 assert(Subtarget->isTargetWindows() &&
7970 "Only Windows alloca probing supported");
7971 SDLoc dl(Op);
7972 // Get the inputs.
7973 SDNode *Node = Op.getNode();
7974 SDValue Chain = Op.getOperand(0);
7975 SDValue Size = Op.getOperand(1);
7976 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7977 EVT VT = Node->getValueType(0);
7978
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00007979 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7980 "no-stack-arg-probe")) {
7981 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7982 Chain = SP.getValue(1);
7983 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7984 if (Align)
7985 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7986 DAG.getConstant(-(uint64_t)Align, dl, VT));
7987 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7988 SDValue Ops[2] = {SP, Chain};
7989 return DAG.getMergeValues(Ops, dl);
7990 }
7991
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007992 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7993
7994 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7995
7996 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7997 Chain = SP.getValue(1);
7998 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00007999 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008000 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8001 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00008002 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00008003
8004 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8005 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8006
8007 SDValue Ops[2] = {SP, Chain};
8008 return DAG.getMergeValues(Ops, dl);
8009}
8010
Tim Northover3b0846e2014-05-24 12:50:23 +00008011/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8012/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8013/// specified in the intrinsic calls.
8014bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8015 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00008016 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00008017 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008018 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00008019 switch (Intrinsic) {
8020 case Intrinsic::aarch64_neon_ld2:
8021 case Intrinsic::aarch64_neon_ld3:
8022 case Intrinsic::aarch64_neon_ld4:
8023 case Intrinsic::aarch64_neon_ld1x2:
8024 case Intrinsic::aarch64_neon_ld1x3:
8025 case Intrinsic::aarch64_neon_ld1x4:
8026 case Intrinsic::aarch64_neon_ld2lane:
8027 case Intrinsic::aarch64_neon_ld3lane:
8028 case Intrinsic::aarch64_neon_ld4lane:
8029 case Intrinsic::aarch64_neon_ld2r:
8030 case Intrinsic::aarch64_neon_ld3r:
8031 case Intrinsic::aarch64_neon_ld4r: {
8032 Info.opc = ISD::INTRINSIC_W_CHAIN;
8033 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008034 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008035 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8036 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8037 Info.offset = 0;
8038 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008039 // volatile loads with NEON intrinsics not supported
8040 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008041 return true;
8042 }
8043 case Intrinsic::aarch64_neon_st2:
8044 case Intrinsic::aarch64_neon_st3:
8045 case Intrinsic::aarch64_neon_st4:
8046 case Intrinsic::aarch64_neon_st1x2:
8047 case Intrinsic::aarch64_neon_st1x3:
8048 case Intrinsic::aarch64_neon_st1x4:
8049 case Intrinsic::aarch64_neon_st2lane:
8050 case Intrinsic::aarch64_neon_st3lane:
8051 case Intrinsic::aarch64_neon_st4lane: {
8052 Info.opc = ISD::INTRINSIC_VOID;
8053 // Conservatively set memVT to the entire set of vectors stored.
8054 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008055 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008056 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8057 if (!ArgTy->isVectorTy())
8058 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008059 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008060 }
8061 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8062 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8063 Info.offset = 0;
8064 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008065 // volatile stores with NEON intrinsics not supported
8066 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008067 return true;
8068 }
8069 case Intrinsic::aarch64_ldaxr:
8070 case Intrinsic::aarch64_ldxr: {
8071 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8072 Info.opc = ISD::INTRINSIC_W_CHAIN;
8073 Info.memVT = MVT::getVT(PtrTy->getElementType());
8074 Info.ptrVal = I.getArgOperand(0);
8075 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008076 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008077 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008078 return true;
8079 }
8080 case Intrinsic::aarch64_stlxr:
8081 case Intrinsic::aarch64_stxr: {
8082 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8083 Info.opc = ISD::INTRINSIC_W_CHAIN;
8084 Info.memVT = MVT::getVT(PtrTy->getElementType());
8085 Info.ptrVal = I.getArgOperand(1);
8086 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008087 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008088 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008089 return true;
8090 }
8091 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008092 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008093 Info.opc = ISD::INTRINSIC_W_CHAIN;
8094 Info.memVT = MVT::i128;
8095 Info.ptrVal = I.getArgOperand(0);
8096 Info.offset = 0;
8097 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008098 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008099 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008100 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008101 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008102 Info.opc = ISD::INTRINSIC_W_CHAIN;
8103 Info.memVT = MVT::i128;
8104 Info.ptrVal = I.getArgOperand(2);
8105 Info.offset = 0;
8106 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008107 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008108 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008109 default:
8110 break;
8111 }
8112
8113 return false;
8114}
8115
John Brawne3b44f92018-03-23 14:47:07 +00008116bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8117 ISD::LoadExtType ExtTy,
8118 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008119 // TODO: This may be worth removing. Check regression tests for diffs.
8120 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8121 return false;
8122
John Brawne3b44f92018-03-23 14:47:07 +00008123 // If we're reducing the load width in order to avoid having to use an extra
8124 // instruction to do extension then it's probably a good idea.
8125 if (ExtTy != ISD::NON_EXTLOAD)
8126 return true;
8127 // Don't reduce load width if it would prevent us from combining a shift into
8128 // the offset.
8129 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8130 assert(Mem);
8131 const SDValue &Base = Mem->getBasePtr();
8132 if (Base.getOpcode() == ISD::ADD &&
8133 Base.getOperand(1).getOpcode() == ISD::SHL &&
8134 Base.getOperand(1).hasOneUse() &&
8135 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8136 // The shift can be combined if it matches the size of the value being
8137 // loaded (and so reducing the width would make it not match).
8138 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8139 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8140 if (ShiftAmount == Log2_32(LoadBytes))
8141 return false;
8142 }
8143 // We have no reason to disallow reducing the load width, so allow it.
8144 return true;
8145}
8146
Tim Northover3b0846e2014-05-24 12:50:23 +00008147// Truncations from 64-bit GPR to 32-bit GPR is free.
8148bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8149 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8150 return false;
8151 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8152 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008153 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008154}
8155bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008156 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008157 return false;
8158 unsigned NumBits1 = VT1.getSizeInBits();
8159 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008160 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008161}
8162
Chad Rosier54390052015-02-23 19:15:16 +00008163/// Check if it is profitable to hoist instruction in then/else to if.
8164/// Not profitable if I and it's user can form a FMA instruction
8165/// because we prefer FMSUB/FMADD.
8166bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8167 if (I->getOpcode() != Instruction::FMul)
8168 return true;
8169
Davide Italiano3e9986f2017-04-18 00:29:54 +00008170 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008171 return true;
8172
8173 Instruction *User = I->user_back();
8174
8175 if (User &&
8176 !(User->getOpcode() == Instruction::FSub ||
8177 User->getOpcode() == Instruction::FAdd))
8178 return true;
8179
8180 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008181 const DataLayout &DL = I->getModule()->getDataLayout();
8182 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008183
Eric Christopher114fa1c2016-02-29 22:50:49 +00008184 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8185 isOperationLegalOrCustom(ISD::FMA, VT) &&
8186 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8187 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008188}
8189
Tim Northover3b0846e2014-05-24 12:50:23 +00008190// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8191// 64-bit GPR.
8192bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8193 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8194 return false;
8195 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8196 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008197 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008198}
8199bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008200 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008201 return false;
8202 unsigned NumBits1 = VT1.getSizeInBits();
8203 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008204 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008205}
8206
8207bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8208 EVT VT1 = Val.getValueType();
8209 if (isZExtFree(VT1, VT2)) {
8210 return true;
8211 }
8212
8213 if (Val.getOpcode() != ISD::LOAD)
8214 return false;
8215
8216 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008217 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8218 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8219 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008220}
8221
Quentin Colombet6843ac42015-03-31 20:52:32 +00008222bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8223 if (isa<FPExtInst>(Ext))
8224 return false;
8225
Haicheng Wu50692a22017-08-01 21:26:45 +00008226 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008227 if (Ext->getType()->isVectorTy())
8228 return false;
8229
8230 for (const Use &U : Ext->uses()) {
8231 // The extension is free if we can fold it with a left shift in an
8232 // addressing mode or an arithmetic operation: add, sub, and cmp.
8233
8234 // Is there a shift?
8235 const Instruction *Instr = cast<Instruction>(U.getUser());
8236
8237 // Is this a constant shift?
8238 switch (Instr->getOpcode()) {
8239 case Instruction::Shl:
8240 if (!isa<ConstantInt>(Instr->getOperand(1)))
8241 return false;
8242 break;
8243 case Instruction::GetElementPtr: {
8244 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008245 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008246 std::advance(GTI, U.getOperandNo()-1);
8247 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008248 // This extension will end up with a shift because of the scaling factor.
8249 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8250 // Get the shift amount based on the scaling factor:
8251 // log2(sizeof(IdxTy)) - log2(8).
8252 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008253 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008254 // Is the constant foldable in the shift of the addressing mode?
8255 // I.e., shift amount is between 1 and 4 inclusive.
8256 if (ShiftAmt == 0 || ShiftAmt > 4)
8257 return false;
8258 break;
8259 }
8260 case Instruction::Trunc:
8261 // Check if this is a noop.
8262 // trunc(sext ty1 to ty2) to ty1.
8263 if (Instr->getType() == Ext->getOperand(0)->getType())
8264 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008265 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008266 default:
8267 return false;
8268 }
8269
8270 // At this point we can use the bfm family, so this extension is free
8271 // for that use.
8272 }
8273 return true;
8274}
8275
Florian Hahn3b251962019-02-05 10:27:40 +00008276/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8277/// or upper half of the vector elements.
8278static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8279 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8280 auto *FullVT = cast<VectorType>(FullV->getType());
8281 auto *HalfVT = cast<VectorType>(HalfV->getType());
8282 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8283 };
8284
8285 auto extractHalf = [](Value *FullV, Value *HalfV) {
8286 auto *FullVT = cast<VectorType>(FullV->getType());
8287 auto *HalfVT = cast<VectorType>(HalfV->getType());
8288 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8289 };
8290
8291 Constant *M1, *M2;
8292 Value *S1Op1, *S2Op1;
8293 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8294 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8295 return false;
8296
8297 // Check that the operands are half as wide as the result and we extract
8298 // half of the elements of the input vectors.
8299 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8300 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8301 return false;
8302
8303 // Check the mask extracts either the lower or upper half of vector
8304 // elements.
8305 int M1Start = -1;
8306 int M2Start = -1;
8307 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8308 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8309 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8310 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8311 return false;
8312
8313 return true;
8314}
8315
8316/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8317/// of the vector elements.
8318static bool areExtractExts(Value *Ext1, Value *Ext2) {
8319 auto areExtDoubled = [](Instruction *Ext) {
8320 return Ext->getType()->getScalarSizeInBits() ==
8321 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8322 };
8323
8324 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8325 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8326 !areExtDoubled(cast<Instruction>(Ext1)) ||
8327 !areExtDoubled(cast<Instruction>(Ext2)))
8328 return false;
8329
8330 return true;
8331}
8332
8333/// Check if sinking \p I's operands to I's basic block is profitable, because
8334/// the operands can be folded into a target instruction, e.g.
8335/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8336bool AArch64TargetLowering::shouldSinkOperands(
8337 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8338 if (!I->getType()->isVectorTy())
8339 return false;
8340
8341 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8342 switch (II->getIntrinsicID()) {
8343 case Intrinsic::aarch64_neon_umull:
8344 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8345 return false;
8346 Ops.push_back(&II->getOperandUse(0));
8347 Ops.push_back(&II->getOperandUse(1));
8348 return true;
8349 default:
8350 return false;
8351 }
8352 }
8353
8354 switch (I->getOpcode()) {
8355 case Instruction::Sub:
8356 case Instruction::Add: {
8357 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8358 return false;
8359
8360 // If the exts' operands extract either the lower or upper elements, we
8361 // can sink them too.
8362 auto Ext1 = cast<Instruction>(I->getOperand(0));
8363 auto Ext2 = cast<Instruction>(I->getOperand(1));
8364 if (areExtractShuffleVectors(Ext1, Ext2)) {
8365 Ops.push_back(&Ext1->getOperandUse(0));
8366 Ops.push_back(&Ext2->getOperandUse(0));
8367 }
8368
8369 Ops.push_back(&I->getOperandUse(0));
8370 Ops.push_back(&I->getOperandUse(1));
8371
8372 return true;
8373 }
8374 default:
8375 return false;
8376 }
8377 return false;
8378}
8379
Tim Northover3b0846e2014-05-24 12:50:23 +00008380bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8381 unsigned &RequiredAligment) const {
8382 if (!LoadedType.isSimple() ||
8383 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8384 return false;
8385 // Cyclone supports unaligned accesses.
8386 RequiredAligment = 0;
8387 unsigned NumBits = LoadedType.getSizeInBits();
8388 return NumBits == 32 || NumBits == 64;
8389}
8390
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008391/// A helper function for determining the number of interleaved accesses we
8392/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008393unsigned
8394AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8395 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008396 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8397}
8398
Geoff Berryb1e87142017-07-14 21:44:12 +00008399MachineMemOperand::Flags
8400AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8401 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8402 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8403 return MOStridedAccess;
8404 return MachineMemOperand::MONone;
8405}
8406
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008407bool AArch64TargetLowering::isLegalInterleavedAccessType(
8408 VectorType *VecTy, const DataLayout &DL) const {
8409
8410 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8411 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8412
8413 // Ensure the number of vector elements is greater than 1.
8414 if (VecTy->getNumElements() < 2)
8415 return false;
8416
8417 // Ensure the element type is legal.
8418 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8419 return false;
8420
8421 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8422 // 128 will be split into multiple interleaved accesses.
8423 return VecSize == 64 || VecSize % 128 == 0;
8424}
8425
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008426/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008427///
8428/// E.g. Lower an interleaved load (Factor = 2):
8429/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8430/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8431/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8432///
8433/// Into:
8434/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8435/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8436/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8437bool AArch64TargetLowering::lowerInterleavedLoad(
8438 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8439 ArrayRef<unsigned> Indices, unsigned Factor) const {
8440 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8441 "Invalid interleave factor");
8442 assert(!Shuffles.empty() && "Empty shufflevector input");
8443 assert(Shuffles.size() == Indices.size() &&
8444 "Unmatched number of shufflevectors and indices");
8445
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008446 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008447
8448 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008449
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008450 // Skip if we do not have NEON and skip illegal vector types. We can
8451 // "legalize" wide vector types into multiple interleaved accesses as long as
8452 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008453 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008454 return false;
8455
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008456 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8457
Hao Liu7ec8ee32015-06-26 02:32:07 +00008458 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8459 // load integer vectors first and then convert to pointer vectors.
8460 Type *EltTy = VecTy->getVectorElementType();
8461 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008462 VecTy =
8463 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008464
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008465 IRBuilder<> Builder(LI);
8466
8467 // The base address of the load.
8468 Value *BaseAddr = LI->getPointerOperand();
8469
8470 if (NumLoads > 1) {
8471 // If we're going to generate more than one load, reset the sub-vector type
8472 // to something legal.
8473 VecTy = VectorType::get(VecTy->getVectorElementType(),
8474 VecTy->getVectorNumElements() / NumLoads);
8475
8476 // We will compute the pointer operand of each load from the original base
8477 // address using GEPs. Cast the base address to a pointer to the scalar
8478 // element type.
8479 BaseAddr = Builder.CreateBitCast(
8480 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8481 LI->getPointerAddressSpace()));
8482 }
8483
Hao Liu7ec8ee32015-06-26 02:32:07 +00008484 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8485 Type *Tys[2] = {VecTy, PtrTy};
8486 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8487 Intrinsic::aarch64_neon_ld3,
8488 Intrinsic::aarch64_neon_ld4};
8489 Function *LdNFunc =
8490 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8491
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008492 // Holds sub-vectors extracted from the load intrinsic return values. The
8493 // sub-vectors are associated with the shufflevector instructions they will
8494 // replace.
8495 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008496
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008497 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008498
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008499 // If we're generating more than one load, compute the base address of
8500 // subsequent loads as an offset from the previous.
8501 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008502 BaseAddr =
8503 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8504 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008505
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008506 CallInst *LdN = Builder.CreateCall(
8507 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008508
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008509 // Extract and store the sub-vectors returned by the load intrinsic.
8510 for (unsigned i = 0; i < Shuffles.size(); i++) {
8511 ShuffleVectorInst *SVI = Shuffles[i];
8512 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008513
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008514 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8515
8516 // Convert the integer vector to pointer vector if the element is pointer.
8517 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008518 SubVec = Builder.CreateIntToPtr(
8519 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8520 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008521 SubVecs[SVI].push_back(SubVec);
8522 }
8523 }
8524
8525 // Replace uses of the shufflevector instructions with the sub-vectors
8526 // returned by the load intrinsic. If a shufflevector instruction is
8527 // associated with more than one sub-vector, those sub-vectors will be
8528 // concatenated into a single wide vector.
8529 for (ShuffleVectorInst *SVI : Shuffles) {
8530 auto &SubVec = SubVecs[SVI];
8531 auto *WideVec =
8532 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8533 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008534 }
8535
8536 return true;
8537}
8538
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008539/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008540///
8541/// E.g. Lower an interleaved store (Factor = 3):
8542/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008543/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008544/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8545///
8546/// Into:
8547/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8548/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8549/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8550/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8551///
8552/// Note that the new shufflevectors will be removed and we'll only generate one
8553/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008554///
8555/// Example for a more general valid mask (Factor 3). Lower:
8556/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8557/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8558/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8559///
8560/// Into:
8561/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8562/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8563/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8564/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008565bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8566 ShuffleVectorInst *SVI,
8567 unsigned Factor) const {
8568 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8569 "Invalid interleave factor");
8570
8571 VectorType *VecTy = SVI->getType();
8572 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8573 "Invalid interleaved store");
8574
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008575 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008576 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008577 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008578
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008579 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008580
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008581 // Skip if we do not have NEON and skip illegal vector types. We can
8582 // "legalize" wide vector types into multiple interleaved accesses as long as
8583 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008584 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008585 return false;
8586
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008587 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8588
Hao Liu7ec8ee32015-06-26 02:32:07 +00008589 Value *Op0 = SVI->getOperand(0);
8590 Value *Op1 = SVI->getOperand(1);
8591 IRBuilder<> Builder(SI);
8592
8593 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8594 // vectors to integer vectors.
8595 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008596 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008597 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008598
8599 // Convert to the corresponding integer vector.
8600 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8601 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8602 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8603
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008604 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008605 }
8606
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008607 // The base address of the store.
8608 Value *BaseAddr = SI->getPointerOperand();
8609
8610 if (NumStores > 1) {
8611 // If we're going to generate more than one store, reset the lane length
8612 // and sub-vector type to something legal.
8613 LaneLen /= NumStores;
8614 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8615
8616 // We will compute the pointer operand of each store from the original base
8617 // address using GEPs. Cast the base address to a pointer to the scalar
8618 // element type.
8619 BaseAddr = Builder.CreateBitCast(
8620 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8621 SI->getPointerAddressSpace()));
8622 }
8623
8624 auto Mask = SVI->getShuffleMask();
8625
Hao Liu7ec8ee32015-06-26 02:32:07 +00008626 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8627 Type *Tys[2] = {SubVecTy, PtrTy};
8628 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8629 Intrinsic::aarch64_neon_st3,
8630 Intrinsic::aarch64_neon_st4};
8631 Function *StNFunc =
8632 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8633
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008634 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008635
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008636 SmallVector<Value *, 5> Ops;
8637
8638 // Split the shufflevector operands into sub vectors for the new stN call.
8639 for (unsigned i = 0; i < Factor; i++) {
8640 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8641 if (Mask[IdxI] >= 0) {
8642 Ops.push_back(Builder.CreateShuffleVector(
8643 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8644 } else {
8645 unsigned StartMask = 0;
8646 for (unsigned j = 1; j < LaneLen; j++) {
8647 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8648 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8649 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8650 break;
8651 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008652 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008653 // Note: Filling undef gaps with random elements is ok, since
8654 // those elements were being written anyway (with undefs).
8655 // In the case of all undefs we're defaulting to using elems from 0
8656 // Note: StartMask cannot be negative, it's checked in
8657 // isReInterleaveMask
8658 Ops.push_back(Builder.CreateShuffleVector(
8659 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008660 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008661 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008662
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008663 // If we generating more than one store, we compute the base address of
8664 // subsequent stores as an offset from the previous.
8665 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008666 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8667 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008668
8669 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8670 Builder.CreateCall(StNFunc, Ops);
8671 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008672 return true;
8673}
8674
Tim Northover3b0846e2014-05-24 12:50:23 +00008675static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8676 unsigned AlignCheck) {
8677 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8678 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8679}
8680
8681EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8682 unsigned SrcAlign, bool IsMemset,
8683 bool ZeroMemset,
8684 bool MemcpyStrSrc,
8685 MachineFunction &MF) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008686 const Function &F = MF.getFunction();
JF Bastien29200612018-09-06 16:03:32 +00008687 bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8688 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8689 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8690 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8691 // taken one instruction to materialize the v2i64 zero and one store (with
8692 // restrictive addressing mode). Just do i64 stores.
8693 bool IsSmallMemset = IsMemset && Size < 32;
8694 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8695 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8696 return true;
8697 bool Fast;
8698 return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8699 };
8700
8701 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8702 AlignmentIsAcceptable(MVT::v2i64, 16))
8703 return MVT::v2i64;
8704 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008705 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008706 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008707 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008708 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008709 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008710 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008711}
8712
8713// 12-bit optionally shifted immediates are legal for adds.
8714bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008715 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008716 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8717 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008718 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008719 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008720 // Same encoding for add/sub, just flip the sign.
8721 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008722 bool IsLegal = ((Immed >> 12) == 0 ||
8723 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008724 LLVM_DEBUG(dbgs() << "Is " << Immed
8725 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008726 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008727}
8728
8729// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8730// immediates is the same as for an add or a sub.
8731bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008732 return isLegalAddImmediate(Immed);
8733}
8734
8735/// isLegalAddressingMode - Return true if the addressing mode represented
8736/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008737bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8738 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008739 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008740 // AArch64 has five basic addressing modes:
8741 // reg
8742 // reg + 9-bit signed offset
8743 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8744 // reg1 + reg2
8745 // reg + SIZE_IN_BYTES * reg
8746
8747 // No global is ever allowed as a base.
8748 if (AM.BaseGV)
8749 return false;
8750
8751 // No reg+reg+imm addressing.
8752 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8753 return false;
8754
8755 // check reg + imm case:
8756 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8757 uint64_t NumBytes = 0;
8758 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008759 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008760 NumBytes = NumBits / 8;
8761 if (!isPowerOf2_64(NumBits))
8762 NumBytes = 0;
8763 }
8764
8765 if (!AM.Scale) {
8766 int64_t Offset = AM.BaseOffs;
8767
8768 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008769 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008770 return true;
8771
8772 // 12-bit unsigned offset
8773 unsigned shift = Log2_64(NumBytes);
8774 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8775 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8776 (Offset >> shift) << shift == Offset)
8777 return true;
8778 return false;
8779 }
8780
8781 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8782
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008783 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008784}
8785
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008786bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8787 // Consider splitting large offset of struct or array.
8788 return true;
8789}
8790
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008791int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8792 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008793 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008794 // Scaling factors are not free at all.
8795 // Operands | Rt Latency
8796 // -------------------------------------------
8797 // Rt, [Xn, Xm] | 4
8798 // -------------------------------------------
8799 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8800 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008801 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008802 // Scale represents reg2 * scale, thus account for 1 if
8803 // it is not equal to 0 or 1.
8804 return AM.Scale != 0 && AM.Scale != 1;
8805 return -1;
8806}
8807
8808bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8809 VT = VT.getScalarType();
8810
8811 if (!VT.isSimple())
8812 return false;
8813
8814 switch (VT.getSimpleVT().SimpleTy) {
8815 case MVT::f32:
8816 case MVT::f64:
8817 return true;
8818 default:
8819 break;
8820 }
8821
8822 return false;
8823}
8824
8825const MCPhysReg *
8826AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8827 // LR is a callee-save register, but we must treat it as clobbered by any call
8828 // site. Hence we include LR in the scratch registers, which are in turn added
8829 // as implicit-defs for stackmaps and patchpoints.
8830 static const MCPhysReg ScratchRegs[] = {
8831 AArch64::X16, AArch64::X17, AArch64::LR, 0
8832 };
8833 return ScratchRegs;
8834}
8835
8836bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008837AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8838 CombineLevel Level) const {
8839 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008840 EVT VT = N->getValueType(0);
8841 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8842 // it with shift to let it be lowered to UBFX.
8843 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8844 isa<ConstantSDNode>(N->getOperand(1))) {
8845 uint64_t TruncMask = N->getConstantOperandVal(1);
8846 if (isMask_64(TruncMask) &&
8847 N->getOperand(0).getOpcode() == ISD::SRL &&
8848 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8849 return false;
8850 }
8851 return true;
8852}
8853
8854bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8855 Type *Ty) const {
8856 assert(Ty->isIntegerTy());
8857
8858 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8859 if (BitSize == 0)
8860 return false;
8861
8862 int64_t Val = Imm.getSExtValue();
8863 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8864 return true;
8865
8866 if ((int64_t)Val < 0)
8867 Val = ~Val;
8868 if (BitSize == 32)
8869 Val &= (1LL << 32) - 1;
8870
8871 unsigned LZ = countLeadingZeros((uint64_t)Val);
8872 unsigned Shift = (63 - LZ) / 16;
8873 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008874 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008875}
8876
Sebastian Pop41073e82018-03-06 16:54:55 +00008877bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8878 unsigned Index) const {
8879 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8880 return false;
8881
8882 return (Index == 0 || Index == ResVT.getVectorNumElements());
8883}
8884
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008885/// Turn vector tests of the signbit in the form of:
8886/// xor (sra X, elt_size(X)-1), -1
8887/// into:
8888/// cmge X, X, #0
8889static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8890 const AArch64Subtarget *Subtarget) {
8891 EVT VT = N->getValueType(0);
8892 if (!Subtarget->hasNEON() || !VT.isVector())
8893 return SDValue();
8894
8895 // There must be a shift right algebraic before the xor, and the xor must be a
8896 // 'not' operation.
8897 SDValue Shift = N->getOperand(0);
8898 SDValue Ones = N->getOperand(1);
8899 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8900 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8901 return SDValue();
8902
8903 // The shift should be smearing the sign bit across each vector element.
8904 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8905 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8906 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8907 return SDValue();
8908
8909 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8910}
8911
Tim Northover3b0846e2014-05-24 12:50:23 +00008912// Generate SUBS and CSEL for integer abs.
8913static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8914 EVT VT = N->getValueType(0);
8915
8916 SDValue N0 = N->getOperand(0);
8917 SDValue N1 = N->getOperand(1);
8918 SDLoc DL(N);
8919
8920 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8921 // and change it to SUB and CSEL.
8922 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8923 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8924 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8925 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8926 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008927 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008928 N0.getOperand(0));
8929 // Generate SUBS & CSEL.
8930 SDValue Cmp =
8931 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008932 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008933 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008934 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008935 SDValue(Cmp.getNode(), 1));
8936 }
8937 return SDValue();
8938}
8939
Tim Northover3b0846e2014-05-24 12:50:23 +00008940static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8941 TargetLowering::DAGCombinerInfo &DCI,
8942 const AArch64Subtarget *Subtarget) {
8943 if (DCI.isBeforeLegalizeOps())
8944 return SDValue();
8945
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008946 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8947 return Cmp;
8948
Tim Northover3b0846e2014-05-24 12:50:23 +00008949 return performIntegerAbsCombine(N, DAG);
8950}
8951
Chad Rosier17020f92014-07-23 14:57:52 +00008952SDValue
8953AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8954 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00008955 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008956 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008957 if (isIntDivCheap(N->getValueType(0), Attr))
8958 return SDValue(N,0); // Lower SDIV as SDIV
8959
Chad Rosier17020f92014-07-23 14:57:52 +00008960 // fold (sdiv X, pow2)
8961 EVT VT = N->getValueType(0);
8962 if ((VT != MVT::i32 && VT != MVT::i64) ||
8963 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8964 return SDValue();
8965
8966 SDLoc DL(N);
8967 SDValue N0 = N->getOperand(0);
8968 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008969 SDValue Zero = DAG.getConstant(0, DL, VT);
8970 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008971
8972 // Add (N0 < 0) ? Pow2 - 1 : 0;
8973 SDValue CCVal;
8974 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8975 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8976 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8977
Craig Toppera568a272018-07-30 21:04:34 +00008978 Created.push_back(Cmp.getNode());
8979 Created.push_back(Add.getNode());
8980 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00008981
8982 // Divide by pow2.
8983 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008984 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008985
8986 // If we're dividing by a positive value, we're done. Otherwise, we must
8987 // negate the result.
8988 if (Divisor.isNonNegative())
8989 return SRA;
8990
Craig Toppera568a272018-07-30 21:04:34 +00008991 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008992 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008993}
8994
Tim Northover3b0846e2014-05-24 12:50:23 +00008995static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8996 TargetLowering::DAGCombinerInfo &DCI,
8997 const AArch64Subtarget *Subtarget) {
8998 if (DCI.isBeforeLegalizeOps())
8999 return SDValue();
9000
Chad Rosier31ee8132016-11-11 17:07:37 +00009001 // The below optimizations require a constant RHS.
9002 if (!isa<ConstantSDNode>(N->getOperand(1)))
9003 return SDValue();
9004
9005 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9006 const APInt &ConstValue = C->getAPIntValue();
9007
Tim Northover3b0846e2014-05-24 12:50:23 +00009008 // Multiplication of a power of two plus/minus one can be done more
9009 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9010 // future CPUs have a cheaper MADD instruction, this may need to be
9011 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9012 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009013 // More aggressively, some multiplications N0 * C can be lowered to
9014 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9015 // e.g. 6=3*2=(2+1)*2.
9016 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9017 // which equals to (1+2)*16-(1+2).
9018 SDValue N0 = N->getOperand(0);
9019 // TrailingZeroes is used to test if the mul can be lowered to
9020 // shift+add+shift.
9021 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9022 if (TrailingZeroes) {
9023 // Conservatively do not lower to shift+add+shift if the mul might be
9024 // folded into smul or umul.
9025 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9026 isZeroExtended(N0.getNode(), DAG)))
9027 return SDValue();
9028 // Conservatively do not lower to shift+add+shift if the mul might be
9029 // folded into madd or msub.
9030 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9031 N->use_begin()->getOpcode() == ISD::SUB))
9032 return SDValue();
9033 }
9034 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9035 // and shift+add+shift.
9036 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9037
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009038 unsigned ShiftAmt, AddSubOpc;
9039 // Is the shifted value the LHS operand of the add/sub?
9040 bool ShiftValUseIsN0 = true;
9041 // Do we need to negate the result?
9042 bool NegateResult = false;
9043
Chad Rosier31ee8132016-11-11 17:07:37 +00009044 if (ConstValue.isNonNegative()) {
9045 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00009046 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00009047 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9048 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009049 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00009050 if (SCVMinus1.isPowerOf2()) {
9051 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009052 AddSubOpc = ISD::ADD;
9053 } else if (CVPlus1.isPowerOf2()) {
9054 ShiftAmt = CVPlus1.logBase2();
9055 AddSubOpc = ISD::SUB;
9056 } else
9057 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00009058 } else {
9059 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00009060 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009061 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009062 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009063 if (CVNegPlus1.isPowerOf2()) {
9064 ShiftAmt = CVNegPlus1.logBase2();
9065 AddSubOpc = ISD::SUB;
9066 ShiftValUseIsN0 = false;
9067 } else if (CVNegMinus1.isPowerOf2()) {
9068 ShiftAmt = CVNegMinus1.logBase2();
9069 AddSubOpc = ISD::ADD;
9070 NegateResult = true;
9071 } else
9072 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009073 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009074
9075 SDLoc DL(N);
9076 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009077 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009078 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9079
9080 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9081 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9082 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009083 assert(!(NegateResult && TrailingZeroes) &&
9084 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009085 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009086 if (NegateResult)
9087 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9088 // Shift the result.
9089 if (TrailingZeroes)
9090 return DAG.getNode(ISD::SHL, DL, VT, Res,
9091 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9092 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00009093}
9094
Jim Grosbachf7502c42014-07-18 00:40:52 +00009095static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9096 SelectionDAG &DAG) {
9097 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9098 // optimize away operation when it's from a constant.
9099 //
9100 // The general transformation is:
9101 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9102 // AND(VECTOR_CMP(x,y), constant2)
9103 // constant2 = UNARYOP(constant)
9104
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009105 // Early exit if this isn't a vector operation, the operand of the
9106 // unary operation isn't a bitwise AND, or if the sizes of the operations
9107 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009108 EVT VT = N->getValueType(0);
9109 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009110 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9111 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009112 return SDValue();
9113
Jim Grosbach724e4382014-07-23 20:41:43 +00009114 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009115 // make the transformation for non-constant splats as well, but it's unclear
9116 // that would be a benefit as it would not eliminate any operations, just
9117 // perform one more step in scalar code before moving to the vector unit.
9118 if (BuildVectorSDNode *BV =
9119 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009120 // Bail out if the vector isn't a constant.
9121 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009122 return SDValue();
9123
9124 // Everything checks out. Build up the new and improved node.
9125 SDLoc DL(N);
9126 EVT IntVT = BV->getValueType(0);
9127 // Create a new constant of the appropriate type for the transformed
9128 // DAG.
9129 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9130 // The AND node needs bitcasts to/from an integer vector type around it.
9131 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9132 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9133 N->getOperand(0)->getOperand(0), MaskConst);
9134 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9135 return Res;
9136 }
9137
9138 return SDValue();
9139}
9140
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009141static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9142 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009143 // First try to optimize away the conversion when it's conditionally from
9144 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009145 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009146 return Res;
9147
Tim Northover3b0846e2014-05-24 12:50:23 +00009148 EVT VT = N->getValueType(0);
9149 if (VT != MVT::f32 && VT != MVT::f64)
9150 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009151
Tim Northover3b0846e2014-05-24 12:50:23 +00009152 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009153 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009154 return SDValue();
9155
9156 // If the result of an integer load is only used by an integer-to-float
9157 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009158 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009159 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009160 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009161 // Do not change the width of a volatile load.
9162 !cast<LoadSDNode>(N0)->isVolatile()) {
9163 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9164 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009165 LN0->getPointerInfo(), LN0->getAlignment(),
9166 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009167
9168 // Make sure successors of the original load stay after it by updating them
9169 // to use the new Chain.
9170 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9171
9172 unsigned Opcode =
9173 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9174 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9175 }
9176
9177 return SDValue();
9178}
9179
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009180/// Fold a floating-point multiply by power of two into floating-point to
9181/// fixed-point conversion.
9182static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009183 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009184 const AArch64Subtarget *Subtarget) {
9185 if (!Subtarget->hasNEON())
9186 return SDValue();
9187
9188 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009189 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9190 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009191 return SDValue();
9192
9193 SDValue ConstVec = Op->getOperand(1);
9194 if (!isa<BuildVectorSDNode>(ConstVec))
9195 return SDValue();
9196
9197 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9198 uint32_t FloatBits = FloatTy.getSizeInBits();
9199 if (FloatBits != 32 && FloatBits != 64)
9200 return SDValue();
9201
9202 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9203 uint32_t IntBits = IntTy.getSizeInBits();
9204 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9205 return SDValue();
9206
9207 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9208 if (IntBits > FloatBits)
9209 return SDValue();
9210
9211 BitVector UndefElements;
9212 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9213 int32_t Bits = IntBits == 64 ? 64 : 32;
9214 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9215 if (C == -1 || C == 0 || C > Bits)
9216 return SDValue();
9217
9218 MVT ResTy;
9219 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9220 switch (NumLanes) {
9221 default:
9222 return SDValue();
9223 case 2:
9224 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9225 break;
9226 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009227 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009228 break;
9229 }
9230
Silviu Barangafa00ba32016-08-08 13:13:57 +00009231 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9232 return SDValue();
9233
9234 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9235 "Illegal vector type after legalization");
9236
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009237 SDLoc DL(N);
9238 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9239 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9240 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9241 SDValue FixConv =
9242 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9243 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9244 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9245 // We can handle smaller integers by generating an extra trunc.
9246 if (IntBits < FloatBits)
9247 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9248
9249 return FixConv;
9250}
9251
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009252/// Fold a floating-point divide by power of two into fixed-point to
9253/// floating-point conversion.
9254static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009255 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009256 const AArch64Subtarget *Subtarget) {
9257 if (!Subtarget->hasNEON())
9258 return SDValue();
9259
9260 SDValue Op = N->getOperand(0);
9261 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009262 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9263 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009264 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9265 return SDValue();
9266
9267 SDValue ConstVec = N->getOperand(1);
9268 if (!isa<BuildVectorSDNode>(ConstVec))
9269 return SDValue();
9270
9271 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9272 int32_t IntBits = IntTy.getSizeInBits();
9273 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9274 return SDValue();
9275
9276 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9277 int32_t FloatBits = FloatTy.getSizeInBits();
9278 if (FloatBits != 32 && FloatBits != 64)
9279 return SDValue();
9280
9281 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9282 if (IntBits > FloatBits)
9283 return SDValue();
9284
9285 BitVector UndefElements;
9286 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9287 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9288 if (C == -1 || C == 0 || C > FloatBits)
9289 return SDValue();
9290
9291 MVT ResTy;
9292 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9293 switch (NumLanes) {
9294 default:
9295 return SDValue();
9296 case 2:
9297 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9298 break;
9299 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009300 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009301 break;
9302 }
9303
Tim Northover85cf5642016-08-26 18:52:31 +00009304 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9305 return SDValue();
9306
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009307 SDLoc DL(N);
9308 SDValue ConvInput = Op.getOperand(0);
9309 bool IsSigned = Opc == ISD::SINT_TO_FP;
9310 if (IntBits < FloatBits)
9311 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9312 ResTy, ConvInput);
9313
9314 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9315 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9316 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9317 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9318 DAG.getConstant(C, DL, MVT::i32));
9319}
9320
Tim Northover3b0846e2014-05-24 12:50:23 +00009321/// An EXTR instruction is made up of two shifts, ORed together. This helper
9322/// searches for and classifies those shifts.
9323static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9324 bool &FromHi) {
9325 if (N.getOpcode() == ISD::SHL)
9326 FromHi = false;
9327 else if (N.getOpcode() == ISD::SRL)
9328 FromHi = true;
9329 else
9330 return false;
9331
9332 if (!isa<ConstantSDNode>(N.getOperand(1)))
9333 return false;
9334
9335 ShiftAmount = N->getConstantOperandVal(1);
9336 Src = N->getOperand(0);
9337 return true;
9338}
9339
9340/// EXTR instruction extracts a contiguous chunk of bits from two existing
9341/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009342/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9343/// with an EXTR. Can't quite be done in TableGen because the two immediates
9344/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009345static SDValue tryCombineToEXTR(SDNode *N,
9346 TargetLowering::DAGCombinerInfo &DCI) {
9347 SelectionDAG &DAG = DCI.DAG;
9348 SDLoc DL(N);
9349 EVT VT = N->getValueType(0);
9350
9351 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9352
9353 if (VT != MVT::i32 && VT != MVT::i64)
9354 return SDValue();
9355
9356 SDValue LHS;
9357 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009358 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009359 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9360 return SDValue();
9361
9362 SDValue RHS;
9363 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009364 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009365 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9366 return SDValue();
9367
9368 // If they're both trying to come from the high part of the register, they're
9369 // not really an EXTR.
9370 if (LHSFromHi == RHSFromHi)
9371 return SDValue();
9372
9373 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9374 return SDValue();
9375
9376 if (LHSFromHi) {
9377 std::swap(LHS, RHS);
9378 std::swap(ShiftLHS, ShiftRHS);
9379 }
9380
9381 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009382 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009383}
9384
9385static SDValue tryCombineToBSL(SDNode *N,
9386 TargetLowering::DAGCombinerInfo &DCI) {
9387 EVT VT = N->getValueType(0);
9388 SelectionDAG &DAG = DCI.DAG;
9389 SDLoc DL(N);
9390
9391 if (!VT.isVector())
9392 return SDValue();
9393
9394 SDValue N0 = N->getOperand(0);
9395 if (N0.getOpcode() != ISD::AND)
9396 return SDValue();
9397
9398 SDValue N1 = N->getOperand(1);
9399 if (N1.getOpcode() != ISD::AND)
9400 return SDValue();
9401
9402 // We only have to look for constant vectors here since the general, variable
9403 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009404 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009405 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9406 for (int i = 1; i >= 0; --i)
9407 for (int j = 1; j >= 0; --j) {
9408 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9409 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9410 if (!BVN0 || !BVN1)
9411 continue;
9412
9413 bool FoundMatch = true;
9414 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9415 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9416 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9417 if (!CN0 || !CN1 ||
9418 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9419 FoundMatch = false;
9420 break;
9421 }
9422 }
9423
9424 if (FoundMatch)
9425 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9426 N0->getOperand(1 - i), N1->getOperand(1 - j));
9427 }
9428
9429 return SDValue();
9430}
9431
9432static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9433 const AArch64Subtarget *Subtarget) {
9434 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009435 SelectionDAG &DAG = DCI.DAG;
9436 EVT VT = N->getValueType(0);
9437
9438 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9439 return SDValue();
9440
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009441 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009442 return Res;
9443
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009444 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009445 return Res;
9446
9447 return SDValue();
9448}
9449
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009450static SDValue performSRLCombine(SDNode *N,
9451 TargetLowering::DAGCombinerInfo &DCI) {
9452 SelectionDAG &DAG = DCI.DAG;
9453 EVT VT = N->getValueType(0);
9454 if (VT != MVT::i32 && VT != MVT::i64)
9455 return SDValue();
9456
9457 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9458 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9459 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9460 SDValue N0 = N->getOperand(0);
9461 if (N0.getOpcode() == ISD::BSWAP) {
9462 SDLoc DL(N);
9463 SDValue N1 = N->getOperand(1);
9464 SDValue N00 = N0.getOperand(0);
9465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9466 uint64_t ShiftAmt = C->getZExtValue();
9467 if (VT == MVT::i32 && ShiftAmt == 16 &&
9468 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9469 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9470 if (VT == MVT::i64 && ShiftAmt == 32 &&
9471 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9472 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9473 }
9474 }
9475 return SDValue();
9476}
9477
Tim Northover3b0846e2014-05-24 12:50:23 +00009478static SDValue performBitcastCombine(SDNode *N,
9479 TargetLowering::DAGCombinerInfo &DCI,
9480 SelectionDAG &DAG) {
9481 // Wait 'til after everything is legalized to try this. That way we have
9482 // legal vector types and such.
9483 if (DCI.isBeforeLegalizeOps())
9484 return SDValue();
9485
9486 // Remove extraneous bitcasts around an extract_subvector.
9487 // For example,
9488 // (v4i16 (bitconvert
9489 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9490 // becomes
9491 // (extract_subvector ((v8i16 ...), (i64 4)))
9492
9493 // Only interested in 64-bit vectors as the ultimate result.
9494 EVT VT = N->getValueType(0);
9495 if (!VT.isVector())
9496 return SDValue();
9497 if (VT.getSimpleVT().getSizeInBits() != 64)
9498 return SDValue();
9499 // Is the operand an extract_subvector starting at the beginning or halfway
9500 // point of the vector? A low half may also come through as an
9501 // EXTRACT_SUBREG, so look for that, too.
9502 SDValue Op0 = N->getOperand(0);
9503 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9504 !(Op0->isMachineOpcode() &&
9505 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9506 return SDValue();
9507 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9508 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9509 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9510 return SDValue();
9511 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9512 if (idx != AArch64::dsub)
9513 return SDValue();
9514 // The dsub reference is equivalent to a lane zero subvector reference.
9515 idx = 0;
9516 }
9517 // Look through the bitcast of the input to the extract.
9518 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9519 return SDValue();
9520 SDValue Source = Op0->getOperand(0)->getOperand(0);
9521 // If the source type has twice the number of elements as our destination
9522 // type, we know this is an extract of the high or low half of the vector.
9523 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009524 if (!SVT.isVector() ||
9525 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009526 return SDValue();
9527
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009528 LLVM_DEBUG(
9529 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009530
9531 // Create the simplified form to just extract the low or high half of the
9532 // vector directly rather than bothering with the bitcasts.
9533 SDLoc dl(N);
9534 unsigned NumElements = VT.getVectorNumElements();
9535 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009536 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009537 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9538 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009539 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009540 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9541 Source, SubReg),
9542 0);
9543 }
9544}
9545
9546static SDValue performConcatVectorsCombine(SDNode *N,
9547 TargetLowering::DAGCombinerInfo &DCI,
9548 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009549 SDLoc dl(N);
9550 EVT VT = N->getValueType(0);
9551 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9552
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009553 // Optimize concat_vectors of truncated vectors, where the intermediate
9554 // type is illegal, to avoid said illegality, e.g.,
9555 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9556 // (v2i16 (truncate (v2i64)))))
9557 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009558 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9559 // (v4i32 (bitcast (v2i64))),
9560 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009561 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9562 // on both input and result type, so we might generate worse code.
9563 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9564 if (N->getNumOperands() == 2 &&
9565 N0->getOpcode() == ISD::TRUNCATE &&
9566 N1->getOpcode() == ISD::TRUNCATE) {
9567 SDValue N00 = N0->getOperand(0);
9568 SDValue N10 = N1->getOperand(0);
9569 EVT N00VT = N00.getValueType();
9570
9571 if (N00VT == N10.getValueType() &&
9572 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9573 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009574 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9575 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9576 for (size_t i = 0; i < Mask.size(); ++i)
9577 Mask[i] = i * 2;
9578 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9579 DAG.getVectorShuffle(
9580 MidVT, dl,
9581 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9582 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009583 }
9584 }
9585
Tim Northover3b0846e2014-05-24 12:50:23 +00009586 // Wait 'til after everything is legalized to try this. That way we have
9587 // legal vector types and such.
9588 if (DCI.isBeforeLegalizeOps())
9589 return SDValue();
9590
Tim Northover3b0846e2014-05-24 12:50:23 +00009591 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9592 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9593 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009594 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009595 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009596 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009597 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009598 }
9599
9600 // Canonicalise concat_vectors so that the right-hand vector has as few
9601 // bit-casts as possible before its real operation. The primary matching
9602 // destination for these operations will be the narrowing "2" instructions,
9603 // which depend on the operation being performed on this right-hand vector.
9604 // For example,
9605 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9606 // becomes
9607 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9608
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009609 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009610 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009611 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009612 MVT RHSTy = RHS.getValueType().getSimpleVT();
9613 // If the RHS is not a vector, this is not the pattern we're looking for.
9614 if (!RHSTy.isVector())
9615 return SDValue();
9616
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009617 LLVM_DEBUG(
9618 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009619
9620 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9621 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009622 return DAG.getNode(ISD::BITCAST, dl, VT,
9623 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9624 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9625 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009626}
9627
9628static SDValue tryCombineFixedPointConvert(SDNode *N,
9629 TargetLowering::DAGCombinerInfo &DCI,
9630 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009631 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009632 // legal vector types and such.
9633 if (DCI.isBeforeLegalizeOps())
9634 return SDValue();
9635 // Transform a scalar conversion of a value from a lane extract into a
9636 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9637 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9638 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9639 //
9640 // The second form interacts better with instruction selection and the
9641 // register allocator to avoid cross-class register copies that aren't
9642 // coalescable due to a lane reference.
9643
9644 // Check the operand and see if it originates from a lane extract.
9645 SDValue Op1 = N->getOperand(1);
9646 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9647 // Yep, no additional predication needed. Perform the transform.
9648 SDValue IID = N->getOperand(0);
9649 SDValue Shift = N->getOperand(2);
9650 SDValue Vec = Op1.getOperand(0);
9651 SDValue Lane = Op1.getOperand(1);
9652 EVT ResTy = N->getValueType(0);
9653 EVT VecResTy;
9654 SDLoc DL(N);
9655
9656 // The vector width should be 128 bits by the time we get here, even
9657 // if it started as 64 bits (the extract_vector handling will have
9658 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009659 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009660 "unexpected vector size on extract_vector_elt!");
9661 if (Vec.getValueType() == MVT::v4i32)
9662 VecResTy = MVT::v4f32;
9663 else if (Vec.getValueType() == MVT::v2i64)
9664 VecResTy = MVT::v2f64;
9665 else
Craig Topper2a30d782014-06-18 05:05:13 +00009666 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009667
9668 SDValue Convert =
9669 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9670 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9671 }
9672 return SDValue();
9673}
9674
9675// AArch64 high-vector "long" operations are formed by performing the non-high
9676// version on an extract_subvector of each operand which gets the high half:
9677//
9678// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9679//
9680// However, there are cases which don't have an extract_high explicitly, but
9681// have another operation that can be made compatible with one for free. For
9682// example:
9683//
9684// (dupv64 scalar) --> (extract_high (dup128 scalar))
9685//
9686// This routine does the actual conversion of such DUPs, once outer routines
9687// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009688// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9689// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009690static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009691 switch (N.getOpcode()) {
9692 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009693 case AArch64ISD::DUPLANE8:
9694 case AArch64ISD::DUPLANE16:
9695 case AArch64ISD::DUPLANE32:
9696 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009697 case AArch64ISD::MOVI:
9698 case AArch64ISD::MOVIshift:
9699 case AArch64ISD::MOVIedit:
9700 case AArch64ISD::MOVImsl:
9701 case AArch64ISD::MVNIshift:
9702 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009703 break;
9704 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009705 // FMOV could be supported, but isn't very useful, as it would only occur
9706 // if you passed a bitcast' floating point immediate to an eligible long
9707 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009708 return SDValue();
9709 }
9710
9711 MVT NarrowTy = N.getSimpleValueType();
9712 if (!NarrowTy.is64BitVector())
9713 return SDValue();
9714
9715 MVT ElementTy = NarrowTy.getVectorElementType();
9716 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009717 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009718
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009719 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009720 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9721 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009722 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009723}
9724
9725static bool isEssentiallyExtractSubvector(SDValue N) {
9726 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9727 return true;
9728
9729 return N.getOpcode() == ISD::BITCAST &&
9730 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
9731}
9732
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009733/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009734struct GenericSetCCInfo {
9735 const SDValue *Opnd0;
9736 const SDValue *Opnd1;
9737 ISD::CondCode CC;
9738};
9739
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009740/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009741struct AArch64SetCCInfo {
9742 const SDValue *Cmp;
9743 AArch64CC::CondCode CC;
9744};
9745
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009746/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009747union SetCCInfo {
9748 GenericSetCCInfo Generic;
9749 AArch64SetCCInfo AArch64;
9750};
9751
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009752/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009753/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9754/// GenericSetCCInfo.
9755struct SetCCInfoAndKind {
9756 SetCCInfo Info;
9757 bool IsAArch64;
9758};
9759
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009760/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009761/// an
9762/// AArch64 lowered one.
9763/// \p SetCCInfo is filled accordingly.
9764/// \post SetCCInfo is meanginfull only when this function returns true.
9765/// \return True when Op is a kind of SET_CC operation.
9766static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9767 // If this is a setcc, this is straight forward.
9768 if (Op.getOpcode() == ISD::SETCC) {
9769 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9770 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9771 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9772 SetCCInfo.IsAArch64 = false;
9773 return true;
9774 }
9775 // Otherwise, check if this is a matching csel instruction.
9776 // In other words:
9777 // - csel 1, 0, cc
9778 // - csel 0, 1, !cc
9779 if (Op.getOpcode() != AArch64ISD::CSEL)
9780 return false;
9781 // Set the information about the operands.
9782 // TODO: we want the operands of the Cmp not the csel
9783 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9784 SetCCInfo.IsAArch64 = true;
9785 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9786 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9787
9788 // Check that the operands matches the constraints:
9789 // (1) Both operands must be constants.
9790 // (2) One must be 1 and the other must be 0.
9791 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9792 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9793
9794 // Check (1).
9795 if (!TValue || !FValue)
9796 return false;
9797
9798 // Check (2).
9799 if (!TValue->isOne()) {
9800 // Update the comparison when we are interested in !cc.
9801 std::swap(TValue, FValue);
9802 SetCCInfo.Info.AArch64.CC =
9803 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9804 }
9805 return TValue->isOne() && FValue->isNullValue();
9806}
9807
9808// Returns true if Op is setcc or zext of setcc.
9809static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9810 if (isSetCC(Op, Info))
9811 return true;
9812 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9813 isSetCC(Op->getOperand(0), Info));
9814}
9815
9816// The folding we want to perform is:
9817// (add x, [zext] (setcc cc ...) )
9818// -->
9819// (csel x, (add x, 1), !cc ...)
9820//
9821// The latter will get matched to a CSINC instruction.
9822static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9823 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9824 SDValue LHS = Op->getOperand(0);
9825 SDValue RHS = Op->getOperand(1);
9826 SetCCInfoAndKind InfoAndKind;
9827
9828 // If neither operand is a SET_CC, give up.
9829 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9830 std::swap(LHS, RHS);
9831 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9832 return SDValue();
9833 }
9834
9835 // FIXME: This could be generatized to work for FP comparisons.
9836 EVT CmpVT = InfoAndKind.IsAArch64
9837 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9838 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9839 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9840 return SDValue();
9841
9842 SDValue CCVal;
9843 SDValue Cmp;
9844 SDLoc dl(Op);
9845 if (InfoAndKind.IsAArch64) {
9846 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009847 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9848 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009849 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9850 } else
9851 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9852 *InfoAndKind.Info.Generic.Opnd1,
9853 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9854 CCVal, DAG, dl);
9855
9856 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009857 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009858 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9859}
9860
9861// The basic add/sub long vector instructions have variants with "2" on the end
9862// which act on the high-half of their inputs. They are normally matched by
9863// patterns like:
9864//
9865// (add (zeroext (extract_high LHS)),
9866// (zeroext (extract_high RHS)))
9867// -> uaddl2 vD, vN, vM
9868//
9869// However, if one of the extracts is something like a duplicate, this
9870// instruction can still be used profitably. This function puts the DAG into a
9871// more appropriate form for those patterns to trigger.
9872static SDValue performAddSubLongCombine(SDNode *N,
9873 TargetLowering::DAGCombinerInfo &DCI,
9874 SelectionDAG &DAG) {
9875 if (DCI.isBeforeLegalizeOps())
9876 return SDValue();
9877
9878 MVT VT = N->getSimpleValueType(0);
9879 if (!VT.is128BitVector()) {
9880 if (N->getOpcode() == ISD::ADD)
9881 return performSetccAddFolding(N, DAG);
9882 return SDValue();
9883 }
9884
9885 // Make sure both branches are extended in the same way.
9886 SDValue LHS = N->getOperand(0);
9887 SDValue RHS = N->getOperand(1);
9888 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9889 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9890 LHS.getOpcode() != RHS.getOpcode())
9891 return SDValue();
9892
9893 unsigned ExtType = LHS.getOpcode();
9894
9895 // It's not worth doing if at least one of the inputs isn't already an
9896 // extract, but we don't know which it'll be so we have to try both.
9897 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9898 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9899 if (!RHS.getNode())
9900 return SDValue();
9901
9902 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9903 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9904 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9905 if (!LHS.getNode())
9906 return SDValue();
9907
9908 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9909 }
9910
9911 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9912}
9913
9914// Massage DAGs which we can use the high-half "long" operations on into
9915// something isel will recognize better. E.g.
9916//
9917// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9918// (aarch64_neon_umull (extract_high (v2i64 vec)))
9919// (extract_high (v2i64 (dup128 scalar)))))
9920//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009921static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009922 TargetLowering::DAGCombinerInfo &DCI,
9923 SelectionDAG &DAG) {
9924 if (DCI.isBeforeLegalizeOps())
9925 return SDValue();
9926
Hal Finkelcd8664c2015-12-11 23:11:52 +00009927 SDValue LHS = N->getOperand(1);
9928 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009929 assert(LHS.getValueType().is64BitVector() &&
9930 RHS.getValueType().is64BitVector() &&
9931 "unexpected shape for long operation");
9932
9933 // Either node could be a DUP, but it's not worth doing both of them (you'd
9934 // just as well use the non-high version) so look for a corresponding extract
9935 // operation on the other "wing".
9936 if (isEssentiallyExtractSubvector(LHS)) {
9937 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9938 if (!RHS.getNode())
9939 return SDValue();
9940 } else if (isEssentiallyExtractSubvector(RHS)) {
9941 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9942 if (!LHS.getNode())
9943 return SDValue();
9944 }
9945
Hal Finkelcd8664c2015-12-11 23:11:52 +00009946 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9947 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009948}
9949
9950static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9951 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9952 unsigned ElemBits = ElemTy.getSizeInBits();
9953
9954 int64_t ShiftAmount;
9955 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9956 APInt SplatValue, SplatUndef;
9957 unsigned SplatBitSize;
9958 bool HasAnyUndefs;
9959 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9960 HasAnyUndefs, ElemBits) ||
9961 SplatBitSize != ElemBits)
9962 return SDValue();
9963
9964 ShiftAmount = SplatValue.getSExtValue();
9965 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9966 ShiftAmount = CVN->getSExtValue();
9967 } else
9968 return SDValue();
9969
9970 unsigned Opcode;
9971 bool IsRightShift;
9972 switch (IID) {
9973 default:
9974 llvm_unreachable("Unknown shift intrinsic");
9975 case Intrinsic::aarch64_neon_sqshl:
9976 Opcode = AArch64ISD::SQSHL_I;
9977 IsRightShift = false;
9978 break;
9979 case Intrinsic::aarch64_neon_uqshl:
9980 Opcode = AArch64ISD::UQSHL_I;
9981 IsRightShift = false;
9982 break;
9983 case Intrinsic::aarch64_neon_srshl:
9984 Opcode = AArch64ISD::SRSHR_I;
9985 IsRightShift = true;
9986 break;
9987 case Intrinsic::aarch64_neon_urshl:
9988 Opcode = AArch64ISD::URSHR_I;
9989 IsRightShift = true;
9990 break;
9991 case Intrinsic::aarch64_neon_sqshlu:
9992 Opcode = AArch64ISD::SQSHLU_I;
9993 IsRightShift = false;
9994 break;
9995 }
9996
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009997 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9998 SDLoc dl(N);
9999 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10000 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10001 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10002 SDLoc dl(N);
10003 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10004 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10005 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010006
10007 return SDValue();
10008}
10009
10010// The CRC32[BH] instructions ignore the high bits of their data operand. Since
10011// the intrinsics must be legal and take an i32, this means there's almost
10012// certainly going to be a zext in the DAG which we can eliminate.
10013static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10014 SDValue AndN = N->getOperand(2);
10015 if (AndN.getOpcode() != ISD::AND)
10016 return SDValue();
10017
10018 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10019 if (!CMask || CMask->getZExtValue() != Mask)
10020 return SDValue();
10021
10022 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10023 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10024}
10025
Ahmed Bougachafab58922015-03-10 20:45:38 +000010026static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10027 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010028 SDLoc dl(N);
10029 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10030 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +000010031 N->getOperand(1).getSimpleValueType(),
10032 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010033 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +000010034}
10035
Tim Northover3b0846e2014-05-24 12:50:23 +000010036static SDValue performIntrinsicCombine(SDNode *N,
10037 TargetLowering::DAGCombinerInfo &DCI,
10038 const AArch64Subtarget *Subtarget) {
10039 SelectionDAG &DAG = DCI.DAG;
10040 unsigned IID = getIntrinsicID(N);
10041 switch (IID) {
10042 default:
10043 break;
10044 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10045 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10046 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +000010047 case Intrinsic::aarch64_neon_saddv:
10048 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10049 case Intrinsic::aarch64_neon_uaddv:
10050 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10051 case Intrinsic::aarch64_neon_sminv:
10052 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10053 case Intrinsic::aarch64_neon_uminv:
10054 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10055 case Intrinsic::aarch64_neon_smaxv:
10056 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10057 case Intrinsic::aarch64_neon_umaxv:
10058 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010059 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +000010060 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010061 N->getOperand(1), N->getOperand(2));
10062 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +000010063 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010064 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +000010065 case Intrinsic::aarch64_neon_fmaxnm:
10066 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10067 N->getOperand(1), N->getOperand(2));
10068 case Intrinsic::aarch64_neon_fminnm:
10069 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10070 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010071 case Intrinsic::aarch64_neon_smull:
10072 case Intrinsic::aarch64_neon_umull:
10073 case Intrinsic::aarch64_neon_pmull:
10074 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +000010075 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010076 case Intrinsic::aarch64_neon_sqshl:
10077 case Intrinsic::aarch64_neon_uqshl:
10078 case Intrinsic::aarch64_neon_sqshlu:
10079 case Intrinsic::aarch64_neon_srshl:
10080 case Intrinsic::aarch64_neon_urshl:
10081 return tryCombineShiftImm(IID, N, DAG);
10082 case Intrinsic::aarch64_crc32b:
10083 case Intrinsic::aarch64_crc32cb:
10084 return tryCombineCRC32(0xff, N, DAG);
10085 case Intrinsic::aarch64_crc32h:
10086 case Intrinsic::aarch64_crc32ch:
10087 return tryCombineCRC32(0xffff, N, DAG);
10088 }
10089 return SDValue();
10090}
10091
10092static SDValue performExtendCombine(SDNode *N,
10093 TargetLowering::DAGCombinerInfo &DCI,
10094 SelectionDAG &DAG) {
10095 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10096 // we can convert that DUP into another extract_high (of a bigger DUP), which
10097 // helps the backend to decide that an sabdl2 would be useful, saving a real
10098 // extract_high operation.
10099 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +000010100 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010101 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010102 unsigned IID = getIntrinsicID(ABDNode);
10103 if (IID == Intrinsic::aarch64_neon_sabd ||
10104 IID == Intrinsic::aarch64_neon_uabd) {
10105 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10106 if (!NewABD.getNode())
10107 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010108
Hal Finkelcd8664c2015-12-11 23:11:52 +000010109 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10110 NewABD);
10111 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010112 }
10113
10114 // This is effectively a custom type legalization for AArch64.
10115 //
10116 // Type legalization will split an extend of a small, legal, type to a larger
10117 // illegal type by first splitting the destination type, often creating
10118 // illegal source types, which then get legalized in isel-confusing ways,
10119 // leading to really terrible codegen. E.g.,
10120 // %result = v8i32 sext v8i8 %value
10121 // becomes
10122 // %losrc = extract_subreg %value, ...
10123 // %hisrc = extract_subreg %value, ...
10124 // %lo = v4i32 sext v4i8 %losrc
10125 // %hi = v4i32 sext v4i8 %hisrc
10126 // Things go rapidly downhill from there.
10127 //
10128 // For AArch64, the [sz]ext vector instructions can only go up one element
10129 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10130 // take two instructions.
10131 //
10132 // This implies that the most efficient way to do the extend from v8i8
10133 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10134 // the normal splitting to happen for the v8i16->v8i32.
10135
10136 // This is pre-legalization to catch some cases where the default
10137 // type legalization will create ill-tempered code.
10138 if (!DCI.isBeforeLegalizeOps())
10139 return SDValue();
10140
10141 // We're only interested in cleaning things up for non-legal vector types
10142 // here. If both the source and destination are legal, things will just
10143 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010144 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010145 EVT ResVT = N->getValueType(0);
10146 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10147 return SDValue();
10148 // If the vector type isn't a simple VT, it's beyond the scope of what
10149 // we're worried about here. Let legalization do its thing and hope for
10150 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010151 SDValue Src = N->getOperand(0);
10152 EVT SrcVT = Src->getValueType(0);
10153 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010154 return SDValue();
10155
Tim Northover3b0846e2014-05-24 12:50:23 +000010156 // If the source VT is a 64-bit vector, we can play games and get the
10157 // better results we want.
10158 if (SrcVT.getSizeInBits() != 64)
10159 return SDValue();
10160
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010161 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010162 unsigned ElementCount = SrcVT.getVectorNumElements();
10163 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10164 SDLoc DL(N);
10165 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10166
10167 // Now split the rest of the operation into two halves, each with a 64
10168 // bit source.
10169 EVT LoVT, HiVT;
10170 SDValue Lo, Hi;
10171 unsigned NumElements = ResVT.getVectorNumElements();
10172 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10173 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10174 ResVT.getVectorElementType(), NumElements / 2);
10175
10176 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10177 LoVT.getVectorNumElements());
10178 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010179 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010180 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010181 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010182 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10183 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10184
10185 // Now combine the parts back together so we still have a single result
10186 // like the combiner expects.
10187 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10188}
10189
Geoff Berry8301c642016-11-16 19:35:19 +000010190static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10191 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010192 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010193 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010194 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010195
10196 // Create scalar stores. This is at least as good as the code sequence for a
10197 // split unaligned store which is a dup.s, ext.b, and two stores.
10198 // Most of the time the three stores should be replaced by store pair
10199 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010200 SDLoc DL(&St);
10201 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010202 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010203
John Brawn3a9c8422017-02-06 18:07:20 +000010204 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010205 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010206 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010207 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010208
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010209 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010210 if (BasePtr->getOpcode() == ISD::ADD &&
10211 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10212 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10213 BasePtr = BasePtr->getOperand(0);
10214 }
10215
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010216 unsigned Offset = EltOffset;
10217 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010218 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010219 SDValue OffsetPtr =
10220 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10221 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010222 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010223 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010224 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010225 Offset += EltOffset;
10226 }
10227 return NewST1;
10228}
10229
Geoff Berry526c5052016-11-14 19:39:04 +000010230/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10231/// load store optimizer pass will merge them to store pair stores. This should
10232/// be better than a movi to create the vector zero followed by a vector store
10233/// if the zero constant is not re-used, since one instructions and one register
10234/// live range will be removed.
10235///
10236/// For example, the final generated code should be:
10237///
10238/// stp xzr, xzr, [x0]
10239///
10240/// instead of:
10241///
10242/// movi v0.2d, #0
10243/// str q0, [x0]
10244///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010245static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10246 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010247 EVT VT = StVal.getValueType();
10248
Geoff Berry8301c642016-11-16 19:35:19 +000010249 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10250 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010251 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010252 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10253 VT.getVectorElementType().getSizeInBits() == 64) ||
10254 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10255 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010256 return SDValue();
10257
10258 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10259 return SDValue();
10260
10261 // If the zero constant has more than one use then the vector store could be
10262 // better since the constant mov will be amortized and stp q instructions
10263 // should be able to be formed.
10264 if (!StVal.hasOneUse())
10265 return SDValue();
10266
Tim Northover964eea72019-01-08 13:30:27 +000010267 // If the store is truncating then it's going down to i16 or smaller, which
10268 // means it can be implemented in a single store anyway.
10269 if (St.isTruncatingStore())
10270 return SDValue();
10271
Geoff Berry526c5052016-11-14 19:39:04 +000010272 // If the immediate offset of the address operand is too large for the stp
10273 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010274 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10275 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010276 if (Offset < -512 || Offset > 504)
10277 return SDValue();
10278 }
10279
10280 for (int I = 0; I < NumVecElts; ++I) {
10281 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010282 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010283 return SDValue();
10284 }
Geoff Berry8301c642016-11-16 19:35:19 +000010285
Geoff Berrybb23df92017-09-21 21:10:06 +000010286 // Use a CopyFromReg WZR/XZR here to prevent
10287 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10288 SDLoc DL(&St);
10289 unsigned ZeroReg;
10290 EVT ZeroVT;
10291 if (VT.getVectorElementType().getSizeInBits() == 32) {
10292 ZeroReg = AArch64::WZR;
10293 ZeroVT = MVT::i32;
10294 } else {
10295 ZeroReg = AArch64::XZR;
10296 ZeroVT = MVT::i64;
10297 }
10298 SDValue SplatVal =
10299 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010300 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010301}
10302
Tim Northover3b0846e2014-05-24 12:50:23 +000010303/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10304/// value. The load store optimizer pass will merge them to store pair stores.
10305/// This has better performance than a splat of the scalar followed by a split
10306/// vector store. Even if the stores are not merged it is four stores vs a dup,
10307/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010308static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10309 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010310 EVT VT = StVal.getValueType();
10311
10312 // Don't replace floating point stores, they possibly won't be transformed to
10313 // stp because of the store pair suppress pass.
10314 if (VT.isFloatingPoint())
10315 return SDValue();
10316
Tim Northover3b0846e2014-05-24 12:50:23 +000010317 // We can express a splat as store pair(s) for 2 or 4 elements.
10318 unsigned NumVecElts = VT.getVectorNumElements();
10319 if (NumVecElts != 4 && NumVecElts != 2)
10320 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010321
Tim Northover964eea72019-01-08 13:30:27 +000010322 // If the store is truncating then it's going down to i16 or smaller, which
10323 // means it can be implemented in a single store anyway.
10324 if (St.isTruncatingStore())
10325 return SDValue();
10326
Tim Northover3b0846e2014-05-24 12:50:23 +000010327 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010328 // Make sure that each of the relevant vector element locations are inserted
10329 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10330 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10331 SDValue SplatVal;
10332 for (unsigned I = 0; I < NumVecElts; ++I) {
10333 // Check for insert vector elements.
10334 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010335 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010336
10337 // Check that same value is inserted at each vector element.
10338 if (I == 0)
10339 SplatVal = StVal.getOperand(1);
10340 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010341 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010342
10343 // Check insert element index.
10344 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10345 if (!CIndex)
10346 return SDValue();
10347 uint64_t IndexVal = CIndex->getZExtValue();
10348 if (IndexVal >= NumVecElts)
10349 return SDValue();
10350 IndexNotInserted.reset(IndexVal);
10351
10352 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010353 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010354 // Check that all vector element locations were inserted to.
10355 if (IndexNotInserted.any())
10356 return SDValue();
10357
Geoff Berry8301c642016-11-16 19:35:19 +000010358 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010359}
10360
Geoff Berry8301c642016-11-16 19:35:19 +000010361static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10362 SelectionDAG &DAG,
10363 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010364
10365 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010366 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010367 return SDValue();
10368
Geoff Berry526c5052016-11-14 19:39:04 +000010369 SDValue StVal = S->getValue();
10370 EVT VT = StVal.getValueType();
10371 if (!VT.isVector())
10372 return SDValue();
10373
10374 // If we get a splat of zeros, convert this vector store to a store of
10375 // scalars. They will be merged into store pairs of xzr thereby removing one
10376 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010377 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010378 return ReplacedZeroSplat;
10379
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010380 // FIXME: The logic for deciding if an unaligned store should be split should
10381 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10382 // a call to that function here.
10383
Matthias Braun651cff42016-06-02 18:03:53 +000010384 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010385 return SDValue();
10386
Sanjay Patel924879a2015-08-04 15:49:57 +000010387 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +000010388 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010389 return SDValue();
10390
Tim Northover3b0846e2014-05-24 12:50:23 +000010391 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10392 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010393 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010394 return SDValue();
10395
10396 // Split unaligned 16B stores. They are terrible for performance.
10397 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10398 // extensions can use this to mark that it does not want splitting to happen
10399 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10400 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10401 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10402 S->getAlignment() <= 2)
10403 return SDValue();
10404
10405 // If we get a splat of a scalar convert this vector store to a store of
10406 // scalars. They will be merged into store pairs thereby removing two
10407 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010408 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010409 return ReplacedSplat;
10410
10411 SDLoc DL(S);
10412 unsigned NumElts = VT.getVectorNumElements() / 2;
10413 // Split VT into two.
10414 EVT HalfVT =
10415 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10416 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010417 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010418 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010419 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010420 SDValue BasePtr = S->getBasePtr();
10421 SDValue NewST1 =
10422 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010423 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010424 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010425 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010426 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010427 S->getPointerInfo(), S->getAlignment(),
10428 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010429}
10430
10431/// Target-specific DAG combine function for post-increment LD1 (lane) and
10432/// post-increment LD1R.
10433static SDValue performPostLD1Combine(SDNode *N,
10434 TargetLowering::DAGCombinerInfo &DCI,
10435 bool IsLaneOp) {
10436 if (DCI.isBeforeLegalizeOps())
10437 return SDValue();
10438
10439 SelectionDAG &DAG = DCI.DAG;
10440 EVT VT = N->getValueType(0);
10441
10442 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10443 SDNode *LD = N->getOperand(LoadIdx).getNode();
10444 // If it is not LOAD, can not do such combine.
10445 if (LD->getOpcode() != ISD::LOAD)
10446 return SDValue();
10447
Geoff Berry60460262018-05-11 16:25:06 +000010448 // The vector lane must be a constant in the LD1LANE opcode.
10449 SDValue Lane;
10450 if (IsLaneOp) {
10451 Lane = N->getOperand(2);
10452 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10453 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10454 return SDValue();
10455 }
10456
Tim Northover3b0846e2014-05-24 12:50:23 +000010457 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10458 EVT MemVT = LoadSDN->getMemoryVT();
10459 // Check if memory operand is the same type as the vector element.
10460 if (MemVT != VT.getVectorElementType())
10461 return SDValue();
10462
10463 // Check if there are other uses. If so, do not combine as it will introduce
10464 // an extra load.
10465 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10466 ++UI) {
10467 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10468 continue;
10469 if (*UI != N)
10470 return SDValue();
10471 }
10472
10473 SDValue Addr = LD->getOperand(1);
10474 SDValue Vector = N->getOperand(0);
10475 // Search for a use of the address operand that is an increment.
10476 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10477 Addr.getNode()->use_end(); UI != UE; ++UI) {
10478 SDNode *User = *UI;
10479 if (User->getOpcode() != ISD::ADD
10480 || UI.getUse().getResNo() != Addr.getResNo())
10481 continue;
10482
Tim Northover3b0846e2014-05-24 12:50:23 +000010483 // If the increment is a constant, it must match the memory ref size.
10484 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10485 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10486 uint32_t IncVal = CInc->getZExtValue();
10487 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10488 if (IncVal != NumBytes)
10489 continue;
10490 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10491 }
10492
Nirav Davee40e2bb2018-09-25 15:30:22 +000010493 // To avoid cycle construction make sure that neither the load nor the add
10494 // are predecessors to each other or the Vector.
10495 SmallPtrSet<const SDNode *, 32> Visited;
10496 SmallVector<const SDNode *, 16> Worklist;
10497 Visited.insert(N);
10498 Worklist.push_back(User);
10499 Worklist.push_back(LD);
10500 Worklist.push_back(Vector.getNode());
10501 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10502 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010503 continue;
10504
Tim Northover3b0846e2014-05-24 12:50:23 +000010505 SmallVector<SDValue, 8> Ops;
10506 Ops.push_back(LD->getOperand(0)); // Chain
10507 if (IsLaneOp) {
10508 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010509 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010510 }
10511 Ops.push_back(Addr);
10512 Ops.push_back(Inc);
10513
10514 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010515 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010516 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10517 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10518 MemVT,
10519 LoadSDN->getMemOperand());
10520
10521 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010522 SDValue NewResults[] = {
10523 SDValue(LD, 0), // The result of load
10524 SDValue(UpdN.getNode(), 2) // Chain
10525 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010526 DCI.CombineTo(LD, NewResults);
10527 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10528 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10529
10530 break;
10531 }
10532 return SDValue();
10533}
10534
Joel Jones7466ccf2017-07-10 22:11:50 +000010535/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010536/// address translation.
10537static bool performTBISimplification(SDValue Addr,
10538 TargetLowering::DAGCombinerInfo &DCI,
10539 SelectionDAG &DAG) {
10540 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010541 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010542 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10543 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010544 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010545 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010546 DCI.CommitTargetLoweringOpt(TLO);
10547 return true;
10548 }
10549 return false;
10550}
10551
10552static SDValue performSTORECombine(SDNode *N,
10553 TargetLowering::DAGCombinerInfo &DCI,
10554 SelectionDAG &DAG,
10555 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010556 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010557 return Split;
10558
10559 if (Subtarget->supportsAddressTopByteIgnored() &&
10560 performTBISimplification(N->getOperand(2), DCI, DAG))
10561 return SDValue(N, 0);
10562
10563 return SDValue();
10564}
10565
Chad Rosier6c36eff2015-09-03 18:13:57 +000010566
Tim Northover3b0846e2014-05-24 12:50:23 +000010567/// Target-specific DAG combine function for NEON load/store intrinsics
10568/// to merge base address updates.
10569static SDValue performNEONPostLDSTCombine(SDNode *N,
10570 TargetLowering::DAGCombinerInfo &DCI,
10571 SelectionDAG &DAG) {
10572 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10573 return SDValue();
10574
10575 unsigned AddrOpIdx = N->getNumOperands() - 1;
10576 SDValue Addr = N->getOperand(AddrOpIdx);
10577
10578 // Search for a use of the address operand that is an increment.
10579 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10580 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10581 SDNode *User = *UI;
10582 if (User->getOpcode() != ISD::ADD ||
10583 UI.getUse().getResNo() != Addr.getResNo())
10584 continue;
10585
10586 // Check that the add is independent of the load/store. Otherwise, folding
10587 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010588 SmallPtrSet<const SDNode *, 32> Visited;
10589 SmallVector<const SDNode *, 16> Worklist;
10590 Visited.insert(Addr.getNode());
10591 Worklist.push_back(N);
10592 Worklist.push_back(User);
10593 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10594 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010595 continue;
10596
10597 // Find the new opcode for the updating load/store.
10598 bool IsStore = false;
10599 bool IsLaneOp = false;
10600 bool IsDupOp = false;
10601 unsigned NewOpc = 0;
10602 unsigned NumVecs = 0;
10603 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10604 switch (IntNo) {
10605 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10606 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10607 NumVecs = 2; break;
10608 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10609 NumVecs = 3; break;
10610 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10611 NumVecs = 4; break;
10612 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10613 NumVecs = 2; IsStore = true; break;
10614 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10615 NumVecs = 3; IsStore = true; break;
10616 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10617 NumVecs = 4; IsStore = true; break;
10618 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10619 NumVecs = 2; break;
10620 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10621 NumVecs = 3; break;
10622 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10623 NumVecs = 4; break;
10624 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10625 NumVecs = 2; IsStore = true; break;
10626 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10627 NumVecs = 3; IsStore = true; break;
10628 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10629 NumVecs = 4; IsStore = true; break;
10630 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10631 NumVecs = 2; IsDupOp = true; break;
10632 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10633 NumVecs = 3; IsDupOp = true; break;
10634 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10635 NumVecs = 4; IsDupOp = true; break;
10636 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10637 NumVecs = 2; IsLaneOp = true; break;
10638 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10639 NumVecs = 3; IsLaneOp = true; break;
10640 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10641 NumVecs = 4; IsLaneOp = true; break;
10642 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10643 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10644 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10645 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10646 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10647 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10648 }
10649
10650 EVT VecTy;
10651 if (IsStore)
10652 VecTy = N->getOperand(2).getValueType();
10653 else
10654 VecTy = N->getValueType(0);
10655
10656 // If the increment is a constant, it must match the memory ref size.
10657 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10658 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10659 uint32_t IncVal = CInc->getZExtValue();
10660 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10661 if (IsLaneOp || IsDupOp)
10662 NumBytes /= VecTy.getVectorNumElements();
10663 if (IncVal != NumBytes)
10664 continue;
10665 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10666 }
10667 SmallVector<SDValue, 8> Ops;
10668 Ops.push_back(N->getOperand(0)); // Incoming chain
10669 // Load lane and store have vector list as input.
10670 if (IsLaneOp || IsStore)
10671 for (unsigned i = 2; i < AddrOpIdx; ++i)
10672 Ops.push_back(N->getOperand(i));
10673 Ops.push_back(Addr); // Base register
10674 Ops.push_back(Inc);
10675
10676 // Return Types.
10677 EVT Tys[6];
10678 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10679 unsigned n;
10680 for (n = 0; n < NumResultVecs; ++n)
10681 Tys[n] = VecTy;
10682 Tys[n++] = MVT::i64; // Type of write back register
10683 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010684 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010685
10686 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10687 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10688 MemInt->getMemoryVT(),
10689 MemInt->getMemOperand());
10690
10691 // Update the uses.
10692 std::vector<SDValue> NewResults;
10693 for (unsigned i = 0; i < NumResultVecs; ++i) {
10694 NewResults.push_back(SDValue(UpdN.getNode(), i));
10695 }
10696 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10697 DCI.CombineTo(N, NewResults);
10698 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10699
10700 break;
10701 }
10702 return SDValue();
10703}
10704
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010705// Checks to see if the value is the prescribed width and returns information
10706// about its extension mode.
10707static
10708bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10709 ExtType = ISD::NON_EXTLOAD;
10710 switch(V.getNode()->getOpcode()) {
10711 default:
10712 return false;
10713 case ISD::LOAD: {
10714 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10715 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10716 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10717 ExtType = LoadNode->getExtensionType();
10718 return true;
10719 }
10720 return false;
10721 }
10722 case ISD::AssertSext: {
10723 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10724 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10725 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10726 ExtType = ISD::SEXTLOAD;
10727 return true;
10728 }
10729 return false;
10730 }
10731 case ISD::AssertZext: {
10732 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10733 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10734 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10735 ExtType = ISD::ZEXTLOAD;
10736 return true;
10737 }
10738 return false;
10739 }
10740 case ISD::Constant:
10741 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010742 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10743 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010744 }
10745 }
10746
10747 return true;
10748}
10749
10750// This function does a whole lot of voodoo to determine if the tests are
10751// equivalent without and with a mask. Essentially what happens is that given a
10752// DAG resembling:
10753//
10754// +-------------+ +-------------+ +-------------+ +-------------+
10755// | Input | | AddConstant | | CompConstant| | CC |
10756// +-------------+ +-------------+ +-------------+ +-------------+
10757// | | | |
10758// V V | +----------+
10759// +-------------+ +----+ | |
10760// | ADD | |0xff| | |
10761// +-------------+ +----+ | |
10762// | | | |
10763// V V | |
10764// +-------------+ | |
10765// | AND | | |
10766// +-------------+ | |
10767// | | |
10768// +-----+ | |
10769// | | |
10770// V V V
10771// +-------------+
10772// | CMP |
10773// +-------------+
10774//
10775// The AND node may be safely removed for some combinations of inputs. In
10776// particular we need to take into account the extension type of the Input,
10777// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10778// width of the input (this can work for any width inputs, the above graph is
10779// specific to 8 bits.
10780//
10781// The specific equations were worked out by generating output tables for each
10782// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10783// problem was simplified by working with 4 bit inputs, which means we only
10784// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10785// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10786// patterns present in both extensions (0,7). For every distinct set of
10787// AddConstant and CompConstants bit patterns we can consider the masked and
10788// unmasked versions to be equivalent if the result of this function is true for
10789// all 16 distinct bit patterns of for the current extension type of Input (w0).
10790//
10791// sub w8, w0, w1
10792// and w10, w8, #0x0f
10793// cmp w8, w2
10794// cset w9, AArch64CC
10795// cmp w10, w2
10796// cset w11, AArch64CC
10797// cmp w9, w11
10798// cset w0, eq
10799// ret
10800//
10801// Since the above function shows when the outputs are equivalent it defines
10802// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10803// would be expensive to run during compiles. The equations below were written
10804// in a test harness that confirmed they gave equivalent outputs to the above
10805// for all inputs function, so they can be used determine if the removal is
10806// legal instead.
10807//
10808// isEquivalentMaskless() is the code for testing if the AND can be removed
10809// factored out of the DAG recognition as the DAG can take several forms.
10810
David Majnemere61e4bf2016-06-21 05:10:24 +000010811static bool isEquivalentMaskless(unsigned CC, unsigned width,
10812 ISD::LoadExtType ExtType, int AddConstant,
10813 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010814 // By being careful about our equations and only writing the in term
10815 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10816 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010817 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010818
10819 // For the purposes of these comparisons sign extending the type is
10820 // equivalent to zero extending the add and displacing it by half the integer
10821 // width. Provided we are careful and make sure our equations are valid over
10822 // the whole range we can just adjust the input and avoid writing equations
10823 // for sign extended inputs.
10824 if (ExtType == ISD::SEXTLOAD)
10825 AddConstant -= (1 << (width-1));
10826
10827 switch(CC) {
10828 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010829 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010830 if ((AddConstant == 0) ||
10831 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10832 (AddConstant >= 0 && CompConstant < 0) ||
10833 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10834 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010835 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010836 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010837 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010838 if ((AddConstant == 0) ||
10839 (AddConstant >= 0 && CompConstant <= 0) ||
10840 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10841 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010842 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010843 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010844 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010845 if ((AddConstant >= 0 && CompConstant < 0) ||
10846 (AddConstant <= 0 && CompConstant >= -1 &&
10847 CompConstant < AddConstant + MaxUInt))
10848 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010849 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010850 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010851 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010852 if ((AddConstant == 0) ||
10853 (AddConstant > 0 && CompConstant <= 0) ||
10854 (AddConstant < 0 && CompConstant <= AddConstant))
10855 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010856 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010857 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010858 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010859 if ((AddConstant >= 0 && CompConstant <= 0) ||
10860 (AddConstant <= 0 && CompConstant >= 0 &&
10861 CompConstant <= AddConstant + MaxUInt))
10862 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010863 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010864 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010865 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010866 if ((AddConstant > 0 && CompConstant < 0) ||
10867 (AddConstant < 0 && CompConstant >= 0 &&
10868 CompConstant < AddConstant + MaxUInt) ||
10869 (AddConstant >= 0 && CompConstant >= 0 &&
10870 CompConstant >= AddConstant) ||
10871 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010872 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010873 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010874 case AArch64CC::VS:
10875 case AArch64CC::VC:
10876 case AArch64CC::AL:
10877 case AArch64CC::NV:
10878 return true;
10879 case AArch64CC::Invalid:
10880 break;
10881 }
10882
10883 return false;
10884}
10885
10886static
10887SDValue performCONDCombine(SDNode *N,
10888 TargetLowering::DAGCombinerInfo &DCI,
10889 SelectionDAG &DAG, unsigned CCIndex,
10890 unsigned CmpIndex) {
10891 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10892 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10893 unsigned CondOpcode = SubsNode->getOpcode();
10894
10895 if (CondOpcode != AArch64ISD::SUBS)
10896 return SDValue();
10897
10898 // There is a SUBS feeding this condition. Is it fed by a mask we can
10899 // use?
10900
10901 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10902 unsigned MaskBits = 0;
10903
10904 if (AndNode->getOpcode() != ISD::AND)
10905 return SDValue();
10906
10907 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10908 uint32_t CNV = CN->getZExtValue();
10909 if (CNV == 255)
10910 MaskBits = 8;
10911 else if (CNV == 65535)
10912 MaskBits = 16;
10913 }
10914
10915 if (!MaskBits)
10916 return SDValue();
10917
10918 SDValue AddValue = AndNode->getOperand(0);
10919
10920 if (AddValue.getOpcode() != ISD::ADD)
10921 return SDValue();
10922
10923 // The basic dag structure is correct, grab the inputs and validate them.
10924
10925 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10926 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10927 SDValue SubsInputValue = SubsNode->getOperand(1);
10928
10929 // The mask is present and the provenance of all the values is a smaller type,
10930 // lets see if the mask is superfluous.
10931
10932 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10933 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10934 return SDValue();
10935
10936 ISD::LoadExtType ExtType;
10937
10938 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10939 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10940 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10941 return SDValue();
10942
10943 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10944 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10945 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10946 return SDValue();
10947
10948 // The AND is not necessary, remove it.
10949
10950 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10951 SubsNode->getValueType(1));
10952 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10953
10954 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10955 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10956
10957 return SDValue(N, 0);
10958}
10959
Tim Northover3b0846e2014-05-24 12:50:23 +000010960// Optimize compare with zero and branch.
10961static SDValue performBRCONDCombine(SDNode *N,
10962 TargetLowering::DAGCombinerInfo &DCI,
10963 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000010964 MachineFunction &MF = DAG.getMachineFunction();
10965 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
10966 // will not be produced, as they are conditional branch instructions that do
10967 // not set flags.
10968 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
10969 return SDValue();
10970
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010971 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010972 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010973 SDValue Chain = N->getOperand(0);
10974 SDValue Dest = N->getOperand(1);
10975 SDValue CCVal = N->getOperand(2);
10976 SDValue Cmp = N->getOperand(3);
10977
10978 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10979 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10980 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10981 return SDValue();
10982
10983 unsigned CmpOpc = Cmp.getOpcode();
10984 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10985 return SDValue();
10986
10987 // Only attempt folding if there is only one use of the flag and no use of the
10988 // value.
10989 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10990 return SDValue();
10991
10992 SDValue LHS = Cmp.getOperand(0);
10993 SDValue RHS = Cmp.getOperand(1);
10994
10995 assert(LHS.getValueType() == RHS.getValueType() &&
10996 "Expected the value type to be the same for both operands!");
10997 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10998 return SDValue();
10999
Artyom Skrobov314ee042015-11-25 19:41:11 +000011000 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011001 std::swap(LHS, RHS);
11002
Artyom Skrobov314ee042015-11-25 19:41:11 +000011003 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000011004 return SDValue();
11005
11006 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11007 LHS.getOpcode() == ISD::SRL)
11008 return SDValue();
11009
11010 // Fold the compare into the branch instruction.
11011 SDValue BR;
11012 if (CC == AArch64CC::EQ)
11013 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11014 else
11015 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11016
11017 // Do not add new nodes to DAG combiner worklist.
11018 DCI.CombineTo(N, BR, false);
11019
11020 return SDValue();
11021}
11022
Geoff Berry9e934b02016-01-04 18:55:47 +000011023// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11024// as well as whether the test should be inverted. This code is required to
11025// catch these cases (as opposed to standard dag combines) because
11026// AArch64ISD::TBZ is matched during legalization.
11027static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11028 SelectionDAG &DAG) {
11029
11030 if (!Op->hasOneUse())
11031 return Op;
11032
11033 // We don't handle undef/constant-fold cases below, as they should have
11034 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11035 // etc.)
11036
11037 // (tbz (trunc x), b) -> (tbz x, b)
11038 // This case is just here to enable more of the below cases to be caught.
11039 if (Op->getOpcode() == ISD::TRUNCATE &&
11040 Bit < Op->getValueType(0).getSizeInBits()) {
11041 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11042 }
11043
11044 if (Op->getNumOperands() != 2)
11045 return Op;
11046
11047 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11048 if (!C)
11049 return Op;
11050
11051 switch (Op->getOpcode()) {
11052 default:
11053 return Op;
11054
11055 // (tbz (and x, m), b) -> (tbz x, b)
11056 case ISD::AND:
11057 if ((C->getZExtValue() >> Bit) & 1)
11058 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11059 return Op;
11060
11061 // (tbz (shl x, c), b) -> (tbz x, b-c)
11062 case ISD::SHL:
11063 if (C->getZExtValue() <= Bit &&
11064 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11065 Bit = Bit - C->getZExtValue();
11066 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11067 }
11068 return Op;
11069
11070 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11071 case ISD::SRA:
11072 Bit = Bit + C->getZExtValue();
11073 if (Bit >= Op->getValueType(0).getSizeInBits())
11074 Bit = Op->getValueType(0).getSizeInBits() - 1;
11075 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11076
11077 // (tbz (srl x, c), b) -> (tbz x, b+c)
11078 case ISD::SRL:
11079 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11080 Bit = Bit + C->getZExtValue();
11081 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11082 }
11083 return Op;
11084
11085 // (tbz (xor x, -1), b) -> (tbnz x, b)
11086 case ISD::XOR:
11087 if ((C->getZExtValue() >> Bit) & 1)
11088 Invert = !Invert;
11089 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11090 }
11091}
11092
11093// Optimize test single bit zero/non-zero and branch.
11094static SDValue performTBZCombine(SDNode *N,
11095 TargetLowering::DAGCombinerInfo &DCI,
11096 SelectionDAG &DAG) {
11097 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11098 bool Invert = false;
11099 SDValue TestSrc = N->getOperand(1);
11100 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11101
11102 if (TestSrc == NewTestSrc)
11103 return SDValue();
11104
11105 unsigned NewOpc = N->getOpcode();
11106 if (Invert) {
11107 if (NewOpc == AArch64ISD::TBZ)
11108 NewOpc = AArch64ISD::TBNZ;
11109 else {
11110 assert(NewOpc == AArch64ISD::TBNZ);
11111 NewOpc = AArch64ISD::TBZ;
11112 }
11113 }
11114
11115 SDLoc DL(N);
11116 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11117 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11118}
11119
Tim Northover3b0846e2014-05-24 12:50:23 +000011120// vselect (v1i1 setcc) ->
11121// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11122// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11123// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11124// such VSELECT.
11125static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11126 SDValue N0 = N->getOperand(0);
11127 EVT CCVT = N0.getValueType();
11128
11129 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11130 CCVT.getVectorElementType() != MVT::i1)
11131 return SDValue();
11132
11133 EVT ResVT = N->getValueType(0);
11134 EVT CmpVT = N0.getOperand(0).getValueType();
11135 // Only combine when the result type is of the same size as the compared
11136 // operands.
11137 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11138 return SDValue();
11139
11140 SDValue IfTrue = N->getOperand(1);
11141 SDValue IfFalse = N->getOperand(2);
11142 SDValue SetCC =
11143 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11144 N0.getOperand(0), N0.getOperand(1),
11145 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11146 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11147 IfTrue, IfFalse);
11148}
11149
11150/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11151/// the compare-mask instructions rather than going via NZCV, even if LHS and
11152/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11153/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011154static SDValue performSelectCombine(SDNode *N,
11155 TargetLowering::DAGCombinerInfo &DCI) {
11156 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011157 SDValue N0 = N->getOperand(0);
11158 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011159
Ahmed Bougachac004c602015-04-27 21:43:12 +000011160 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011161 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011162
Ahmed Bougachac004c602015-04-27 21:43:12 +000011163 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11164 // scalar SetCCResultType. We also don't expect vectors, because we assume
11165 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11166 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11167 "Scalar-SETCC feeding SELECT has unexpected result type!");
11168
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011169 // If NumMaskElts == 0, the comparison is larger than select result. The
11170 // largest real NEON comparison is 64-bits per lane, which means the result is
11171 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011172 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011173
11174 // Don't try to do this optimization when the setcc itself has i1 operands.
11175 // There are no legal vectors of i1, so this would be pointless.
11176 if (SrcVT == MVT::i1)
11177 return SDValue();
11178
Tim Northover3c0915e2014-08-29 15:34:58 +000011179 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011180 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011181 return SDValue();
11182
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011183 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011184 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11185
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011186 // Also bail out if the vector CCVT isn't the same size as ResVT.
11187 // This can happen if the SETCC operand size doesn't divide the ResVT size
11188 // (e.g., f64 vs v3f32).
11189 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11190 return SDValue();
11191
Ahmed Bougachac004c602015-04-27 21:43:12 +000011192 // Make sure we didn't create illegal types, if we're not supposed to.
11193 assert(DCI.isBeforeLegalize() ||
11194 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11195
Tim Northover3b0846e2014-05-24 12:50:23 +000011196 // First perform a vector comparison, where lane 0 is the one we're interested
11197 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011198 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011199 SDValue LHS =
11200 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11201 SDValue RHS =
11202 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11203 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11204
11205 // Now duplicate the comparison mask we want across all other lanes.
11206 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011207 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011208 Mask = DAG.getNode(ISD::BITCAST, DL,
11209 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011210
11211 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11212}
11213
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011214/// Get rid of unnecessary NVCASTs (that don't change the type).
11215static SDValue performNVCASTCombine(SDNode *N) {
11216 if (N->getValueType(0) == N->getOperand(0).getValueType())
11217 return N->getOperand(0);
11218
11219 return SDValue();
11220}
11221
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011222// If all users of the globaladdr are of the form (globaladdr + constant), find
11223// the smallest constant, fold it into the globaladdr's offset and rewrite the
11224// globaladdr as (globaladdr + constant) - constant.
11225static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11226 const AArch64Subtarget *Subtarget,
11227 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011228 auto *GN = cast<GlobalAddressSDNode>(N);
11229 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11230 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011231 return SDValue();
11232
11233 uint64_t MinOffset = -1ull;
11234 for (SDNode *N : GN->uses()) {
11235 if (N->getOpcode() != ISD::ADD)
11236 return SDValue();
11237 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11238 if (!C)
11239 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11240 if (!C)
11241 return SDValue();
11242 MinOffset = std::min(MinOffset, C->getZExtValue());
11243 }
11244 uint64_t Offset = MinOffset + GN->getOffset();
11245
11246 // Require that the new offset is larger than the existing one. Otherwise, we
11247 // can end up oscillating between two possible DAGs, for example,
11248 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11249 if (Offset <= uint64_t(GN->getOffset()))
11250 return SDValue();
11251
11252 // Check whether folding this offset is legal. It must not go out of bounds of
11253 // the referenced object to avoid violating the code model, and must be
11254 // smaller than 2^21 because this is the largest offset expressible in all
11255 // object formats.
11256 //
11257 // This check also prevents us from folding negative offsets, which will end
11258 // up being treated in the same way as large positive ones. They could also
11259 // cause code model violations, and aren't really common enough to matter.
11260 if (Offset >= (1 << 21))
11261 return SDValue();
11262
11263 const GlobalValue *GV = GN->getGlobal();
11264 Type *T = GV->getValueType();
11265 if (!T->isSized() ||
11266 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11267 return SDValue();
11268
11269 SDLoc DL(GN);
11270 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11271 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11272 DAG.getConstant(MinOffset, DL, MVT::i64));
11273}
11274
Tim Northover3b0846e2014-05-24 12:50:23 +000011275SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11276 DAGCombinerInfo &DCI) const {
11277 SelectionDAG &DAG = DCI.DAG;
11278 switch (N->getOpcode()) {
11279 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011280 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011281 break;
11282 case ISD::ADD:
11283 case ISD::SUB:
11284 return performAddSubLongCombine(N, DCI, DAG);
11285 case ISD::XOR:
11286 return performXorCombine(N, DAG, DCI, Subtarget);
11287 case ISD::MUL:
11288 return performMulCombine(N, DAG, DCI, Subtarget);
11289 case ISD::SINT_TO_FP:
11290 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011291 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011292 case ISD::FP_TO_SINT:
11293 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011294 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011295 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011296 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011297 case ISD::OR:
11298 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011299 case ISD::SRL:
11300 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011301 case ISD::INTRINSIC_WO_CHAIN:
11302 return performIntrinsicCombine(N, DCI, Subtarget);
11303 case ISD::ANY_EXTEND:
11304 case ISD::ZERO_EXTEND:
11305 case ISD::SIGN_EXTEND:
11306 return performExtendCombine(N, DCI, DAG);
11307 case ISD::BITCAST:
11308 return performBitcastCombine(N, DCI, DAG);
11309 case ISD::CONCAT_VECTORS:
11310 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011311 case ISD::SELECT:
11312 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011313 case ISD::VSELECT:
11314 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011315 case ISD::LOAD:
11316 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11317 return SDValue(N, 0);
11318 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011319 case ISD::STORE:
11320 return performSTORECombine(N, DCI, DAG, Subtarget);
11321 case AArch64ISD::BRCOND:
11322 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011323 case AArch64ISD::TBNZ:
11324 case AArch64ISD::TBZ:
11325 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011326 case AArch64ISD::CSEL:
11327 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011328 case AArch64ISD::DUP:
11329 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011330 case AArch64ISD::NVCAST:
11331 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011332 case ISD::INSERT_VECTOR_ELT:
11333 return performPostLD1Combine(N, DCI, true);
11334 case ISD::INTRINSIC_VOID:
11335 case ISD::INTRINSIC_W_CHAIN:
11336 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11337 case Intrinsic::aarch64_neon_ld2:
11338 case Intrinsic::aarch64_neon_ld3:
11339 case Intrinsic::aarch64_neon_ld4:
11340 case Intrinsic::aarch64_neon_ld1x2:
11341 case Intrinsic::aarch64_neon_ld1x3:
11342 case Intrinsic::aarch64_neon_ld1x4:
11343 case Intrinsic::aarch64_neon_ld2lane:
11344 case Intrinsic::aarch64_neon_ld3lane:
11345 case Intrinsic::aarch64_neon_ld4lane:
11346 case Intrinsic::aarch64_neon_ld2r:
11347 case Intrinsic::aarch64_neon_ld3r:
11348 case Intrinsic::aarch64_neon_ld4r:
11349 case Intrinsic::aarch64_neon_st2:
11350 case Intrinsic::aarch64_neon_st3:
11351 case Intrinsic::aarch64_neon_st4:
11352 case Intrinsic::aarch64_neon_st1x2:
11353 case Intrinsic::aarch64_neon_st1x3:
11354 case Intrinsic::aarch64_neon_st1x4:
11355 case Intrinsic::aarch64_neon_st2lane:
11356 case Intrinsic::aarch64_neon_st3lane:
11357 case Intrinsic::aarch64_neon_st4lane:
11358 return performNEONPostLDSTCombine(N, DCI, DAG);
11359 default:
11360 break;
11361 }
Reid Klecknereb568942018-11-01 18:02:27 +000011362 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011363 case ISD::GlobalAddress:
11364 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011365 }
11366 return SDValue();
11367}
11368
11369// Check if the return value is used as only a return value, as otherwise
11370// we can't perform a tail-call. In particular, we need to check for
11371// target ISD nodes that are returns and any other "odd" constructs
11372// that the generic analysis code won't necessarily catch.
11373bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11374 SDValue &Chain) const {
11375 if (N->getNumValues() != 1)
11376 return false;
11377 if (!N->hasNUsesOfValue(1, 0))
11378 return false;
11379
11380 SDValue TCChain = Chain;
11381 SDNode *Copy = *N->use_begin();
11382 if (Copy->getOpcode() == ISD::CopyToReg) {
11383 // If the copy has a glue operand, we conservatively assume it isn't safe to
11384 // perform a tail call.
11385 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11386 MVT::Glue)
11387 return false;
11388 TCChain = Copy->getOperand(0);
11389 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11390 return false;
11391
11392 bool HasRet = false;
11393 for (SDNode *Node : Copy->uses()) {
11394 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11395 return false;
11396 HasRet = true;
11397 }
11398
11399 if (!HasRet)
11400 return false;
11401
11402 Chain = TCChain;
11403 return true;
11404}
11405
11406// Return whether the an instruction can potentially be optimized to a tail
11407// call. This will cause the optimizers to attempt to move, or duplicate,
11408// return instructions to help enable tail call optimizations for this
11409// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011410bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011411 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011412}
11413
11414bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11415 SDValue &Offset,
11416 ISD::MemIndexedMode &AM,
11417 bool &IsInc,
11418 SelectionDAG &DAG) const {
11419 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11420 return false;
11421
11422 Base = Op->getOperand(0);
11423 // All of the indexed addressing mode instructions take a signed
11424 // 9 bit immediate offset.
11425 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011426 int64_t RHSC = RHS->getSExtValue();
11427 if (Op->getOpcode() == ISD::SUB)
11428 RHSC = -(uint64_t)RHSC;
11429 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011430 return false;
11431 IsInc = (Op->getOpcode() == ISD::ADD);
11432 Offset = Op->getOperand(1);
11433 return true;
11434 }
11435 return false;
11436}
11437
11438bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11439 SDValue &Offset,
11440 ISD::MemIndexedMode &AM,
11441 SelectionDAG &DAG) const {
11442 EVT VT;
11443 SDValue Ptr;
11444 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11445 VT = LD->getMemoryVT();
11446 Ptr = LD->getBasePtr();
11447 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11448 VT = ST->getMemoryVT();
11449 Ptr = ST->getBasePtr();
11450 } else
11451 return false;
11452
11453 bool IsInc;
11454 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11455 return false;
11456 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11457 return true;
11458}
11459
11460bool AArch64TargetLowering::getPostIndexedAddressParts(
11461 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11462 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11463 EVT VT;
11464 SDValue Ptr;
11465 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11466 VT = LD->getMemoryVT();
11467 Ptr = LD->getBasePtr();
11468 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11469 VT = ST->getMemoryVT();
11470 Ptr = ST->getBasePtr();
11471 } else
11472 return false;
11473
11474 bool IsInc;
11475 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11476 return false;
11477 // Post-indexing updates the base, so it's not a valid transform
11478 // if that's not the same as the load's pointer.
11479 if (Ptr != Base)
11480 return false;
11481 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11482 return true;
11483}
11484
Tim Northoverf8bfe212014-07-18 13:07:05 +000011485static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11486 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011487 SDLoc DL(N);
11488 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011489
11490 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11491 return;
11492
Tim Northoverf8bfe212014-07-18 13:07:05 +000011493 Op = SDValue(
11494 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11495 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011496 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011497 0);
11498 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11499 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11500}
11501
Charlie Turner434d4592015-10-16 15:38:25 +000011502static void ReplaceReductionResults(SDNode *N,
11503 SmallVectorImpl<SDValue> &Results,
11504 SelectionDAG &DAG, unsigned InterOp,
11505 unsigned AcrossOp) {
11506 EVT LoVT, HiVT;
11507 SDValue Lo, Hi;
11508 SDLoc dl(N);
11509 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11510 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11511 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11512 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11513 Results.push_back(SplitVal);
11514}
11515
Tim Northover2f32e7f2016-08-04 19:32:28 +000011516static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11517 SDLoc DL(N);
11518 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11519 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11520 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11521 DAG.getConstant(64, DL, MVT::i64)));
11522 return std::make_pair(Lo, Hi);
11523}
11524
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011525// Create an even/odd pair of X registers holding integer value V.
11526static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11527 SDLoc dl(V.getNode());
11528 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11529 SDValue VHi = DAG.getAnyExtOrTrunc(
11530 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11531 dl, MVT::i64);
11532 if (DAG.getDataLayout().isBigEndian())
11533 std::swap (VLo, VHi);
11534 SDValue RegClass =
11535 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11536 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11537 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11538 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11539 return SDValue(
11540 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11541}
11542
Tim Northovercdf15292016-04-14 17:03:29 +000011543static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011544 SmallVectorImpl<SDValue> &Results,
11545 SelectionDAG &DAG,
11546 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011547 assert(N->getValueType(0) == MVT::i128 &&
11548 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011549
11550 if (Subtarget->hasLSE()) {
11551 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11552 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11553 SDValue Ops[] = {
11554 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11555 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11556 N->getOperand(1), // Ptr
11557 N->getOperand(0), // Chain in
11558 };
11559
Chandler Carruth66654b72018-08-14 23:30:32 +000011560 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011561
11562 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011563 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011564 case AtomicOrdering::Monotonic:
11565 Opcode = AArch64::CASPX;
11566 break;
11567 case AtomicOrdering::Acquire:
11568 Opcode = AArch64::CASPAX;
11569 break;
11570 case AtomicOrdering::Release:
11571 Opcode = AArch64::CASPLX;
11572 break;
11573 case AtomicOrdering::AcquireRelease:
11574 case AtomicOrdering::SequentiallyConsistent:
11575 Opcode = AArch64::CASPALX;
11576 break;
11577 default:
11578 llvm_unreachable("Unexpected ordering!");
11579 }
11580
11581 MachineSDNode *CmpSwap = DAG.getMachineNode(
11582 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011583 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011584
11585 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11586 if (DAG.getDataLayout().isBigEndian())
11587 std::swap(SubReg1, SubReg2);
11588 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11589 SDValue(CmpSwap, 0)));
11590 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11591 SDValue(CmpSwap, 0)));
11592 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11593 return;
11594 }
11595
Tim Northover2f32e7f2016-08-04 19:32:28 +000011596 auto Desired = splitInt128(N->getOperand(2), DAG);
11597 auto New = splitInt128(N->getOperand(3), DAG);
11598 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11599 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011600 SDNode *CmpSwap = DAG.getMachineNode(
11601 AArch64::CMP_SWAP_128, SDLoc(N),
11602 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11603
Chandler Carruth66654b72018-08-14 23:30:32 +000011604 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11605 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011606
11607 Results.push_back(SDValue(CmpSwap, 0));
11608 Results.push_back(SDValue(CmpSwap, 1));
11609 Results.push_back(SDValue(CmpSwap, 3));
11610}
11611
Tim Northover3b0846e2014-05-24 12:50:23 +000011612void AArch64TargetLowering::ReplaceNodeResults(
11613 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11614 switch (N->getOpcode()) {
11615 default:
11616 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011617 case ISD::BITCAST:
11618 ReplaceBITCASTResults(N, Results, DAG);
11619 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011620 case ISD::VECREDUCE_ADD:
11621 case ISD::VECREDUCE_SMAX:
11622 case ISD::VECREDUCE_SMIN:
11623 case ISD::VECREDUCE_UMAX:
11624 case ISD::VECREDUCE_UMIN:
11625 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11626 return;
11627
Charlie Turner434d4592015-10-16 15:38:25 +000011628 case AArch64ISD::SADDV:
11629 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11630 return;
11631 case AArch64ISD::UADDV:
11632 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11633 return;
11634 case AArch64ISD::SMINV:
11635 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11636 return;
11637 case AArch64ISD::UMINV:
11638 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11639 return;
11640 case AArch64ISD::SMAXV:
11641 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11642 return;
11643 case AArch64ISD::UMAXV:
11644 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11645 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011646 case ISD::FP_TO_UINT:
11647 case ISD::FP_TO_SINT:
11648 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11649 // Let normal code take care of it by not adding anything to Results.
11650 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011651 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011652 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011653 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011654 }
11655}
11656
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011657bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011658 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11659 return TargetLowering::useLoadStackGuardNode();
11660 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011661}
11662
Sanjay Patel1dd15592015-07-28 23:05:48 +000011663unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011664 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11665 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011666 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011667}
11668
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011669TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011670AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011671 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11672 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011673 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11674 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011675 return TypeWidenVector;
11676
11677 return TargetLoweringBase::getPreferredVectorAction(VT);
11678}
11679
Robin Morisseted3d48f2014-09-03 21:29:59 +000011680// Loads and stores less than 128-bits are already atomic; ones above that
11681// are doomed anyway, so defer to the default libcall and blame the OS when
11682// things go wrong.
11683bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11684 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11685 return Size == 128;
11686}
11687
11688// Loads and stores less than 128-bits are already atomic; ones above that
11689// are doomed anyway, so defer to the default libcall and blame the OS when
11690// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011691TargetLowering::AtomicExpansionKind
11692AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011693 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011694 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011695}
11696
11697// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011698TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011699AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000011700 if (AI->isFloatingPointOperation())
11701 return AtomicExpansionKind::CmpXChg;
11702
Robin Morisseted3d48f2014-09-03 21:29:59 +000011703 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011704 if (Size > 128) return AtomicExpansionKind::None;
11705 // Nand not supported in LSE.
11706 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011707 // Leave 128 bits to LLSC.
11708 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011709}
11710
Alex Bradbury79518b02018-09-19 14:51:42 +000011711TargetLowering::AtomicExpansionKind
11712AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011713 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011714 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011715 if (Subtarget->hasLSE())
11716 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011717 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11718 // implement cmpxchg without spilling. If the address being exchanged is also
11719 // on the stack and close enough to the spill slot, this can lead to a
11720 // situation where the monitor always gets cleared and the atomic operation
11721 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011722 if (getTargetMachine().getOptLevel() == 0)
11723 return AtomicExpansionKind::None;
11724 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011725}
11726
Tim Northover3b0846e2014-05-24 12:50:23 +000011727Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11728 AtomicOrdering Ord) const {
11729 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11730 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011731 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011732
11733 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11734 // intrinsic must return {i64, i64} and we have to recombine them into a
11735 // single i128 here.
11736 if (ValTy->getPrimitiveSizeInBits() == 128) {
11737 Intrinsic::ID Int =
11738 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011739 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011740
11741 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11742 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11743
11744 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11745 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11746 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11747 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11748 return Builder.CreateOr(
11749 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11750 }
11751
11752 Type *Tys[] = { Addr->getType() };
11753 Intrinsic::ID Int =
11754 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011755 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011756
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011757 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11758
11759 const DataLayout &DL = M->getDataLayout();
11760 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11761 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11762
11763 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000011764}
11765
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011766void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11767 IRBuilder<> &Builder) const {
11768 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011769 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011770}
11771
Tim Northover3b0846e2014-05-24 12:50:23 +000011772Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11773 Value *Val, Value *Addr,
11774 AtomicOrdering Ord) const {
11775 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011776 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011777
11778 // Since the intrinsics must have legal type, the i128 intrinsics take two
11779 // parameters: "i64, i64". We must marshal Val into the appropriate form
11780 // before the call.
11781 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11782 Intrinsic::ID Int =
11783 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11784 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11785 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11786
11787 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11788 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11789 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011790 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011791 }
11792
11793 Intrinsic::ID Int =
11794 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11795 Type *Tys[] = { Addr->getType() };
11796 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11797
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011798 const DataLayout &DL = M->getDataLayout();
11799 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
11800 Val = Builder.CreateBitCast(Val, IntValTy);
11801
David Blaikieff6409d2015-05-18 22:13:54 +000011802 return Builder.CreateCall(Stxr,
11803 {Builder.CreateZExtOrBitCast(
11804 Val, Stxr->getFunctionType()->getParamType(0)),
11805 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011806}
Tim Northover3c55cca2014-11-27 21:02:42 +000011807
11808bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11809 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11810 return Ty->isArrayTy();
11811}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011812
11813bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11814 EVT) const {
11815 return false;
11816}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011817
Petr Hoseka7d59162017-02-24 03:10:10 +000011818static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011819 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11820 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011821 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011822 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000011823 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
11824 Offset),
11825 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011826}
11827
Petr Hoseka7d59162017-02-24 03:10:10 +000011828Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11829 // Android provides a fixed TLS slot for the stack cookie. See the definition
11830 // of TLS_SLOT_STACK_GUARD in
11831 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11832 if (Subtarget->isTargetAndroid())
11833 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011834
Petr Hoseka7d59162017-02-24 03:10:10 +000011835 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011836 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011837 if (Subtarget->isTargetFuchsia())
11838 return UseTlsOffset(IRB, -0x10);
11839
11840 return TargetLowering::getIRStackGuard(IRB);
11841}
11842
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011843void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11844 // MSVC CRT provides functionalities for stack protection.
11845 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11846 // MSVC CRT has a global variable holding security cookie.
11847 M.getOrInsertGlobal("__security_cookie",
11848 Type::getInt8PtrTy(M.getContext()));
11849
11850 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000011851 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
11852 "__security_check_cookie", Type::getVoidTy(M.getContext()),
11853 Type::getInt8PtrTy(M.getContext()));
11854 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
11855 F->setCallingConv(CallingConv::Win64);
11856 F->addAttribute(1, Attribute::AttrKind::InReg);
11857 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011858 return;
11859 }
11860 TargetLowering::insertSSPDeclarations(M);
11861}
11862
11863Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
11864 // MSVC CRT has a global variable holding security cookie.
11865 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11866 return M.getGlobalVariable("__security_cookie");
11867 return TargetLowering::getSDagStackGuard(M);
11868}
11869
James Y Knight7976eb52019-02-01 20:43:25 +000011870Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011871 // MSVC CRT has a function to validate security cookie.
11872 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11873 return M.getFunction("__security_check_cookie");
11874 return TargetLowering::getSSPStackGuardCheck(M);
11875}
11876
Petr Hoseka7d59162017-02-24 03:10:10 +000011877Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011878 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11879 // definition of TLS_SLOT_SAFESTACK in
11880 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011881 if (Subtarget->isTargetAndroid())
11882 return UseTlsOffset(IRB, 0x48);
11883
11884 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011885 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011886 if (Subtarget->isTargetFuchsia())
11887 return UseTlsOffset(IRB, -0x8);
11888
11889 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011890}
Manman Rencbe4f942015-12-16 21:04:19 +000011891
Geoff Berry5d534b62017-02-21 18:53:14 +000011892bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11893 const Instruction &AndI) const {
11894 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11895 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11896 // may be beneficial to sink in other cases, but we would have to check that
11897 // the cmp would not get folded into the br to form a cbz for these to be
11898 // beneficial.
11899 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11900 if (!Mask)
11901 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011902 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011903}
11904
Manman Rencbe4f942015-12-16 21:04:19 +000011905void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11906 // Update IsSplitCSR in AArch64unctionInfo.
11907 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11908 AFI->setIsSplitCSR(true);
11909}
11910
11911void AArch64TargetLowering::insertCopiesSplitCSR(
11912 MachineBasicBlock *Entry,
11913 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11914 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11915 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11916 if (!IStart)
11917 return;
11918
11919 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11920 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011921 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011922 for (const MCPhysReg *I = IStart; *I; ++I) {
11923 const TargetRegisterClass *RC = nullptr;
11924 if (AArch64::GPR64RegClass.contains(*I))
11925 RC = &AArch64::GPR64RegClass;
11926 else if (AArch64::FPR64RegClass.contains(*I))
11927 RC = &AArch64::FPR64RegClass;
11928 else
11929 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11930
11931 unsigned NewVR = MRI->createVirtualRegister(RC);
11932 // Create copy from CSR to a virtual register.
11933 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11934 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11935 // nounwind. If we want to generalize this later, we may need to emit
11936 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011937 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011938 Attribute::NoUnwind) &&
11939 "Function should be nounwind in insertCopiesSplitCSR!");
11940 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011941 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011942 .addReg(*I);
11943
Manman Ren4632e8e2016-01-15 20:13:28 +000011944 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011945 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011946 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11947 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011948 .addReg(NewVR);
11949 }
11950}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011951
Reid Klecknerb5180542017-03-21 16:57:19 +000011952bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011953 // Integer division on AArch64 is expensive. However, when aggressively
11954 // optimizing for code size, we prefer to use a div instruction, as it is
11955 // usually smaller than the alternative sequence.
11956 // The exception to this is vector division. Since AArch64 doesn't have vector
11957 // integer division, leaving the division as-is is a loss even in terms of
11958 // size, because it will have to be scalarized, while the alternative code
11959 // sequence can be performed in vector form.
11960 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011961 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011962 return OptSize && !VT.isVector();
11963}
Tim Northoverf19d4672017-02-08 17:57:20 +000011964
Joel Jones07150922018-01-25 21:55:39 +000011965bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11966 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11967}
11968
Tim Northoverf19d4672017-02-08 17:57:20 +000011969unsigned
11970AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011971 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011972 return getPointerTy(DL).getSizeInBits();
11973
11974 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11975}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011976
11977void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11978 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11979 TargetLoweringBase::finalizeLowering(MF);
11980}
Eli Friedmanad1151c2018-11-09 23:33:30 +000011981
11982// Unlike X86, we let frame lowering assign offsets to all catch objects.
11983bool AArch64TargetLowering::needsFixedCatchObjects() const {
11984 return false;
11985}