blob: 2a260dd1611bfa9bd4535022d8d49b0ebf889804 [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
Tim Northover3b0846e2014-05-24 12:50:23 +0000684 // AArch64 doesn't have MUL.2d:
685 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000686 // Custom handling for some quad-vector types to detect MULL.
687 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
688 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
689 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
690
Amara Emersonc9916d72017-05-16 21:29:22 +0000691 // Vector reductions
692 for (MVT VT : MVT::integer_valuetypes()) {
693 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
694 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
695 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
696 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
697 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
698 }
699 for (MVT VT : MVT::fp_valuetypes()) {
700 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
701 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
702 }
703
Tim Northover3b0846e2014-05-24 12:50:23 +0000704 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
705 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
706 // Likewise, narrowing and extending vector loads/stores aren't handled
707 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000708 for (MVT VT : MVT::vector_valuetypes()) {
709 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000710
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000711 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
Craig Topper129d5292018-11-29 19:36:17 +0000712 setOperationAction(ISD::MULHS, VT, Legal);
713 setOperationAction(ISD::MULHU, VT, Legal);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000714 } else {
715 setOperationAction(ISD::MULHS, VT, Expand);
716 setOperationAction(ISD::MULHU, VT, Expand);
717 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000718 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000719 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000720
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000721 setOperationAction(ISD::BSWAP, VT, Expand);
Nikita Popova3be17e2019-02-12 18:55:53 +0000722 setOperationAction(ISD::CTTZ, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000723
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000724 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000725 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000726 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
727 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
728 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
729 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000730 }
731
732 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000733 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000734 setOperationAction(ISD::FFLOOR, Ty, Legal);
735 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
736 setOperationAction(ISD::FCEIL, Ty, Legal);
737 setOperationAction(ISD::FRINT, Ty, Legal);
738 setOperationAction(ISD::FTRUNC, Ty, Legal);
739 setOperationAction(ISD::FROUND, Ty, Legal);
740 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000741
742 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000743 }
James Molloyf089ab72014-08-06 10:42:18 +0000744
Matthias Braun651cff42016-06-02 18:03:53 +0000745 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000746}
747
Craig Topper18e69f42016-04-15 06:20:21 +0000748void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000749 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000750
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000751 if (VT.isFloatingPoint()) {
752 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
753 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
754 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000755 }
756
757 // Mark vector float intrinsics as expand.
758 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000759 setOperationAction(ISD::FSIN, VT, Expand);
760 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000761 setOperationAction(ISD::FPOW, VT, Expand);
762 setOperationAction(ISD::FLOG, VT, Expand);
763 setOperationAction(ISD::FLOG2, VT, Expand);
764 setOperationAction(ISD::FLOG10, VT, Expand);
765 setOperationAction(ISD::FEXP, VT, Expand);
766 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000767
768 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000769 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000770 }
771
Craig Topper18e69f42016-04-15 06:20:21 +0000772 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
773 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
774 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
775 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
776 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
777 setOperationAction(ISD::SRA, VT, Custom);
778 setOperationAction(ISD::SRL, VT, Custom);
779 setOperationAction(ISD::SHL, VT, Custom);
780 setOperationAction(ISD::AND, VT, Custom);
781 setOperationAction(ISD::OR, VT, Custom);
782 setOperationAction(ISD::SETCC, VT, Custom);
783 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000784
Craig Topper18e69f42016-04-15 06:20:21 +0000785 setOperationAction(ISD::SELECT, VT, Expand);
786 setOperationAction(ISD::SELECT_CC, VT, Expand);
787 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000788 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000789 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000790
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000791 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000792 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000793 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000794
Craig Topper18e69f42016-04-15 06:20:21 +0000795 setOperationAction(ISD::UDIV, VT, Expand);
796 setOperationAction(ISD::SDIV, VT, Expand);
797 setOperationAction(ISD::UREM, VT, Expand);
798 setOperationAction(ISD::SREM, VT, Expand);
799 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000800
Craig Topper18e69f42016-04-15 06:20:21 +0000801 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
802 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000803
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000804 if (!VT.isFloatingPoint())
805 setOperationAction(ISD::ABS, VT, Legal);
806
Hal Finkelcd8664c2015-12-11 23:11:52 +0000807 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000808 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000809 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000810 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000811
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000812 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
813 if (VT.isFloatingPoint() &&
814 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000815 for (unsigned Opcode :
816 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000817 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000818
Tim Northover3b0846e2014-05-24 12:50:23 +0000819 if (Subtarget->isLittleEndian()) {
820 for (unsigned im = (unsigned)ISD::PRE_INC;
821 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000822 setIndexedLoadAction(im, VT, Legal);
823 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000824 }
825 }
826}
827
828void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
829 addRegisterClass(VT, &AArch64::FPR64RegClass);
830 addTypeForNEON(VT, MVT::v2i32);
831}
832
833void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
834 addRegisterClass(VT, &AArch64::FPR128RegClass);
835 addTypeForNEON(VT, MVT::v4i32);
836}
837
Mehdi Amini44ede332015-07-09 02:09:04 +0000838EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
839 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000840 if (!VT.isVector())
841 return MVT::i32;
842 return VT.changeVectorElementTypeToInteger();
843}
844
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000845static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
846 const APInt &Demanded,
847 TargetLowering::TargetLoweringOpt &TLO,
848 unsigned NewOpc) {
849 uint64_t OldImm = Imm, NewImm, Enc;
850 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
851
852 // Return if the immediate is already all zeros, all ones, a bimm32 or a
853 // bimm64.
854 if (Imm == 0 || Imm == Mask ||
855 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
856 return false;
857
858 unsigned EltSize = Size;
859 uint64_t DemandedBits = Demanded.getZExtValue();
860
861 // Clear bits that are not demanded.
862 Imm &= DemandedBits;
863
864 while (true) {
865 // The goal here is to set the non-demanded bits in a way that minimizes
866 // the number of switching between 0 and 1. In order to achieve this goal,
867 // we set the non-demanded bits to the value of the preceding demanded bits.
868 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
869 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
870 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
871 // The final result is 0b11000011.
872 uint64_t NonDemandedBits = ~DemandedBits;
873 uint64_t InvertedImm = ~Imm & DemandedBits;
874 uint64_t RotatedImm =
875 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
876 NonDemandedBits;
877 uint64_t Sum = RotatedImm + NonDemandedBits;
878 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
879 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
880 NewImm = (Imm | Ones) & Mask;
881
882 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
883 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
884 // we halve the element size and continue the search.
885 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
886 break;
887
888 // We cannot shrink the element size any further if it is 2-bits.
889 if (EltSize == 2)
890 return false;
891
892 EltSize /= 2;
893 Mask >>= EltSize;
894 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
895
896 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
897 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
898 return false;
899
900 // Merge the upper and lower halves of Imm and DemandedBits.
901 Imm |= Hi;
902 DemandedBits |= DemandedBitsHi;
903 }
904
905 ++NumOptimizedImms;
906
907 // Replicate the element across the register width.
908 while (EltSize < Size) {
909 NewImm |= NewImm << EltSize;
910 EltSize *= 2;
911 }
912
913 (void)OldImm;
914 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
915 "demanded bits should never be altered");
916 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
917
918 // Create the new constant immediate node.
919 EVT VT = Op.getValueType();
920 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000921 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000922
923 // If the new constant immediate is all-zeros or all-ones, let the target
924 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000925 if (NewImm == 0 || NewImm == OrigMask) {
926 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
927 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000928 // Otherwise, create a machine node so that target independent DAG combine
929 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000930 } else {
931 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
932 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
933 New = SDValue(
934 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
935 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000936
937 return TLO.CombineTo(Op, New);
938}
939
940bool AArch64TargetLowering::targetShrinkDemandedConstant(
941 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
942 // Delay this optimization to as late as possible.
943 if (!TLO.LegalOps)
944 return false;
945
946 if (!EnableOptimizeLogicalImm)
947 return false;
948
949 EVT VT = Op.getValueType();
950 if (VT.isVector())
951 return false;
952
953 unsigned Size = VT.getSizeInBits();
954 assert((Size == 32 || Size == 64) &&
955 "i32 or i64 is expected after legalization.");
956
957 // Exit early if we demand all bits.
958 if (Demanded.countPopulation() == Size)
959 return false;
960
961 unsigned NewOpc;
962 switch (Op.getOpcode()) {
963 default:
964 return false;
965 case ISD::AND:
966 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
967 break;
968 case ISD::OR:
969 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
970 break;
971 case ISD::XOR:
972 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
973 break;
974 }
975 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
976 if (!C)
977 return false;
978 uint64_t Imm = C->getZExtValue();
979 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
980}
981
Tim Northover3b0846e2014-05-24 12:50:23 +0000982/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000983/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000984void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000985 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000986 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000987 switch (Op.getOpcode()) {
988 default:
989 break;
990 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000991 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +0000992 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
993 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +0000994 Known.Zero &= Known2.Zero;
995 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +0000996 break;
997 }
998 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000999 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001000 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1001 switch (IntID) {
1002 default: return;
1003 case Intrinsic::aarch64_ldaxr:
1004 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001005 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001006 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001007 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001008 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001009 return;
1010 }
1011 }
1012 break;
1013 }
1014 case ISD::INTRINSIC_WO_CHAIN:
1015 case ISD::INTRINSIC_VOID: {
1016 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1017 switch (IntNo) {
1018 default:
1019 break;
1020 case Intrinsic::aarch64_neon_umaxv:
1021 case Intrinsic::aarch64_neon_uminv: {
1022 // Figure out the datatype of the vector operand. The UMINV instruction
1023 // will zero extend the result, so we can mark as known zero all the
1024 // bits larger than the element datatype. 32-bit or larget doesn't need
1025 // this as those are legal types and will be handled by isel directly.
1026 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001027 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001028 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1029 assert(BitWidth >= 8 && "Unexpected width!");
1030 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001031 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001032 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1033 assert(BitWidth >= 16 && "Unexpected width!");
1034 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001035 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001036 }
1037 break;
1038 } break;
1039 }
1040 }
1041 }
1042}
1043
Mehdi Aminieaabc512015-07-09 15:12:23 +00001044MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1045 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001046 return MVT::i64;
1047}
1048
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001049bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1050 unsigned AddrSpace,
1051 unsigned Align,
1052 bool *Fast) const {
1053 if (Subtarget->requiresStrictAlign())
1054 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001055
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001056 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001057 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1058 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001059 // See comments in performSTORECombine() for more details about
1060 // these conditions.
1061
1062 // Code that uses clang vector extensions can mark that it
1063 // wants unaligned accesses to be treated as fast by
1064 // underspecifying alignment to be 1 or 2.
1065 Align <= 2 ||
1066
1067 // Disregard v2i64. Memcpy lowering produces those and splitting
1068 // them regresses performance on micro-benchmarks and olden/bh.
1069 VT == MVT::v2i64;
1070 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001071 return true;
1072}
1073
Tim Northover3b0846e2014-05-24 12:50:23 +00001074FastISel *
1075AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1076 const TargetLibraryInfo *libInfo) const {
1077 return AArch64::createFastISel(funcInfo, libInfo);
1078}
1079
1080const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001081 switch ((AArch64ISD::NodeType)Opcode) {
1082 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001083 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1084 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001085 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001086 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1087 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1088 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1089 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1090 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1091 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1092 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1093 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1094 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1095 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001096 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001097 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1098 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1099 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1100 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1101 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1102 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1103 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001104 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1105 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1106 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001107 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001108 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1109 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1110 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1111 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1112 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1113 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1114 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1115 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1116 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1117 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1118 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1119 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1120 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1121 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1122 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1123 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1124 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1125 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1126 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1127 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1128 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1129 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1130 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1131 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1132 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1133 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1134 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1135 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1136 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1137 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1138 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1139 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1140 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1141 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1142 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1143 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1144 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1145 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1146 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1147 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1148 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1149 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1150 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1151 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1152 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1153 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1154 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1155 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001156 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1157 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1158 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1159 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1160 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1161 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001162 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1163 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1164 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1165 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1166 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1167 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1168 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001169 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001170 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1171 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001172 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001173 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1174 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1175 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1176 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1177 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1178 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1179 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1180 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1181 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1182 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1183 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1184 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1185 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1186 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1187 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1188 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1189 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1190 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1191 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1192 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1193 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1194 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1195 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1196 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1197 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1198 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1199 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1200 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1201 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001202 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1203 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001204 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001205 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1206 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1207 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001208 }
Matthias Braund04893f2015-05-07 21:33:59 +00001209 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001210}
1211
1212MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001213AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001214 MachineBasicBlock *MBB) const {
1215 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1216 // phi node:
1217
1218 // OrigBB:
1219 // [... previous instrs leading to comparison ...]
1220 // b.ne TrueBB
1221 // b EndBB
1222 // TrueBB:
1223 // ; Fallthrough
1224 // EndBB:
1225 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1226
Tim Northover3b0846e2014-05-24 12:50:23 +00001227 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001228 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001229 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001230 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001231 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001232
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001233 unsigned DestReg = MI.getOperand(0).getReg();
1234 unsigned IfTrueReg = MI.getOperand(1).getReg();
1235 unsigned IfFalseReg = MI.getOperand(2).getReg();
1236 unsigned CondCode = MI.getOperand(3).getImm();
1237 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001238
1239 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1240 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1241 MF->insert(It, TrueBB);
1242 MF->insert(It, EndBB);
1243
1244 // Transfer rest of current basic-block to EndBB
1245 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1246 MBB->end());
1247 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1248
1249 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1250 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1251 MBB->addSuccessor(TrueBB);
1252 MBB->addSuccessor(EndBB);
1253
1254 // TrueBB falls through to the end.
1255 TrueBB->addSuccessor(EndBB);
1256
1257 if (!NZCVKilled) {
1258 TrueBB->addLiveIn(AArch64::NZCV);
1259 EndBB->addLiveIn(AArch64::NZCV);
1260 }
1261
1262 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1263 .addReg(IfTrueReg)
1264 .addMBB(TrueBB)
1265 .addReg(IfFalseReg)
1266 .addMBB(MBB);
1267
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001268 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001269 return EndBB;
1270}
1271
Eli Friedmanad1151c2018-11-09 23:33:30 +00001272MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1273 MachineInstr &MI, MachineBasicBlock *BB) const {
1274 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1275 BB->getParent()->getFunction().getPersonalityFn())) &&
1276 "SEH does not use catchret!");
1277 return BB;
1278}
1279
1280MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1281 MachineInstr &MI, MachineBasicBlock *BB) const {
1282 MI.eraseFromParent();
1283 return BB;
1284}
1285
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001286MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1287 MachineInstr &MI, MachineBasicBlock *BB) const {
1288 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001289 default:
1290#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001291 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001292#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001293 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001294
1295 case AArch64::F128CSEL:
1296 return EmitF128CSEL(MI, BB);
1297
1298 case TargetOpcode::STACKMAP:
1299 case TargetOpcode::PATCHPOINT:
1300 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001301
1302 case AArch64::CATCHRET:
1303 return EmitLoweredCatchRet(MI, BB);
1304 case AArch64::CATCHPAD:
1305 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001306 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001307}
1308
1309//===----------------------------------------------------------------------===//
1310// AArch64 Lowering private implementation.
1311//===----------------------------------------------------------------------===//
1312
1313//===----------------------------------------------------------------------===//
1314// Lowering Code
1315//===----------------------------------------------------------------------===//
1316
1317/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1318/// CC
1319static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1320 switch (CC) {
1321 default:
1322 llvm_unreachable("Unknown condition code!");
1323 case ISD::SETNE:
1324 return AArch64CC::NE;
1325 case ISD::SETEQ:
1326 return AArch64CC::EQ;
1327 case ISD::SETGT:
1328 return AArch64CC::GT;
1329 case ISD::SETGE:
1330 return AArch64CC::GE;
1331 case ISD::SETLT:
1332 return AArch64CC::LT;
1333 case ISD::SETLE:
1334 return AArch64CC::LE;
1335 case ISD::SETUGT:
1336 return AArch64CC::HI;
1337 case ISD::SETUGE:
1338 return AArch64CC::HS;
1339 case ISD::SETULT:
1340 return AArch64CC::LO;
1341 case ISD::SETULE:
1342 return AArch64CC::LS;
1343 }
1344}
1345
1346/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1347static void changeFPCCToAArch64CC(ISD::CondCode CC,
1348 AArch64CC::CondCode &CondCode,
1349 AArch64CC::CondCode &CondCode2) {
1350 CondCode2 = AArch64CC::AL;
1351 switch (CC) {
1352 default:
1353 llvm_unreachable("Unknown FP condition!");
1354 case ISD::SETEQ:
1355 case ISD::SETOEQ:
1356 CondCode = AArch64CC::EQ;
1357 break;
1358 case ISD::SETGT:
1359 case ISD::SETOGT:
1360 CondCode = AArch64CC::GT;
1361 break;
1362 case ISD::SETGE:
1363 case ISD::SETOGE:
1364 CondCode = AArch64CC::GE;
1365 break;
1366 case ISD::SETOLT:
1367 CondCode = AArch64CC::MI;
1368 break;
1369 case ISD::SETOLE:
1370 CondCode = AArch64CC::LS;
1371 break;
1372 case ISD::SETONE:
1373 CondCode = AArch64CC::MI;
1374 CondCode2 = AArch64CC::GT;
1375 break;
1376 case ISD::SETO:
1377 CondCode = AArch64CC::VC;
1378 break;
1379 case ISD::SETUO:
1380 CondCode = AArch64CC::VS;
1381 break;
1382 case ISD::SETUEQ:
1383 CondCode = AArch64CC::EQ;
1384 CondCode2 = AArch64CC::VS;
1385 break;
1386 case ISD::SETUGT:
1387 CondCode = AArch64CC::HI;
1388 break;
1389 case ISD::SETUGE:
1390 CondCode = AArch64CC::PL;
1391 break;
1392 case ISD::SETLT:
1393 case ISD::SETULT:
1394 CondCode = AArch64CC::LT;
1395 break;
1396 case ISD::SETLE:
1397 case ISD::SETULE:
1398 CondCode = AArch64CC::LE;
1399 break;
1400 case ISD::SETNE:
1401 case ISD::SETUNE:
1402 CondCode = AArch64CC::NE;
1403 break;
1404 }
1405}
1406
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001407/// Convert a DAG fp condition code to an AArch64 CC.
1408/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1409/// should be AND'ed instead of OR'ed.
1410static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1411 AArch64CC::CondCode &CondCode,
1412 AArch64CC::CondCode &CondCode2) {
1413 CondCode2 = AArch64CC::AL;
1414 switch (CC) {
1415 default:
1416 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1417 assert(CondCode2 == AArch64CC::AL);
1418 break;
1419 case ISD::SETONE:
1420 // (a one b)
1421 // == ((a olt b) || (a ogt b))
1422 // == ((a ord b) && (a une b))
1423 CondCode = AArch64CC::VC;
1424 CondCode2 = AArch64CC::NE;
1425 break;
1426 case ISD::SETUEQ:
1427 // (a ueq b)
1428 // == ((a uno b) || (a oeq b))
1429 // == ((a ule b) && (a uge b))
1430 CondCode = AArch64CC::PL;
1431 CondCode2 = AArch64CC::LE;
1432 break;
1433 }
1434}
1435
Tim Northover3b0846e2014-05-24 12:50:23 +00001436/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1437/// CC usable with the vector instructions. Fewer operations are available
1438/// without a real NZCV register, so we have to use less efficient combinations
1439/// to get the same effect.
1440static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1441 AArch64CC::CondCode &CondCode,
1442 AArch64CC::CondCode &CondCode2,
1443 bool &Invert) {
1444 Invert = false;
1445 switch (CC) {
1446 default:
1447 // Mostly the scalar mappings work fine.
1448 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1449 break;
1450 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001451 Invert = true;
1452 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001453 case ISD::SETO:
1454 CondCode = AArch64CC::MI;
1455 CondCode2 = AArch64CC::GE;
1456 break;
1457 case ISD::SETUEQ:
1458 case ISD::SETULT:
1459 case ISD::SETULE:
1460 case ISD::SETUGT:
1461 case ISD::SETUGE:
1462 // All of the compare-mask comparisons are ordered, but we can switch
1463 // between the two by a double inversion. E.g. ULE == !OGT.
1464 Invert = true;
1465 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1466 break;
1467 }
1468}
1469
1470static bool isLegalArithImmed(uint64_t C) {
1471 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001472 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001473 LLVM_DEBUG(dbgs() << "Is imm " << C
1474 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001475 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001476}
1477
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001478// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1479// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1480// can be set differently by this operation. It comes down to whether
1481// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1482// everything is fine. If not then the optimization is wrong. Thus general
1483// comparisons are only valid if op2 != 0.
1484//
1485// So, finally, the only LLVM-native comparisons that don't mention C and V
1486// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1487// the absence of information about op2.
1488static bool isCMN(SDValue Op, ISD::CondCode CC) {
1489 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1490 (CC == ISD::SETEQ || CC == ISD::SETNE);
1491}
1492
Tim Northover3b0846e2014-05-24 12:50:23 +00001493static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001494 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001495 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001496 const bool FullFP16 =
1497 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001498
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001499 if (VT.isFloatingPoint()) {
1500 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001501 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001502 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1503 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001504 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001505 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001506 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001507 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001508
1509 // The CMP instruction is just an alias for SUBS, and representing it as
1510 // SUBS means that it's possible to get CSE with subtract operations.
1511 // A later phase can perform the optimization of setting the destination
1512 // register to WZR/XZR if it ends up being unused.
1513 unsigned Opcode = AArch64ISD::SUBS;
1514
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001515 if (isCMN(RHS, CC)) {
1516 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001517 Opcode = AArch64ISD::ADDS;
1518 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001519 } else if (isCMN(LHS, CC)) {
1520 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1521 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1522 Opcode = AArch64ISD::ADDS;
1523 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001524 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001525 !isUnsignedIntSetCC(CC)) {
1526 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1527 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1528 // of the signed comparisons.
1529 Opcode = AArch64ISD::ANDS;
1530 RHS = LHS.getOperand(1);
1531 LHS = LHS.getOperand(0);
1532 }
1533
Matthias Braunaf7d7702015-07-16 20:02:37 +00001534 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001535 .getValue(1);
1536}
1537
Matthias Braunaf7d7702015-07-16 20:02:37 +00001538/// \defgroup AArch64CCMP CMP;CCMP matching
1539///
1540/// These functions deal with the formation of CMP;CCMP;... sequences.
1541/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1542/// a comparison. They set the NZCV flags to a predefined value if their
1543/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001544/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001545/// expressed as:
1546/// cmp A
1547/// ccmp B, inv(CB), CA
1548/// check for CB flags
1549///
Matthias Braund0412122018-12-06 01:40:23 +00001550/// This naturally lets us implement chains of AND operations with SETCC
1551/// operands. And we can even implement some other situations by transforming
1552/// them:
1553/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1554/// negating the flags used in a CCMP/FCCMP operations.
1555/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1556/// by negating the flags we test for afterwards. i.e.
1557/// NEG (CMP CCMP CCCMP ...) can be implemented.
1558/// - Note that we can only ever negate all previously processed results.
1559/// What we can not implement by flipping the flags to test is a negation
1560/// of two sub-trees (because the negation affects all sub-trees emitted so
1561/// far, so the 2nd sub-tree we emit would also affect the first).
1562/// With those tools we can implement some OR operations:
1563/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1564/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1565/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1566/// elimination rules from earlier to implement the whole thing as a
1567/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001568///
Matthias Braund0412122018-12-06 01:40:23 +00001569/// As complete example:
1570/// or (or (setCA (cmp A)) (setCB (cmp B)))
1571/// (and (setCC (cmp C)) (setCD (cmp D)))"
1572/// can be reassociated to:
1573/// or (and (setCC (cmp C)) setCD (cmp D))
1574// (or (setCA (cmp A)) (setCB (cmp B)))
1575/// can be transformed to:
1576/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1577/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1578/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001579/// cmp C
1580/// ccmp D, inv(CD), CC
1581/// ccmp A, CA, inv(CD)
1582/// ccmp B, CB, inv(CA)
1583/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001584///
1585/// A counterexample is "or (and A B) (and C D)" which translates to
1586/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1587/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001588/// @{
1589
Geoff Berrye41c2df2015-07-20 22:03:52 +00001590/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001591static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1592 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001593 AArch64CC::CondCode Predicate,
1594 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001595 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001596 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001597 const bool FullFP16 =
1598 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1599
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001600 if (LHS.getValueType().isFloatingPoint()) {
1601 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001602 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001603 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1604 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1605 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001606 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001607 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001608 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001609 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001610 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1611 Opcode = AArch64ISD::CCMN;
1612 RHS = RHS.getOperand(1);
1613 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001614 }
1615 if (Opcode == 0)
1616 Opcode = AArch64ISD::CCMP;
1617
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001618 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1619 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1620 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001621 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1622 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1623}
1624
Matthias Braun96d12512018-11-06 03:15:22 +00001625/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1626/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001627/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1628/// changing the conditions on the SETCC tests.
1629/// (this means we can call emitConjunctionRec() with
1630/// Negate==true on this sub-tree)
1631/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1632/// cannot do the negation naturally. We are required to
1633/// emit the subtree first in this case.
1634/// \param WillNegate Is true if are called when the result of this
1635/// subexpression must be negated. This happens when the
1636/// outer expression is an OR. We can use this fact to know
1637/// that we have a double negation (or (or ...) ...) that
1638/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001639static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001640 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001641 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001642 if (!Val.hasOneUse())
1643 return false;
1644 unsigned Opcode = Val->getOpcode();
1645 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001646 if (Val->getOperand(0).getValueType() == MVT::f128)
1647 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001648 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001649 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001650 return true;
1651 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001652 // Protect against exponential runtime and stack overflow.
1653 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001654 return false;
1655 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001656 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001657 SDValue O0 = Val->getOperand(0);
1658 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001659 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001660 bool MustBeFirstL;
1661 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001662 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001663 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001664 bool MustBeFirstR;
1665 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001666 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001667
Matthias Braund0412122018-12-06 01:40:23 +00001668 if (MustBeFirstL && MustBeFirstR)
1669 return false;
1670
1671 if (IsOR) {
1672 // For an OR expression we need to be able to naturally negate at least
1673 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001674 if (!CanNegateL && !CanNegateR)
1675 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001676 // If we the result of the OR will be negated and we can naturally negate
1677 // the leafs, then this sub-tree as a whole negates naturally.
1678 CanNegate = WillNegate && CanNegateL && CanNegateR;
1679 // If we cannot naturally negate the whole sub-tree, then this must be
1680 // emitted first.
1681 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001682 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001683 assert(Opcode == ISD::AND && "Must be OR or AND");
1684 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001685 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001686 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001687 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001688 return true;
1689 }
1690 return false;
1691}
1692
1693/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1694/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1695/// Tries to transform the given i1 producing node @p Val to a series compare
1696/// and conditional compare operations. @returns an NZCV flags producing node
1697/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1698/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001699/// \p Negate is true if we want this sub-tree being negated just by changing
1700/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001701static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001702 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001703 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001704 // We're at a tree leaf, produce a conditional comparison operation.
1705 unsigned Opcode = Val->getOpcode();
1706 if (Opcode == ISD::SETCC) {
1707 SDValue LHS = Val->getOperand(0);
1708 SDValue RHS = Val->getOperand(1);
1709 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1710 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001711 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001712 CC = getSetCCInverse(CC, isInteger);
1713 SDLoc DL(Val);
1714 // Determine OutCC and handle FP special case.
1715 if (isInteger) {
1716 OutCC = changeIntCCToAArch64CC(CC);
1717 } else {
1718 assert(LHS.getValueType().isFloatingPoint());
1719 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001720 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1721 // Some floating point conditions can't be tested with a single condition
1722 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001723 if (ExtraCC != AArch64CC::AL) {
1724 SDValue ExtraCmp;
1725 if (!CCOp.getNode())
1726 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001727 else
1728 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001729 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001730 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001731 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001732 }
1733 }
1734
1735 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001736 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001737 return emitComparison(LHS, RHS, CC, DL, DAG);
1738 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001739 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001740 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001741 }
Matthias Braund0412122018-12-06 01:40:23 +00001742 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001743
Matthias Braund0412122018-12-06 01:40:23 +00001744 bool IsOR = Opcode == ISD::OR;
1745
Matthias Braunaf7d7702015-07-16 20:02:37 +00001746 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001747 bool CanNegateL;
1748 bool MustBeFirstL;
1749 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1750 assert(ValidL && "Valid conjunction/disjunction tree");
1751 (void)ValidL;
1752
Matthias Braunaf7d7702015-07-16 20:02:37 +00001753 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001754 bool CanNegateR;
1755 bool MustBeFirstR;
1756 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1757 assert(ValidR && "Valid conjunction/disjunction tree");
1758 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001759
Matthias Braund0412122018-12-06 01:40:23 +00001760 // Swap sub-tree that must come first to the right side.
1761 if (MustBeFirstL) {
1762 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1763 std::swap(LHS, RHS);
1764 std::swap(CanNegateL, CanNegateR);
1765 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001766 }
1767
Matthias Braund0412122018-12-06 01:40:23 +00001768 bool NegateR;
1769 bool NegateAfterR;
1770 bool NegateL;
1771 bool NegateAfterAll;
1772 if (Opcode == ISD::OR) {
1773 // Swap the sub-tree that we can negate naturally to the left.
1774 if (!CanNegateL) {
1775 assert(CanNegateR && "at least one side must be negatable");
1776 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1777 assert(!Negate);
1778 std::swap(LHS, RHS);
1779 NegateR = false;
1780 NegateAfterR = true;
1781 } else {
1782 // Negate the left sub-tree if possible, otherwise negate the result.
1783 NegateR = CanNegateR;
1784 NegateAfterR = !CanNegateR;
1785 }
1786 NegateL = true;
1787 NegateAfterAll = !Negate;
1788 } else {
1789 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1790 assert(!Negate && "Valid conjunction/disjunction tree");
1791
1792 NegateL = false;
1793 NegateR = false;
1794 NegateAfterR = false;
1795 NegateAfterAll = false;
1796 }
1797
1798 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001799 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001800 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1801 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001802 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001803 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1804 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001805 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1806 return CmpL;
1807}
1808
Matthias Braun96d12512018-11-06 03:15:22 +00001809/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1810/// In some cases this is even possible with OR operations in the expression.
1811/// See \ref AArch64CCMP.
1812/// \see emitConjunctionRec().
1813static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1814 AArch64CC::CondCode &OutCC) {
1815 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001816 bool DummyMustBeFirst;
1817 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001818 return SDValue();
1819
Matthias Braun96d12512018-11-06 03:15:22 +00001820 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001821}
1822
Matthias Braunaf7d7702015-07-16 20:02:37 +00001823/// @}
1824
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001825/// Returns how profitable it is to fold a comparison's operand's shift and/or
1826/// extension operations.
1827static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1828 auto isSupportedExtend = [&](SDValue V) {
1829 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1830 return true;
1831
1832 if (V.getOpcode() == ISD::AND)
1833 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1834 uint64_t Mask = MaskCst->getZExtValue();
1835 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1836 }
1837
1838 return false;
1839 };
1840
1841 if (!Op.hasOneUse())
1842 return 0;
1843
1844 if (isSupportedExtend(Op))
1845 return 1;
1846
1847 unsigned Opc = Op.getOpcode();
1848 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1849 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1850 uint64_t Shift = ShiftCst->getZExtValue();
1851 if (isSupportedExtend(Op.getOperand(0)))
1852 return (Shift <= 4) ? 2 : 1;
1853 EVT VT = Op.getValueType();
1854 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1855 return 1;
1856 }
1857
1858 return 0;
1859}
1860
Tim Northover3b0846e2014-05-24 12:50:23 +00001861static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001862 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001863 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001864 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1865 EVT VT = RHS.getValueType();
1866 uint64_t C = RHSC->getZExtValue();
1867 if (!isLegalArithImmed(C)) {
1868 // Constant does not fit, try adjusting it by one?
1869 switch (CC) {
1870 default:
1871 break;
1872 case ISD::SETLT:
1873 case ISD::SETGE:
1874 if ((VT == MVT::i32 && C != 0x80000000 &&
1875 isLegalArithImmed((uint32_t)(C - 1))) ||
1876 (VT == MVT::i64 && C != 0x80000000ULL &&
1877 isLegalArithImmed(C - 1ULL))) {
1878 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1879 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001880 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001881 }
1882 break;
1883 case ISD::SETULT:
1884 case ISD::SETUGE:
1885 if ((VT == MVT::i32 && C != 0 &&
1886 isLegalArithImmed((uint32_t)(C - 1))) ||
1887 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1888 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1889 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001890 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001891 }
1892 break;
1893 case ISD::SETLE:
1894 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001895 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001896 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001897 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001898 isLegalArithImmed(C + 1ULL))) {
1899 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1900 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001901 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001902 }
1903 break;
1904 case ISD::SETULE:
1905 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001906 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001907 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001908 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001909 isLegalArithImmed(C + 1ULL))) {
1910 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1911 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001912 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001913 }
1914 break;
1915 }
1916 }
1917 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001918
1919 // Comparisons are canonicalized so that the RHS operand is simpler than the
1920 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1921 // can fold some shift+extend operations on the RHS operand, so swap the
1922 // operands if that can be done.
1923 //
1924 // For example:
1925 // lsl w13, w11, #1
1926 // cmp w13, w12
1927 // can be turned into:
1928 // cmp w12, w11, lsl #1
1929 if (!isa<ConstantSDNode>(RHS) ||
1930 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1931 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1932
1933 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1934 std::swap(LHS, RHS);
1935 CC = ISD::getSetCCSwappedOperands(CC);
1936 }
1937 }
1938
Matthias Braunaf7d7702015-07-16 20:02:37 +00001939 SDValue Cmp;
1940 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001941 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001942 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1943
1944 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1945 // For the i8 operand, the largest immediate is 255, so this can be easily
1946 // encoded in the compare instruction. For the i16 operand, however, the
1947 // largest immediate cannot be encoded in the compare.
1948 // Therefore, use a sign extending load and cmn to avoid materializing the
1949 // -1 constant. For example,
1950 // movz w1, #65535
1951 // ldrh w0, [x0, #0]
1952 // cmp w0, w1
1953 // >
1954 // ldrsh w0, [x0, #0]
1955 // cmn w0, #1
1956 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1957 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001958 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001959 // transformation is profitable.
1960 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1961 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1962 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1963 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1964 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1965 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1966 SDValue SExt =
1967 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1968 DAG.getValueType(MVT::i16));
1969 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1970 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001971 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001972 AArch64CC = changeIntCCToAArch64CC(CC);
1973 }
1974 }
1975
1976 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00001977 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001978 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1979 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001980 }
1981 }
1982 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001983
1984 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001985 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001986 AArch64CC = changeIntCCToAArch64CC(CC);
1987 }
1988 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001989 return Cmp;
1990}
1991
1992static std::pair<SDValue, SDValue>
1993getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1994 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1995 "Unsupported value type");
1996 SDValue Value, Overflow;
1997 SDLoc DL(Op);
1998 SDValue LHS = Op.getOperand(0);
1999 SDValue RHS = Op.getOperand(1);
2000 unsigned Opc = 0;
2001 switch (Op.getOpcode()) {
2002 default:
2003 llvm_unreachable("Unknown overflow instruction!");
2004 case ISD::SADDO:
2005 Opc = AArch64ISD::ADDS;
2006 CC = AArch64CC::VS;
2007 break;
2008 case ISD::UADDO:
2009 Opc = AArch64ISD::ADDS;
2010 CC = AArch64CC::HS;
2011 break;
2012 case ISD::SSUBO:
2013 Opc = AArch64ISD::SUBS;
2014 CC = AArch64CC::VS;
2015 break;
2016 case ISD::USUBO:
2017 Opc = AArch64ISD::SUBS;
2018 CC = AArch64CC::LO;
2019 break;
2020 // Multiply needs a little bit extra work.
2021 case ISD::SMULO:
2022 case ISD::UMULO: {
2023 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002024 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002025 if (Op.getValueType() == MVT::i32) {
2026 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2027 // For a 32 bit multiply with overflow check we want the instruction
2028 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2029 // need to generate the following pattern:
2030 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2031 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2032 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2033 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2034 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002035 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002036 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2037 // operation. We need to clear out the upper 32 bits, because we used a
2038 // widening multiply that wrote all 64 bits. In the end this should be a
2039 // noop.
2040 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2041 if (IsSigned) {
2042 // The signed overflow check requires more than just a simple check for
2043 // any bit set in the upper 32 bits of the result. These bits could be
2044 // just the sign bits of a negative number. To perform the overflow
2045 // check we have to arithmetic shift right the 32nd bit of the result by
2046 // 31 bits. Then we compare the result to the upper 32 bits.
2047 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002048 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002049 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2050 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002051 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002052 // It is important that LowerBits is last, otherwise the arithmetic
2053 // shift will not be folded into the compare (SUBS).
2054 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2055 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2056 .getValue(1);
2057 } else {
2058 // The overflow check for unsigned multiply is easy. We only need to
2059 // check if any of the upper 32 bits are set. This can be done with a
2060 // CMP (shifted register). For that we need to generate the following
2061 // pattern:
2062 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2063 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002064 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002065 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2066 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002067 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2068 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002069 UpperBits).getValue(1);
2070 }
2071 break;
2072 }
2073 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2074 // For the 64 bit multiply
2075 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2076 if (IsSigned) {
2077 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2078 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002079 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002080 // It is important that LowerBits is last, otherwise the arithmetic
2081 // shift will not be folded into the compare (SUBS).
2082 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2083 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2084 .getValue(1);
2085 } else {
2086 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2087 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2088 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002089 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2090 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002091 UpperBits).getValue(1);
2092 }
2093 break;
2094 }
2095 } // switch (...)
2096
2097 if (Opc) {
2098 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2099
2100 // Emit the AArch64 operation with overflow check.
2101 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2102 Overflow = Value.getValue(1);
2103 }
2104 return std::make_pair(Value, Overflow);
2105}
2106
2107SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2108 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002109 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002110 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002111}
2112
Amara Emerson24ca39c2017-10-09 15:15:09 +00002113// Returns true if the given Op is the overflow flag result of an overflow
2114// intrinsic operation.
2115static bool isOverflowIntrOpRes(SDValue Op) {
2116 unsigned Opc = Op.getOpcode();
2117 return (Op.getResNo() == 1 &&
2118 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2119 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2120}
2121
Tim Northover3b0846e2014-05-24 12:50:23 +00002122static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2123 SDValue Sel = Op.getOperand(0);
2124 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002125 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002126
Amara Emerson24ca39c2017-10-09 15:15:09 +00002127 // If the operand is an overflow checking operation, invert the condition
2128 // code and kill the Not operation. I.e., transform:
2129 // (xor (overflow_op_bool, 1))
2130 // -->
2131 // (csel 1, 0, invert(cc), overflow_op_bool)
2132 // ... which later gets transformed to just a cset instruction with an
2133 // inverted condition code, rather than a cset + eor sequence.
2134 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2135 // Only lower legal XALUO ops.
2136 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2137 return SDValue();
2138
2139 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2140 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2141 AArch64CC::CondCode CC;
2142 SDValue Value, Overflow;
2143 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2144 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2145 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2146 CCVal, Overflow);
2147 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002148 // If neither operand is a SELECT_CC, give up.
2149 if (Sel.getOpcode() != ISD::SELECT_CC)
2150 std::swap(Sel, Other);
2151 if (Sel.getOpcode() != ISD::SELECT_CC)
2152 return Op;
2153
2154 // The folding we want to perform is:
2155 // (xor x, (select_cc a, b, cc, 0, -1) )
2156 // -->
2157 // (csel x, (xor x, -1), cc ...)
2158 //
2159 // The latter will get matched to a CSINV instruction.
2160
2161 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2162 SDValue LHS = Sel.getOperand(0);
2163 SDValue RHS = Sel.getOperand(1);
2164 SDValue TVal = Sel.getOperand(2);
2165 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002166
2167 // FIXME: This could be generalized to non-integer comparisons.
2168 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2169 return Op;
2170
2171 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2172 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2173
Eric Christopher572e03a2015-06-19 01:53:21 +00002174 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002175 if (!CFVal || !CTVal)
2176 return Op;
2177
2178 // We can commute the SELECT_CC by inverting the condition. This
2179 // might be needed to make this fit into a CSINV pattern.
2180 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2181 std::swap(TVal, FVal);
2182 std::swap(CTVal, CFVal);
2183 CC = ISD::getSetCCInverse(CC, true);
2184 }
2185
2186 // If the constants line up, perform the transform!
2187 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2188 SDValue CCVal;
2189 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2190
2191 FVal = Other;
2192 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002193 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002194
2195 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2196 CCVal, Cmp);
2197 }
2198
2199 return Op;
2200}
2201
2202static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2203 EVT VT = Op.getValueType();
2204
2205 // Let legalize expand this if it isn't a legal type yet.
2206 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2207 return SDValue();
2208
2209 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2210
2211 unsigned Opc;
2212 bool ExtraOp = false;
2213 switch (Op.getOpcode()) {
2214 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002215 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002216 case ISD::ADDC:
2217 Opc = AArch64ISD::ADDS;
2218 break;
2219 case ISD::SUBC:
2220 Opc = AArch64ISD::SUBS;
2221 break;
2222 case ISD::ADDE:
2223 Opc = AArch64ISD::ADCS;
2224 ExtraOp = true;
2225 break;
2226 case ISD::SUBE:
2227 Opc = AArch64ISD::SBCS;
2228 ExtraOp = true;
2229 break;
2230 }
2231
2232 if (!ExtraOp)
2233 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2234 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2235 Op.getOperand(2));
2236}
2237
2238static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2239 // Let legalize expand this if it isn't a legal type yet.
2240 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2241 return SDValue();
2242
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002243 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002244 AArch64CC::CondCode CC;
2245 // The actual operation that sets the overflow or carry flag.
2246 SDValue Value, Overflow;
2247 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2248
2249 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002250 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2251 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002252
2253 // We use an inverted condition, because the conditional select is inverted
2254 // too. This will allow it to be selected to a single instruction:
2255 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002256 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2257 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002258 CCVal, Overflow);
2259
2260 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002261 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002262}
2263
2264// Prefetch operands are:
2265// 1: Address to prefetch
2266// 2: bool isWrite
2267// 3: int locality (0 = no locality ... 3 = extreme locality)
2268// 4: bool isDataCache
2269static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2270 SDLoc DL(Op);
2271 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2272 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002273 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002274
2275 bool IsStream = !Locality;
2276 // When the locality number is set
2277 if (Locality) {
2278 // The front-end should have filtered out the out-of-range values
2279 assert(Locality <= 3 && "Prefetch locality out-of-range");
2280 // The locality degree is the opposite of the cache speed.
2281 // Put the number the other way around.
2282 // The encoding starts at 0 for level 1
2283 Locality = 3 - Locality;
2284 }
2285
2286 // built the mask value encoding the expected behavior.
2287 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002288 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002289 (Locality << 1) | // Cache level bits
2290 (unsigned)IsStream; // Stream bit
2291 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002292 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002293}
2294
2295SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2296 SelectionDAG &DAG) const {
2297 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2298
2299 RTLIB::Libcall LC;
2300 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2301
2302 return LowerF128Call(Op, DAG, LC);
2303}
2304
2305SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2306 SelectionDAG &DAG) const {
2307 if (Op.getOperand(0).getValueType() != MVT::f128) {
2308 // It's legal except when f128 is involved
2309 return Op;
2310 }
2311
2312 RTLIB::Libcall LC;
2313 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2314
2315 // FP_ROUND node has a second operand indicating whether it is known to be
2316 // precise. That doesn't take part in the LibCall so we can't directly use
2317 // LowerF128Call.
2318 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002319 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2320 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002321}
2322
2323static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2324 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2325 // Any additional optimization in this function should be recorded
2326 // in the cost tables.
2327 EVT InVT = Op.getOperand(0).getValueType();
2328 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002329 unsigned NumElts = InVT.getVectorNumElements();
2330
2331 // f16 vectors are promoted to f32 before a conversion.
2332 if (InVT.getVectorElementType() == MVT::f16) {
2333 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2334 SDLoc dl(Op);
2335 return DAG.getNode(
2336 Op.getOpcode(), dl, Op.getValueType(),
2337 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2338 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002339
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002340 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002341 SDLoc dl(Op);
2342 SDValue Cv =
2343 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2344 Op.getOperand(0));
2345 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002346 }
2347
2348 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002349 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002350 MVT ExtVT =
2351 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2352 VT.getVectorNumElements());
2353 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002354 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2355 }
2356
2357 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002358 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002359}
2360
2361SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2362 SelectionDAG &DAG) const {
2363 if (Op.getOperand(0).getValueType().isVector())
2364 return LowerVectorFP_TO_INT(Op, DAG);
2365
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002366 // f16 conversions are promoted to f32 when full fp16 is not supported.
2367 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2368 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002369 SDLoc dl(Op);
2370 return DAG.getNode(
2371 Op.getOpcode(), dl, Op.getValueType(),
2372 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2373 }
2374
Tim Northover3b0846e2014-05-24 12:50:23 +00002375 if (Op.getOperand(0).getValueType() != MVT::f128) {
2376 // It's legal except when f128 is involved
2377 return Op;
2378 }
2379
2380 RTLIB::Libcall LC;
2381 if (Op.getOpcode() == ISD::FP_TO_SINT)
2382 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2383 else
2384 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2385
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002386 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002387 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002388}
2389
2390static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2391 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2392 // Any additional optimization in this function should be recorded
2393 // in the cost tables.
2394 EVT VT = Op.getValueType();
2395 SDLoc dl(Op);
2396 SDValue In = Op.getOperand(0);
2397 EVT InVT = In.getValueType();
2398
Tim Northoveref0d7602014-06-15 09:27:06 +00002399 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2400 MVT CastVT =
2401 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2402 InVT.getVectorNumElements());
2403 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002404 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002405 }
2406
Tim Northoveref0d7602014-06-15 09:27:06 +00002407 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2408 unsigned CastOpc =
2409 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2410 EVT CastVT = VT.changeVectorElementTypeToInteger();
2411 In = DAG.getNode(CastOpc, dl, CastVT, In);
2412 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002413 }
2414
Tim Northoveref0d7602014-06-15 09:27:06 +00002415 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002416}
2417
2418SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2419 SelectionDAG &DAG) const {
2420 if (Op.getValueType().isVector())
2421 return LowerVectorINT_TO_FP(Op, DAG);
2422
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002423 // f16 conversions are promoted to f32 when full fp16 is not supported.
2424 if (Op.getValueType() == MVT::f16 &&
2425 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002426 SDLoc dl(Op);
2427 return DAG.getNode(
2428 ISD::FP_ROUND, dl, MVT::f16,
2429 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002430 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002431 }
2432
Tim Northover3b0846e2014-05-24 12:50:23 +00002433 // i128 conversions are libcalls.
2434 if (Op.getOperand(0).getValueType() == MVT::i128)
2435 return SDValue();
2436
2437 // Other conversions are legal, unless it's to the completely software-based
2438 // fp128.
2439 if (Op.getValueType() != MVT::f128)
2440 return Op;
2441
2442 RTLIB::Libcall LC;
2443 if (Op.getOpcode() == ISD::SINT_TO_FP)
2444 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2445 else
2446 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2447
2448 return LowerF128Call(Op, DAG, LC);
2449}
2450
2451SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2452 SelectionDAG &DAG) const {
2453 // For iOS, we want to call an alternative entry point: __sincos_stret,
2454 // which returns the values in two S / D registers.
2455 SDLoc dl(Op);
2456 SDValue Arg = Op.getOperand(0);
2457 EVT ArgVT = Arg.getValueType();
2458 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2459
2460 ArgListTy Args;
2461 ArgListEntry Entry;
2462
2463 Entry.Node = Arg;
2464 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002465 Entry.IsSExt = false;
2466 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002467 Args.push_back(Entry);
2468
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002469 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2470 : RTLIB::SINCOS_STRET_F32;
2471 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002472 SDValue Callee =
2473 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002474
Serge Gueltone38003f2017-05-09 19:31:13 +00002475 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002476 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002477 CLI.setDebugLoc(dl)
2478 .setChain(DAG.getEntryNode())
2479 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002480
2481 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2482 return CallResult.first;
2483}
2484
Tim Northoverf8bfe212014-07-18 13:07:05 +00002485static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2486 if (Op.getValueType() != MVT::f16)
2487 return SDValue();
2488
2489 assert(Op.getOperand(0).getValueType() == MVT::i16);
2490 SDLoc DL(Op);
2491
2492 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2493 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2494 return SDValue(
2495 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002496 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002497 0);
2498}
2499
Chad Rosierd9d0f862014-10-08 02:31:24 +00002500static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2501 if (OrigVT.getSizeInBits() >= 64)
2502 return OrigVT;
2503
2504 assert(OrigVT.isSimple() && "Expecting a simple value type");
2505
2506 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2507 switch (OrigSimpleTy) {
2508 default: llvm_unreachable("Unexpected Vector Type");
2509 case MVT::v2i8:
2510 case MVT::v2i16:
2511 return MVT::v2i32;
2512 case MVT::v4i8:
2513 return MVT::v4i16;
2514 }
2515}
2516
2517static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2518 const EVT &OrigTy,
2519 const EVT &ExtTy,
2520 unsigned ExtOpcode) {
2521 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2522 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2523 // 64-bits we need to insert a new extension so that it will be 64-bits.
2524 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2525 if (OrigTy.getSizeInBits() >= 64)
2526 return N;
2527
2528 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2529 EVT NewVT = getExtensionTo64Bits(OrigTy);
2530
2531 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2532}
2533
2534static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2535 bool isSigned) {
2536 EVT VT = N->getValueType(0);
2537
2538 if (N->getOpcode() != ISD::BUILD_VECTOR)
2539 return false;
2540
Pete Cooper3af9a252015-06-26 18:17:36 +00002541 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002542 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002543 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002544 unsigned HalfSize = EltSize / 2;
2545 if (isSigned) {
2546 if (!isIntN(HalfSize, C->getSExtValue()))
2547 return false;
2548 } else {
2549 if (!isUIntN(HalfSize, C->getZExtValue()))
2550 return false;
2551 }
2552 continue;
2553 }
2554 return false;
2555 }
2556
2557 return true;
2558}
2559
2560static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2561 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2562 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2563 N->getOperand(0)->getValueType(0),
2564 N->getValueType(0),
2565 N->getOpcode());
2566
2567 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2568 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002569 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002570 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002571 unsigned NumElts = VT.getVectorNumElements();
2572 MVT TruncVT = MVT::getIntegerVT(EltSize);
2573 SmallVector<SDValue, 8> Ops;
2574 for (unsigned i = 0; i != NumElts; ++i) {
2575 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2576 const APInt &CInt = C->getAPIntValue();
2577 // Element types smaller than 32 bits are not legal, so use i32 elements.
2578 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002579 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002580 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002581 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002582}
2583
2584static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002585 return N->getOpcode() == ISD::SIGN_EXTEND ||
2586 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002587}
2588
2589static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002590 return N->getOpcode() == ISD::ZERO_EXTEND ||
2591 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002592}
2593
2594static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2595 unsigned Opcode = N->getOpcode();
2596 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2597 SDNode *N0 = N->getOperand(0).getNode();
2598 SDNode *N1 = N->getOperand(1).getNode();
2599 return N0->hasOneUse() && N1->hasOneUse() &&
2600 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2601 }
2602 return false;
2603}
2604
2605static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2606 unsigned Opcode = N->getOpcode();
2607 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2608 SDNode *N0 = N->getOperand(0).getNode();
2609 SDNode *N1 = N->getOperand(1).getNode();
2610 return N0->hasOneUse() && N1->hasOneUse() &&
2611 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2612 }
2613 return false;
2614}
2615
Tim Northover70666e72018-06-20 12:09:01 +00002616SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2617 SelectionDAG &DAG) const {
2618 // The rounding mode is in bits 23:22 of the FPSCR.
2619 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2620 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2621 // so that the shift + and get folded into a bitfield extract.
2622 SDLoc dl(Op);
2623
2624 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2625 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2626 MVT::i64));
2627 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2628 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2629 DAG.getConstant(1U << 22, dl, MVT::i32));
2630 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2631 DAG.getConstant(22, dl, MVT::i32));
2632 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2633 DAG.getConstant(3, dl, MVT::i32));
2634}
2635
Chad Rosierd9d0f862014-10-08 02:31:24 +00002636static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2637 // Multiplications are only custom-lowered for 128-bit vectors so that
2638 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2639 EVT VT = Op.getValueType();
2640 assert(VT.is128BitVector() && VT.isInteger() &&
2641 "unexpected type for custom-lowering ISD::MUL");
2642 SDNode *N0 = Op.getOperand(0).getNode();
2643 SDNode *N1 = Op.getOperand(1).getNode();
2644 unsigned NewOpc = 0;
2645 bool isMLA = false;
2646 bool isN0SExt = isSignExtended(N0, DAG);
2647 bool isN1SExt = isSignExtended(N1, DAG);
2648 if (isN0SExt && isN1SExt)
2649 NewOpc = AArch64ISD::SMULL;
2650 else {
2651 bool isN0ZExt = isZeroExtended(N0, DAG);
2652 bool isN1ZExt = isZeroExtended(N1, DAG);
2653 if (isN0ZExt && isN1ZExt)
2654 NewOpc = AArch64ISD::UMULL;
2655 else if (isN1SExt || isN1ZExt) {
2656 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2657 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2658 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2659 NewOpc = AArch64ISD::SMULL;
2660 isMLA = true;
2661 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2662 NewOpc = AArch64ISD::UMULL;
2663 isMLA = true;
2664 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2665 std::swap(N0, N1);
2666 NewOpc = AArch64ISD::UMULL;
2667 isMLA = true;
2668 }
2669 }
2670
2671 if (!NewOpc) {
2672 if (VT == MVT::v2i64)
2673 // Fall through to expand this. It is not legal.
2674 return SDValue();
2675 else
2676 // Other vector multiplications are legal.
2677 return Op;
2678 }
2679 }
2680
2681 // Legalize to a S/UMULL instruction
2682 SDLoc DL(Op);
2683 SDValue Op0;
2684 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2685 if (!isMLA) {
2686 Op0 = skipExtensionForVectorMULL(N0, DAG);
2687 assert(Op0.getValueType().is64BitVector() &&
2688 Op1.getValueType().is64BitVector() &&
2689 "unexpected types for extended operands to VMULL");
2690 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2691 }
2692 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2693 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2694 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2695 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2696 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2697 EVT Op1VT = Op1.getValueType();
2698 return DAG.getNode(N0->getOpcode(), DL, VT,
2699 DAG.getNode(NewOpc, DL, VT,
2700 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2701 DAG.getNode(NewOpc, DL, VT,
2702 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2703}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002704
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002705SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2706 SelectionDAG &DAG) const {
2707 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2708 SDLoc dl(Op);
2709 switch (IntNo) {
2710 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002711 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002712 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2713 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2714 }
Eli Friedman33aecc82019-01-15 00:15:24 +00002715 case Intrinsic::aarch64_neon_abs: {
2716 EVT Ty = Op.getValueType();
2717 if (Ty == MVT::i64) {
2718 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2719 Op.getOperand(1));
2720 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2721 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2722 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2723 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2724 } else {
2725 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2726 }
2727 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002728 case Intrinsic::aarch64_neon_smax:
2729 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2730 Op.getOperand(1), Op.getOperand(2));
2731 case Intrinsic::aarch64_neon_umax:
2732 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2733 Op.getOperand(1), Op.getOperand(2));
2734 case Intrinsic::aarch64_neon_smin:
2735 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2736 Op.getOperand(1), Op.getOperand(2));
2737 case Intrinsic::aarch64_neon_umin:
2738 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2739 Op.getOperand(1), Op.getOperand(2));
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002740
2741 case Intrinsic::localaddress: {
Mandeep Singh Grang70d484d2019-02-01 21:41:33 +00002742 const auto &MF = DAG.getMachineFunction();
2743 const auto *RegInfo = Subtarget->getRegisterInfo();
2744 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +00002745 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2746 Op.getSimpleValueType());
2747 }
2748
2749 case Intrinsic::eh_recoverfp: {
2750 // FIXME: This needs to be implemented to correctly handle highly aligned
2751 // stack objects. For now we simply return the incoming FP. Refer D53541
2752 // for more details.
2753 SDValue FnOp = Op.getOperand(1);
2754 SDValue IncomingFPOp = Op.getOperand(2);
2755 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2756 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2757 if (!Fn)
2758 report_fatal_error(
2759 "llvm.eh.recoverfp must take a function as the first argument");
2760 return IncomingFPOp;
2761 }
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002762 }
2763}
2764
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002765// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2766static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2767 EVT VT, EVT MemVT,
2768 SelectionDAG &DAG) {
2769 assert(VT.isVector() && "VT should be a vector type");
2770 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2771
2772 SDValue Value = ST->getValue();
2773
2774 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2775 // the word lane which represent the v4i8 subvector. It optimizes the store
2776 // to:
2777 //
2778 // xtn v0.8b, v0.8h
2779 // str s0, [x0]
2780
2781 SDValue Undef = DAG.getUNDEF(MVT::i16);
2782 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2783 {Undef, Undef, Undef, Undef});
2784
2785 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2786 Value, UndefVec);
2787 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2788
2789 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2790 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2791 Trunc, DAG.getConstant(0, DL, MVT::i64));
2792
2793 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2794 ST->getBasePtr(), ST->getMemOperand());
2795}
2796
2797// Custom lowering for any store, vector or scalar and/or default or with
2798// a truncate operations. Currently only custom lower truncate operation
2799// from vector v4i16 to v4i8.
2800SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2801 SelectionDAG &DAG) const {
2802 SDLoc Dl(Op);
2803 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2804 assert (StoreNode && "Can only custom lower store nodes");
2805
2806 SDValue Value = StoreNode->getValue();
2807
2808 EVT VT = Value.getValueType();
2809 EVT MemVT = StoreNode->getMemoryVT();
2810
2811 assert (VT.isVector() && "Can only custom lower vector store types");
2812
2813 unsigned AS = StoreNode->getAddressSpace();
2814 unsigned Align = StoreNode->getAlignment();
2815 if (Align < MemVT.getStoreSize() &&
2816 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2817 return scalarizeVectorStore(StoreNode, DAG);
2818 }
2819
2820 if (StoreNode->isTruncatingStore()) {
2821 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2822 }
2823
2824 return SDValue();
2825}
2826
Tim Northover3b0846e2014-05-24 12:50:23 +00002827SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2828 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002829 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2830 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002831
Tim Northover3b0846e2014-05-24 12:50:23 +00002832 switch (Op.getOpcode()) {
2833 default:
2834 llvm_unreachable("unimplemented operand");
2835 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002836 case ISD::BITCAST:
2837 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002838 case ISD::GlobalAddress:
2839 return LowerGlobalAddress(Op, DAG);
2840 case ISD::GlobalTLSAddress:
2841 return LowerGlobalTLSAddress(Op, DAG);
2842 case ISD::SETCC:
2843 return LowerSETCC(Op, DAG);
2844 case ISD::BR_CC:
2845 return LowerBR_CC(Op, DAG);
2846 case ISD::SELECT:
2847 return LowerSELECT(Op, DAG);
2848 case ISD::SELECT_CC:
2849 return LowerSELECT_CC(Op, DAG);
2850 case ISD::JumpTable:
2851 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002852 case ISD::BR_JT:
2853 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002854 case ISD::ConstantPool:
2855 return LowerConstantPool(Op, DAG);
2856 case ISD::BlockAddress:
2857 return LowerBlockAddress(Op, DAG);
2858 case ISD::VASTART:
2859 return LowerVASTART(Op, DAG);
2860 case ISD::VACOPY:
2861 return LowerVACOPY(Op, DAG);
2862 case ISD::VAARG:
2863 return LowerVAARG(Op, DAG);
2864 case ISD::ADDC:
2865 case ISD::ADDE:
2866 case ISD::SUBC:
2867 case ISD::SUBE:
2868 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2869 case ISD::SADDO:
2870 case ISD::UADDO:
2871 case ISD::SSUBO:
2872 case ISD::USUBO:
2873 case ISD::SMULO:
2874 case ISD::UMULO:
2875 return LowerXALUO(Op, DAG);
2876 case ISD::FADD:
2877 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2878 case ISD::FSUB:
2879 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2880 case ISD::FMUL:
2881 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2882 case ISD::FDIV:
2883 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2884 case ISD::FP_ROUND:
2885 return LowerFP_ROUND(Op, DAG);
2886 case ISD::FP_EXTEND:
2887 return LowerFP_EXTEND(Op, DAG);
2888 case ISD::FRAMEADDR:
2889 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002890 case ISD::SPONENTRY:
2891 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002892 case ISD::RETURNADDR:
2893 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002894 case ISD::ADDROFRETURNADDR:
2895 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002896 case ISD::INSERT_VECTOR_ELT:
2897 return LowerINSERT_VECTOR_ELT(Op, DAG);
2898 case ISD::EXTRACT_VECTOR_ELT:
2899 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2900 case ISD::BUILD_VECTOR:
2901 return LowerBUILD_VECTOR(Op, DAG);
2902 case ISD::VECTOR_SHUFFLE:
2903 return LowerVECTOR_SHUFFLE(Op, DAG);
2904 case ISD::EXTRACT_SUBVECTOR:
2905 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2906 case ISD::SRA:
2907 case ISD::SRL:
2908 case ISD::SHL:
2909 return LowerVectorSRA_SRL_SHL(Op, DAG);
2910 case ISD::SHL_PARTS:
2911 return LowerShiftLeftParts(Op, DAG);
2912 case ISD::SRL_PARTS:
2913 case ISD::SRA_PARTS:
2914 return LowerShiftRightParts(Op, DAG);
2915 case ISD::CTPOP:
2916 return LowerCTPOP(Op, DAG);
2917 case ISD::FCOPYSIGN:
2918 return LowerFCOPYSIGN(Op, DAG);
2919 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002920 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002921 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002922 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002923 case ISD::XOR:
2924 return LowerXOR(Op, DAG);
2925 case ISD::PREFETCH:
2926 return LowerPREFETCH(Op, DAG);
2927 case ISD::SINT_TO_FP:
2928 case ISD::UINT_TO_FP:
2929 return LowerINT_TO_FP(Op, DAG);
2930 case ISD::FP_TO_SINT:
2931 case ISD::FP_TO_UINT:
2932 return LowerFP_TO_INT(Op, DAG);
2933 case ISD::FSINCOS:
2934 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002935 case ISD::FLT_ROUNDS_:
2936 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002937 case ISD::MUL:
2938 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002939 case ISD::INTRINSIC_WO_CHAIN:
2940 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002941 case ISD::STORE:
2942 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002943 case ISD::VECREDUCE_ADD:
2944 case ISD::VECREDUCE_SMAX:
2945 case ISD::VECREDUCE_SMIN:
2946 case ISD::VECREDUCE_UMAX:
2947 case ISD::VECREDUCE_UMIN:
2948 case ISD::VECREDUCE_FMAX:
2949 case ISD::VECREDUCE_FMIN:
2950 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002951 case ISD::ATOMIC_LOAD_SUB:
2952 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002953 case ISD::ATOMIC_LOAD_AND:
2954 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002955 case ISD::DYNAMIC_STACKALLOC:
2956 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002957 }
2958}
2959
Tim Northover3b0846e2014-05-24 12:50:23 +00002960//===----------------------------------------------------------------------===//
2961// Calling Convention Implementation
2962//===----------------------------------------------------------------------===//
2963
Robin Morisset039781e2014-08-29 21:53:01 +00002964/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002965CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2966 bool IsVarArg) const {
2967 switch (CC) {
2968 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002969 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002970 case CallingConv::WebKit_JS:
2971 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002972 case CallingConv::GHC:
2973 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002974 case CallingConv::C:
2975 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002976 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002977 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002978 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002979 if (Subtarget->isTargetWindows() && IsVarArg)
2980 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002981 if (!Subtarget->isTargetDarwin())
2982 return CC_AArch64_AAPCS;
2983 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002984 case CallingConv::Win64:
2985 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00002986 case CallingConv::AArch64_VectorCall:
2987 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002988 }
2989}
2990
Tim Northover406024a2016-08-10 21:44:01 +00002991CCAssignFn *
2992AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2993 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2994 : RetCC_AArch64_AAPCS;
2995}
2996
Tim Northover3b0846e2014-05-24 12:50:23 +00002997SDValue AArch64TargetLowering::LowerFormalArguments(
2998 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002999 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3000 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003001 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003002 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00003003 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003004
3005 // Assign locations to all of the incoming arguments.
3006 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003007 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3008 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003009
3010 // At this point, Ins[].VT may already be promoted to i32. To correctly
3011 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3012 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3013 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3014 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3015 // LocVT.
3016 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00003017 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00003018 unsigned CurArgIdx = 0;
3019 for (unsigned i = 0; i != NumArgs; ++i) {
3020 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00003021 if (Ins[i].isOrigArg()) {
3022 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3023 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00003024
Andrew Trick05938a52015-02-16 18:10:47 +00003025 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003026 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3027 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003028 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3029 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3030 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3031 ValVT = MVT::i8;
3032 else if (ActualMVT == MVT::i16)
3033 ValVT = MVT::i16;
3034 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003035 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3036 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003037 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003038 assert(!Res && "Call operand has unhandled type");
3039 (void)Res;
3040 }
3041 assert(ArgLocs.size() == Ins.size());
3042 SmallVector<SDValue, 16> ArgValues;
3043 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3044 CCValAssign &VA = ArgLocs[i];
3045
3046 if (Ins[i].Flags.isByVal()) {
3047 // Byval is used for HFAs in the PCS, but the system should work in a
3048 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003049 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003050 int Size = Ins[i].Flags.getByValSize();
3051 unsigned NumRegs = (Size + 7) / 8;
3052
3053 // FIXME: This works on big-endian for composite byvals, which are the common
3054 // case. It should also work for fundamental types too.
3055 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003056 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003057 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003058 InVals.push_back(FrameIdxN);
3059
3060 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003061 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003062
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003063 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003064 // Arguments stored in registers.
3065 EVT RegVT = VA.getLocVT();
3066
3067 SDValue ArgValue;
3068 const TargetRegisterClass *RC;
3069
3070 if (RegVT == MVT::i32)
3071 RC = &AArch64::GPR32RegClass;
3072 else if (RegVT == MVT::i64)
3073 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003074 else if (RegVT == MVT::f16)
3075 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003076 else if (RegVT == MVT::f32)
3077 RC = &AArch64::FPR32RegClass;
3078 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3079 RC = &AArch64::FPR64RegClass;
3080 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3081 RC = &AArch64::FPR128RegClass;
3082 else
3083 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3084
3085 // Transform the arguments in physical registers into virtual ones.
3086 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3087 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3088
3089 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3090 // to 64 bits. Insert an assert[sz]ext to capture this, then
3091 // truncate to the right size.
3092 switch (VA.getLocInfo()) {
3093 default:
3094 llvm_unreachable("Unknown loc info!");
3095 case CCValAssign::Full:
3096 break;
3097 case CCValAssign::BCvt:
3098 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3099 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003100 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003101 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003102 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003103 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3104 // nodes after our lowering.
3105 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003106 break;
3107 }
3108
3109 InVals.push_back(ArgValue);
3110
3111 } else { // VA.isRegLoc()
3112 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3113 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003114 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003115
3116 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003117 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3118 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003119 BEAlign = 8 - ArgSize;
3120
Matthias Braun941a7052016-07-28 18:40:00 +00003121 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003122
3123 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003124 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003125 SDValue ArgValue;
3126
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003127 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003128 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003129 MVT MemVT = VA.getValVT();
3130
Tim Northover47e003c2014-05-26 17:21:53 +00003131 switch (VA.getLocInfo()) {
3132 default:
3133 break;
Tim Northover6890add2014-06-03 13:54:53 +00003134 case CCValAssign::BCvt:
3135 MemVT = VA.getLocVT();
3136 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003137 case CCValAssign::SExt:
3138 ExtType = ISD::SEXTLOAD;
3139 break;
3140 case CCValAssign::ZExt:
3141 ExtType = ISD::ZEXTLOAD;
3142 break;
3143 case CCValAssign::AExt:
3144 ExtType = ISD::EXTLOAD;
3145 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003146 }
3147
Alex Lorenze40c8a22015-08-11 23:09:45 +00003148 ArgValue = DAG.getExtLoad(
3149 ExtType, DL, VA.getLocVT(), Chain, FIN,
3150 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003151 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003152
Tim Northover3b0846e2014-05-24 12:50:23 +00003153 InVals.push_back(ArgValue);
3154 }
3155 }
3156
3157 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003158 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003159 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003160 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003161 // The AAPCS variadic function ABI is identical to the non-variadic
3162 // one. As a result there may be more arguments in registers and we should
3163 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003164 // Win64 variadic functions also pass arguments in registers, but all float
3165 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003166 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3167 }
3168
Tim Northover3b0846e2014-05-24 12:50:23 +00003169 // This will point to the next argument passed via stack.
3170 unsigned StackOffset = CCInfo.getNextStackOffset();
3171 // We currently pass all varargs at 8-byte alignment.
3172 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003173 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003174
3175 if (MFI.hasMustTailInVarArgFunc()) {
3176 SmallVector<MVT, 2> RegParmTypes;
3177 RegParmTypes.push_back(MVT::i64);
3178 RegParmTypes.push_back(MVT::f128);
3179 // Compute the set of forwarded registers. The rest are scratch.
3180 SmallVectorImpl<ForwardedRegister> &Forwards =
3181 FuncInfo->getForwardedMustTailRegParms();
3182 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3183 CC_AArch64_AAPCS);
3184 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003185 }
3186
Tim Northover3b0846e2014-05-24 12:50:23 +00003187 unsigned StackArgSize = CCInfo.getNextStackOffset();
3188 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3189 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3190 // This is a non-standard ABI so by fiat I say we're allowed to make full
3191 // use of the stack area to be popped, which must be aligned to 16 bytes in
3192 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003193 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003194
3195 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3196 // a multiple of 16.
3197 FuncInfo->setArgumentStackToRestore(StackArgSize);
3198
3199 // This realignment carries over to the available bytes below. Our own
3200 // callers will guarantee the space is free by giving an aligned value to
3201 // CALLSEQ_START.
3202 }
3203 // Even if we're not expected to free up the space, it's useful to know how
3204 // much is there while considering tail calls (because we can reuse it).
3205 FuncInfo->setBytesInStackArgArea(StackArgSize);
3206
Tri Vo6c47c622018-09-22 22:17:50 +00003207 if (Subtarget->hasCustomCallingConv())
3208 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3209
Tim Northover3b0846e2014-05-24 12:50:23 +00003210 return Chain;
3211}
3212
3213void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003214 SelectionDAG &DAG,
3215 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003216 SDValue &Chain) const {
3217 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003218 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003219 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003220 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003221 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003222
3223 SmallVector<SDValue, 8> MemOps;
3224
3225 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3226 AArch64::X3, AArch64::X4, AArch64::X5,
3227 AArch64::X6, AArch64::X7 };
3228 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003229 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003230
3231 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3232 int GPRIdx = 0;
3233 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003234 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003235 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003236 if (GPRSaveSize & 15)
3237 // The extra size here, if triggered, will always be 8.
3238 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3239 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003240 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003241
Mehdi Amini44ede332015-07-09 02:09:04 +00003242 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003243
3244 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3245 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3246 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003247 SDValue Store = DAG.getStore(
3248 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003249 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003250 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3251 GPRIdx,
3252 (i - FirstVariadicGPR) * 8)
3253 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003254 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003255 FIN =
3256 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003257 }
3258 }
3259 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3260 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3261
Martin Storsjo2f24e932017-07-17 20:05:19 +00003262 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003263 static const MCPhysReg FPRArgRegs[] = {
3264 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3265 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3266 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003267 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003268
3269 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3270 int FPRIdx = 0;
3271 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003272 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003273
Mehdi Amini44ede332015-07-09 02:09:04 +00003274 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003275
3276 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3277 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3278 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3279
Alex Lorenze40c8a22015-08-11 23:09:45 +00003280 SDValue Store = DAG.getStore(
3281 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003282 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003283 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003284 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3285 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003286 }
3287 }
3288 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3289 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3290 }
3291
3292 if (!MemOps.empty()) {
3293 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3294 }
3295}
3296
3297/// LowerCallResult - Lower the result values of a call into the
3298/// appropriate copies out of appropriate physical registers.
3299SDValue AArch64TargetLowering::LowerCallResult(
3300 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003301 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3302 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003303 SDValue ThisVal) const {
3304 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3305 ? RetCC_AArch64_WebKit_JS
3306 : RetCC_AArch64_AAPCS;
3307 // Assign locations to each value returned by this call.
3308 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003309 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3310 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003311 CCInfo.AnalyzeCallResult(Ins, RetCC);
3312
3313 // Copy all of the result registers out of their specified physreg.
3314 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3315 CCValAssign VA = RVLocs[i];
3316
3317 // Pass 'this' value directly from the argument to return value, to avoid
3318 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003319 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003320 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3321 "unexpected return calling convention register assignment");
3322 InVals.push_back(ThisVal);
3323 continue;
3324 }
3325
3326 SDValue Val =
3327 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3328 Chain = Val.getValue(1);
3329 InFlag = Val.getValue(2);
3330
3331 switch (VA.getLocInfo()) {
3332 default:
3333 llvm_unreachable("Unknown loc info!");
3334 case CCValAssign::Full:
3335 break;
3336 case CCValAssign::BCvt:
3337 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3338 break;
3339 }
3340
3341 InVals.push_back(Val);
3342 }
3343
3344 return Chain;
3345}
3346
Matthias Braun1af14142016-09-13 19:27:38 +00003347/// Return true if the calling convention is one that we can guarantee TCO for.
3348static bool canGuaranteeTCO(CallingConv::ID CC) {
3349 return CC == CallingConv::Fast;
3350}
3351
3352/// Return true if we might ever do TCO for calls with this calling convention.
3353static bool mayTailCallThisCC(CallingConv::ID CC) {
3354 switch (CC) {
3355 case CallingConv::C:
3356 case CallingConv::PreserveMost:
3357 case CallingConv::Swift:
3358 return true;
3359 default:
3360 return canGuaranteeTCO(CC);
3361 }
3362}
3363
Tim Northover3b0846e2014-05-24 12:50:23 +00003364bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3365 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003366 const SmallVectorImpl<ISD::OutputArg> &Outs,
3367 const SmallVectorImpl<SDValue> &OutVals,
3368 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003369 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003370 return false;
3371
Matthias Braun8d414362016-03-30 22:46:04 +00003372 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003373 const Function &CallerF = MF.getFunction();
3374 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003375 bool CCMatch = CallerCC == CalleeCC;
3376
3377 // Byval parameters hand the function a pointer directly into the stack area
3378 // we want to reuse during a tail call. Working around this *is* possible (see
3379 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003380 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3381 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003382 i != e; ++i)
3383 if (i->hasByValAttr())
3384 return false;
3385
Matthias Braun1af14142016-09-13 19:27:38 +00003386 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3387 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003388
Oliver Stannard12993dd2014-08-18 12:42:15 +00003389 // Externally-defined functions with weak linkage should not be
3390 // tail-called on AArch64 when the OS does not support dynamic
3391 // pre-emption of symbols, as the AAELF spec requires normal calls
3392 // to undefined weak functions to be replaced with a NOP or jump to the
3393 // next instruction. The behaviour of branch instructions in this
3394 // situation (as used for tail calls) is implementation-defined, so we
3395 // cannot rely on the linker replacing the tail call with a return.
3396 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3397 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003398 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003399 if (GV->hasExternalWeakLinkage() &&
3400 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003401 return false;
3402 }
3403
Tim Northover3b0846e2014-05-24 12:50:23 +00003404 // Now we search for cases where we can use a tail call without changing the
3405 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3406 // concept.
3407
3408 // I want anyone implementing a new calling convention to think long and hard
3409 // about this assert.
3410 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3411 "Unexpected variadic calling convention");
3412
Matthias Braun8d414362016-03-30 22:46:04 +00003413 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003414 if (isVarArg && !Outs.empty()) {
3415 // At least two cases here: if caller is fastcc then we can't have any
3416 // memory arguments (we'd be expected to clean up the stack afterwards). If
3417 // caller is C then we could potentially use its argument area.
3418
3419 // FIXME: for now we take the most conservative of these in both cases:
3420 // disallow all variadic memory operands.
3421 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003422 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003423
3424 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003425 for (const CCValAssign &ArgLoc : ArgLocs)
3426 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003427 return false;
3428 }
3429
Matthias Braun8d414362016-03-30 22:46:04 +00003430 // Check that the call results are passed in the same way.
3431 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3432 CCAssignFnForCall(CalleeCC, isVarArg),
3433 CCAssignFnForCall(CallerCC, isVarArg)))
3434 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003435 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003436 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3437 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003438 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003439 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003440 if (Subtarget->hasCustomCallingConv()) {
3441 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3442 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3443 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003444 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003445 return false;
3446 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003447
3448 // Nothing more to check if the callee is taking no arguments
3449 if (Outs.empty())
3450 return true;
3451
3452 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003453 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003454
3455 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3456
3457 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3458
Matthias Braun74a0bd32016-04-13 21:43:16 +00003459 // If the stack arguments for this call do not fit into our own save area then
3460 // the call cannot be made tail.
3461 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3462 return false;
3463
Matthias Braun46b0f032016-04-14 01:10:42 +00003464 const MachineRegisterInfo &MRI = MF.getRegInfo();
3465 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3466 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003467
3468 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003469}
3470
3471SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3472 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003473 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003474 int ClobberedFI) const {
3475 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003476 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3477 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003478
3479 // Include the original chain at the beginning of the list. When this is
3480 // used by target LowerCall hooks, this helps legalize find the
3481 // CALLSEQ_BEGIN node.
3482 ArgChains.push_back(Chain);
3483
3484 // Add a chain value for each stack argument corresponding
3485 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3486 UE = DAG.getEntryNode().getNode()->use_end();
3487 U != UE; ++U)
3488 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3489 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3490 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003491 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003492 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003493 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003494
3495 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3496 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3497 ArgChains.push_back(SDValue(L, 1));
3498 }
3499
3500 // Build a tokenfactor for all the chains.
3501 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3502}
3503
3504bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3505 bool TailCallOpt) const {
3506 return CallCC == CallingConv::Fast && TailCallOpt;
3507}
3508
Tim Northover3b0846e2014-05-24 12:50:23 +00003509/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3510/// and add input and output parameter nodes.
3511SDValue
3512AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3513 SmallVectorImpl<SDValue> &InVals) const {
3514 SelectionDAG &DAG = CLI.DAG;
3515 SDLoc &DL = CLI.DL;
3516 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3517 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3518 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3519 SDValue Chain = CLI.Chain;
3520 SDValue Callee = CLI.Callee;
3521 bool &IsTailCall = CLI.IsTailCall;
3522 CallingConv::ID CallConv = CLI.CallConv;
3523 bool IsVarArg = CLI.IsVarArg;
3524
3525 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003526 bool IsThisReturn = false;
3527
3528 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3529 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3530 bool IsSibCall = false;
3531
3532 if (IsTailCall) {
3533 // Check if it's really possible to do a tail call.
3534 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003535 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003536 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003537 report_fatal_error("failed to perform tail call elimination on a call "
3538 "site marked musttail");
3539
3540 // A sibling call is one where we're under the usual C ABI and not planning
3541 // to change that but can still do a tail call:
3542 if (!TailCallOpt && IsTailCall)
3543 IsSibCall = true;
3544
3545 if (IsTailCall)
3546 ++NumTailCalls;
3547 }
3548
3549 // Analyze operands of the call, assigning locations to each operand.
3550 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003551 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3552 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003553
3554 if (IsVarArg) {
3555 // Handle fixed and variable vector arguments differently.
3556 // Variable vector arguments always go into memory.
3557 unsigned NumArgs = Outs.size();
3558
3559 for (unsigned i = 0; i != NumArgs; ++i) {
3560 MVT ArgVT = Outs[i].VT;
3561 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3562 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3563 /*IsVarArg=*/ !Outs[i].IsFixed);
3564 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3565 assert(!Res && "Call operand has unhandled type");
3566 (void)Res;
3567 }
3568 } else {
3569 // At this point, Outs[].VT may already be promoted to i32. To correctly
3570 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3571 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3572 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3573 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3574 // LocVT.
3575 unsigned NumArgs = Outs.size();
3576 for (unsigned i = 0; i != NumArgs; ++i) {
3577 MVT ValVT = Outs[i].VT;
3578 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003579 EVT ActualVT = getValueType(DAG.getDataLayout(),
3580 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003581 /*AllowUnknown*/ true);
3582 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3583 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3584 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003585 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003586 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003587 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003588 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003589
3590 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003591 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003592 assert(!Res && "Call operand has unhandled type");
3593 (void)Res;
3594 }
3595 }
3596
3597 // Get a count of how many bytes are to be pushed on the stack.
3598 unsigned NumBytes = CCInfo.getNextStackOffset();
3599
3600 if (IsSibCall) {
3601 // Since we're not changing the ABI to make this a tail call, the memory
3602 // operands are already available in the caller's incoming argument space.
3603 NumBytes = 0;
3604 }
3605
3606 // FPDiff is the byte offset of the call's argument area from the callee's.
3607 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3608 // by this amount for a tail call. In a sibling call it must be 0 because the
3609 // caller will deallocate the entire stack and the callee still expects its
3610 // arguments to begin at SP+0. Completely unused for non-tail calls.
3611 int FPDiff = 0;
3612
3613 if (IsTailCall && !IsSibCall) {
3614 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3615
3616 // Since callee will pop argument stack as a tail call, we must keep the
3617 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003618 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003619
3620 // FPDiff will be negative if this tail call requires more space than we
3621 // would automatically have in our incoming argument space. Positive if we
3622 // can actually shrink the stack.
3623 FPDiff = NumReusableBytes - NumBytes;
3624
3625 // The stack pointer must be 16-byte aligned at all times it's used for a
3626 // memory operation, which in practice means at *all* times and in
3627 // particular across call boundaries. Therefore our own arguments started at
3628 // a 16-byte aligned SP and the delta applied for the tail call should
3629 // satisfy the same constraint.
3630 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3631 }
3632
3633 // Adjust the stack pointer for the new arguments...
3634 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003635 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003636 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003637
Mehdi Amini44ede332015-07-09 02:09:04 +00003638 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3639 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003640
3641 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3642 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003643 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003644
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003645 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3646 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3647 for (const auto &F : Forwards) {
3648 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3649 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3650 }
3651 }
3652
Tim Northover3b0846e2014-05-24 12:50:23 +00003653 // Walk the register/memloc assignments, inserting copies/loads.
3654 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3655 ++i, ++realArgIdx) {
3656 CCValAssign &VA = ArgLocs[i];
3657 SDValue Arg = OutVals[realArgIdx];
3658 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3659
3660 // Promote the value if needed.
3661 switch (VA.getLocInfo()) {
3662 default:
3663 llvm_unreachable("Unknown loc info!");
3664 case CCValAssign::Full:
3665 break;
3666 case CCValAssign::SExt:
3667 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3668 break;
3669 case CCValAssign::ZExt:
3670 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3671 break;
3672 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003673 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3674 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3675 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3676 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3677 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003678 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3679 break;
3680 case CCValAssign::BCvt:
3681 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3682 break;
3683 case CCValAssign::FPExt:
3684 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3685 break;
3686 }
3687
3688 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003689 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3690 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003691 assert(VA.getLocVT() == MVT::i64 &&
3692 "unexpected calling convention register assignment");
3693 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3694 "unexpected use of 'returned'");
3695 IsThisReturn = true;
3696 }
3697 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3698 } else {
3699 assert(VA.isMemLoc());
3700
3701 SDValue DstAddr;
3702 MachinePointerInfo DstInfo;
3703
3704 // FIXME: This works on big-endian for composite byvals, which are the
3705 // common case. It should also work for fundamental types too.
3706 uint32_t BEAlign = 0;
3707 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003708 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003709 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003710 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3711 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003712 if (OpSize < 8)
3713 BEAlign = 8 - OpSize;
3714 }
3715 unsigned LocMemOffset = VA.getLocMemOffset();
3716 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003717 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003718 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003719
3720 if (IsTailCall) {
3721 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003722 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003723
Mehdi Amini44ede332015-07-09 02:09:04 +00003724 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003725 DstInfo =
3726 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003727
3728 // Make sure any stack arguments overlapping with where we're storing
3729 // are loaded before this eventual operation. Otherwise they'll be
3730 // clobbered.
3731 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3732 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003733 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003734
Mehdi Amini44ede332015-07-09 02:09:04 +00003735 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003736 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3737 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003738 }
3739
3740 if (Outs[i].Flags.isByVal()) {
3741 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003742 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003743 SDValue Cpy = DAG.getMemcpy(
3744 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003745 /*isVol = */ false, /*AlwaysInline = */ false,
3746 /*isTailCall = */ false,
3747 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003748
3749 MemOpChains.push_back(Cpy);
3750 } else {
3751 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3752 // promoted to a legal register type i32, we should truncate Arg back to
3753 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003754 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3755 VA.getValVT() == MVT::i16)
3756 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003757
Justin Lebar9c375812016-07-15 18:27:10 +00003758 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003759 MemOpChains.push_back(Store);
3760 }
3761 }
3762 }
3763
3764 if (!MemOpChains.empty())
3765 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3766
3767 // Build a sequence of copy-to-reg nodes chained together with token chain
3768 // and flag operands which copy the outgoing args into the appropriate regs.
3769 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003770 for (auto &RegToPass : RegsToPass) {
3771 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3772 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003773 InFlag = Chain.getValue(1);
3774 }
3775
3776 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3777 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3778 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003779 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3780 auto GV = G->getGlobal();
3781 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3782 AArch64II::MO_GOT) {
3783 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3784 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003785 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3786 assert(Subtarget->isTargetWindows() &&
3787 "Windows is the only supported COFF target");
3788 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003789 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003790 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003791 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3792 }
3793 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3794 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3795 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003796 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003797 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3798 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003799 } else {
3800 const char *Sym = S->getSymbol();
3801 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003802 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003803 }
3804
3805 // We don't usually want to end the call-sequence here because we would tidy
3806 // the frame up *after* the call, however in the ABI-changing tail-call case
3807 // we've carefully laid out the parameters so that when sp is reset they'll be
3808 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003809 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003810 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3811 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003812 InFlag = Chain.getValue(1);
3813 }
3814
3815 std::vector<SDValue> Ops;
3816 Ops.push_back(Chain);
3817 Ops.push_back(Callee);
3818
3819 if (IsTailCall) {
3820 // Each tail call may have to adjust the stack by a different amount, so
3821 // this information must travel along with the operation for eventual
3822 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003823 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003824 }
3825
3826 // Add argument registers to the end of the list so that they are known live
3827 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003828 for (auto &RegToPass : RegsToPass)
3829 Ops.push_back(DAG.getRegister(RegToPass.first,
3830 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003831
3832 // Add a register mask operand representing the call-preserved registers.
3833 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003834 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003835 if (IsThisReturn) {
3836 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003837 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003838 if (!Mask) {
3839 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003840 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003841 }
3842 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003843 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003844
Tri Vo6c47c622018-09-22 22:17:50 +00003845 if (Subtarget->hasCustomCallingConv())
3846 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3847
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003848 if (TRI->isAnyArgRegReserved(MF))
3849 TRI->emitReservedArgRegCallError(MF);
3850
Tim Northover3b0846e2014-05-24 12:50:23 +00003851 assert(Mask && "Missing call preserved mask for calling convention");
3852 Ops.push_back(DAG.getRegisterMask(Mask));
3853
3854 if (InFlag.getNode())
3855 Ops.push_back(InFlag);
3856
3857 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3858
3859 // If we're doing a tall call, use a TC_RETURN here rather than an
3860 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003861 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003862 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003863 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003864 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003865
3866 // Returns a chain and a flag for retval copy to use.
3867 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3868 InFlag = Chain.getValue(1);
3869
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003870 uint64_t CalleePopBytes =
3871 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003872
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003873 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3874 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3875 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003876 if (!Ins.empty())
3877 InFlag = Chain.getValue(1);
3878
3879 // Handle result values, copying them out of physregs into vregs that we
3880 // return.
3881 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3882 InVals, IsThisReturn,
3883 IsThisReturn ? OutVals[0] : SDValue());
3884}
3885
3886bool AArch64TargetLowering::CanLowerReturn(
3887 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3888 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3889 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3890 ? RetCC_AArch64_WebKit_JS
3891 : RetCC_AArch64_AAPCS;
3892 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003893 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003894 return CCInfo.CheckReturn(Outs, RetCC);
3895}
3896
3897SDValue
3898AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3899 bool isVarArg,
3900 const SmallVectorImpl<ISD::OutputArg> &Outs,
3901 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003902 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003903 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3904 ? RetCC_AArch64_WebKit_JS
3905 : RetCC_AArch64_AAPCS;
3906 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003907 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3908 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003909 CCInfo.AnalyzeReturn(Outs, RetCC);
3910
3911 // Copy the result values into the output registers.
3912 SDValue Flag;
3913 SmallVector<SDValue, 4> RetOps(1, Chain);
3914 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3915 ++i, ++realRVLocIdx) {
3916 CCValAssign &VA = RVLocs[i];
3917 assert(VA.isRegLoc() && "Can only return in registers!");
3918 SDValue Arg = OutVals[realRVLocIdx];
3919
3920 switch (VA.getLocInfo()) {
3921 default:
3922 llvm_unreachable("Unknown loc info!");
3923 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003924 if (Outs[i].ArgVT == MVT::i1) {
3925 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3926 // value. This is strictly redundant on Darwin (which uses "zeroext
3927 // i1"), but will be optimised out before ISel.
3928 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3929 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3930 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003931 break;
3932 case CCValAssign::BCvt:
3933 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3934 break;
3935 }
3936
3937 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3938 Flag = Chain.getValue(1);
3939 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3940 }
Manman Rencbe4f942015-12-16 21:04:19 +00003941 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3942 const MCPhysReg *I =
3943 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3944 if (I) {
3945 for (; *I; ++I) {
3946 if (AArch64::GPR64RegClass.contains(*I))
3947 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3948 else if (AArch64::FPR64RegClass.contains(*I))
3949 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3950 else
3951 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3952 }
3953 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003954
3955 RetOps[0] = Chain; // Update chain.
3956
3957 // Add the flag if we have it.
3958 if (Flag.getNode())
3959 RetOps.push_back(Flag);
3960
3961 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3962}
3963
3964//===----------------------------------------------------------------------===//
3965// Other Lowering Code
3966//===----------------------------------------------------------------------===//
3967
Joel Jonesa7c4a522017-04-21 17:31:03 +00003968SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3969 SelectionDAG &DAG,
3970 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003971 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3972 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003973}
3974
3975SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3976 SelectionDAG &DAG,
3977 unsigned Flag) const {
3978 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3979}
3980
3981SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3982 SelectionDAG &DAG,
3983 unsigned Flag) const {
3984 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3985 N->getOffset(), Flag);
3986}
3987
3988SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3989 SelectionDAG &DAG,
3990 unsigned Flag) const {
3991 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3992}
3993
3994// (loadGOT sym)
3995template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003996SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3997 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003998 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00003999 SDLoc DL(N);
4000 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004001 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004002 // FIXME: Once remat is capable of dealing with instructions with register
4003 // operands, expand this into two nodes instead of using a wrapper node.
4004 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4005}
4006
4007// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4008template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004009SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4010 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004011 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004012 SDLoc DL(N);
4013 EVT Ty = getPointerTy(DAG.getDataLayout());
4014 const unsigned char MO_NC = AArch64II::MO_NC;
4015 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004016 AArch64ISD::WrapperLarge, DL, Ty,
4017 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4018 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4019 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4020 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00004021}
4022
4023// (addlow (adrp %hi(sym)) %lo(sym))
4024template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004025SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4026 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004027 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004028 SDLoc DL(N);
4029 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004030 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004031 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004032 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004033 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4034 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4035}
4036
David Green9dd1d452018-08-22 11:31:39 +00004037// (adr sym)
4038template <class NodeTy>
4039SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4040 unsigned Flags) const {
4041 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4042 SDLoc DL(N);
4043 EVT Ty = getPointerTy(DAG.getDataLayout());
4044 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4045 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4046}
4047
Tim Northover3b0846e2014-05-24 12:50:23 +00004048SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4049 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004050 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004051 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00004052 unsigned char OpFlags =
4053 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004054
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004055 if (OpFlags != AArch64II::MO_NO_FLAG)
4056 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4057 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004058
David Green9dd1d452018-08-22 11:31:39 +00004059 // This also catches the large code model case for Darwin, and tiny code
4060 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004061 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004062 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004063 }
4064
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004065 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004066 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004067 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004068 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004069 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004070 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004071 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004072 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004073 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4074 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004075 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004076 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4077 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4078 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004079}
4080
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004081/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004082/// and calls to compute the variable's address (for Darwin, currently) and
4083/// return an SDValue containing the final node.
4084
4085/// Darwin only has one TLS scheme which must be capable of dealing with the
4086/// fully general situation, in the worst case. This means:
4087/// + "extern __thread" declaration.
4088/// + Defined in a possibly unknown dynamic library.
4089///
4090/// The general system is that each __thread variable has a [3 x i64] descriptor
4091/// which contains information used by the runtime to calculate the address. The
4092/// only part of this the compiler needs to know about is the first xword, which
4093/// contains a function pointer that must be called with the address of the
4094/// entire descriptor in "x0".
4095///
4096/// Since this descriptor may be in a different unit, in general even the
4097/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4098/// is:
4099/// adrp x0, _var@TLVPPAGE
4100/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4101/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4102/// ; the function pointer
4103/// blr x1 ; Uses descriptor address in x0
4104/// ; Address of _var is now in x0.
4105///
4106/// If the address of _var's descriptor *is* known to the linker, then it can
4107/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4108/// a slight efficiency gain.
4109SDValue
4110AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4111 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004112 assert(Subtarget->isTargetDarwin() &&
4113 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004114
4115 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004116 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004117 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4118
4119 SDValue TLVPAddr =
4120 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4121 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4122
4123 // The first entry in the descriptor is a function pointer that we must call
4124 // to obtain the address of the variable.
4125 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004126 SDValue FuncTLVGet = DAG.getLoad(
4127 MVT::i64, DL, Chain, DescAddr,
4128 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4129 /* Alignment = */ 8,
4130 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4131 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004132 Chain = FuncTLVGet.getValue(1);
4133
Matthias Braun941a7052016-07-28 18:40:00 +00004134 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4135 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004136
4137 // TLS calls preserve all registers except those that absolutely must be
4138 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4139 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004140 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4141 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4142 if (Subtarget->hasCustomCallingConv())
4143 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004144
4145 // Finally, we can make the call. This is just a degenerate version of a
4146 // normal AArch64 call node: x0 takes the address of the descriptor, and
4147 // returns the address of the variable in this thread.
4148 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4149 Chain =
4150 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4151 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4152 DAG.getRegisterMask(Mask), Chain.getValue(1));
4153 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4154}
4155
4156/// When accessing thread-local variables under either the general-dynamic or
4157/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4158/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004159/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004160///
Kristof Beylsaea84612015-03-04 09:12:08 +00004161/// The sequence is:
4162/// adrp x0, :tlsdesc:var
4163/// ldr x1, [x0, #:tlsdesc_lo12:var]
4164/// add x0, x0, #:tlsdesc_lo12:var
4165/// .tlsdesccall var
4166/// blr x1
4167/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004168///
Kristof Beylsaea84612015-03-04 09:12:08 +00004169/// The above sequence must be produced unscheduled, to enable the linker to
4170/// optimize/relax this sequence.
4171/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4172/// above sequence, and expanded really late in the compilation flow, to ensure
4173/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004174SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4175 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004176 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004177 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004178
Kristof Beylsaea84612015-03-04 09:12:08 +00004179 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004180 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004181
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004182 Chain =
4183 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004184 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004185
4186 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4187}
4188
4189SDValue
4190AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4191 SelectionDAG &DAG) const {
4192 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004193 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4194 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004195 // Different choices can be made for the maximum size of the TLS area for a
4196 // module. For the small address model, the default TLS size is 16MiB and the
4197 // maximum TLS size is 4GiB.
4198 // FIXME: add -mtls-size command line option and make it control the 16MiB
4199 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004200 // FIXME: add tiny codemodel support. We currently generate the same code as
4201 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004202 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4203
4204 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004205
Kristof Beylsaea84612015-03-04 09:12:08 +00004206 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4207 if (Model == TLSModel::LocalDynamic)
4208 Model = TLSModel::GeneralDynamic;
4209 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004210
4211 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004212 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004213 SDLoc DL(Op);
4214 const GlobalValue *GV = GA->getGlobal();
4215
4216 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4217
4218 if (Model == TLSModel::LocalExec) {
4219 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004220 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004221 SDValue LoVar = DAG.getTargetGlobalAddress(
4222 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004223 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004224
Kristof Beylsaea84612015-03-04 09:12:08 +00004225 SDValue TPWithOff_lo =
4226 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004227 HiVar,
4228 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004229 0);
4230 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004231 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4232 LoVar,
4233 DAG.getTargetConstant(0, DL, MVT::i32)),
4234 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004235 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004236 } else if (Model == TLSModel::InitialExec) {
4237 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4238 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4239 } else if (Model == TLSModel::LocalDynamic) {
4240 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4241 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4242 // the beginning of the module's TLS region, followed by a DTPREL offset
4243 // calculation.
4244
4245 // These accesses will need deduplicating if there's more than one.
4246 AArch64FunctionInfo *MFI =
4247 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4248 MFI->incNumLocalDynamicTLSAccesses();
4249
Tim Northover3b0846e2014-05-24 12:50:23 +00004250 // The call needs a relocation too for linker relaxation. It doesn't make
4251 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4252 // the address.
4253 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4254 AArch64II::MO_TLS);
4255
4256 // Now we can calculate the offset from TPIDR_EL0 to this module's
4257 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004258 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004259
4260 // Now use :dtprel_whatever: operations to calculate this variable's offset
4261 // in its thread-storage area.
4262 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004263 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004264 SDValue LoVar = DAG.getTargetGlobalAddress(
4265 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004266 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4267
Kristof Beylsaea84612015-03-04 09:12:08 +00004268 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004269 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004270 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004271 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4272 DAG.getTargetConstant(0, DL, MVT::i32)),
4273 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004274 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004275 // The call needs a relocation too for linker relaxation. It doesn't make
4276 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4277 // the address.
4278 SDValue SymAddr =
4279 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4280
4281 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004282 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004283 } else
4284 llvm_unreachable("Unsupported ELF TLS access model");
4285
4286 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4287}
4288
Martin Storsjocc240962018-03-10 19:05:21 +00004289SDValue
4290AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4291 SelectionDAG &DAG) const {
4292 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4293
4294 SDValue Chain = DAG.getEntryNode();
4295 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4296 SDLoc DL(Op);
4297
4298 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4299
4300 // Load the ThreadLocalStoragePointer from the TEB
4301 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4302 SDValue TLSArray =
4303 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4304 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4305 Chain = TLSArray.getValue(1);
4306
4307 // Load the TLS index from the C runtime;
4308 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4309 // This also does the same as LOADgot, but using a generic i32 load,
4310 // while LOADgot only loads i64.
4311 SDValue TLSIndexHi =
4312 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4313 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4314 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4315 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4316 SDValue TLSIndex =
4317 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4318 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4319 Chain = TLSIndex.getValue(1);
4320
4321 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4322 // offset into the TLSArray.
4323 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4324 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4325 DAG.getConstant(3, DL, PtrVT));
4326 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4327 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4328 MachinePointerInfo());
4329 Chain = TLS.getValue(1);
4330
4331 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4332 const GlobalValue *GV = GA->getGlobal();
4333 SDValue TGAHi = DAG.getTargetGlobalAddress(
4334 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4335 SDValue TGALo = DAG.getTargetGlobalAddress(
4336 GV, DL, PtrVT, 0,
4337 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4338
4339 // Add the offset from the start of the .tls section (section base).
4340 SDValue Addr =
4341 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4342 DAG.getTargetConstant(0, DL, MVT::i32)),
4343 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004344 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004345 return Addr;
4346}
4347
Tim Northover3b0846e2014-05-24 12:50:23 +00004348SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4349 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004350 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004351 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004352 return LowerToTLSEmulatedModel(GA, DAG);
4353
Tim Northover3b0846e2014-05-24 12:50:23 +00004354 if (Subtarget->isTargetDarwin())
4355 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004356 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004357 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004358 if (Subtarget->isTargetWindows())
4359 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004360
4361 llvm_unreachable("Unexpected platform trying to use TLS");
4362}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004363
Tim Northover3b0846e2014-05-24 12:50:23 +00004364SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4365 SDValue Chain = Op.getOperand(0);
4366 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4367 SDValue LHS = Op.getOperand(2);
4368 SDValue RHS = Op.getOperand(3);
4369 SDValue Dest = Op.getOperand(4);
4370 SDLoc dl(Op);
4371
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004372 MachineFunction &MF = DAG.getMachineFunction();
4373 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4374 // will not be produced, as they are conditional branch instructions that do
4375 // not set flags.
4376 bool ProduceNonFlagSettingCondBr =
4377 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4378
Tim Northover3b0846e2014-05-24 12:50:23 +00004379 // Handle f128 first, since lowering it will result in comparing the return
4380 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4381 // is expecting to deal with.
4382 if (LHS.getValueType() == MVT::f128) {
4383 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4384
4385 // If softenSetCCOperands returned a scalar, we need to compare the result
4386 // against zero to select between true and false values.
4387 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004388 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004389 CC = ISD::SETNE;
4390 }
4391 }
4392
4393 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4394 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004395 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4396 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004397 // Only lower legal XALUO ops.
4398 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4399 return SDValue();
4400
4401 // The actual operation with overflow check.
4402 AArch64CC::CondCode OFCC;
4403 SDValue Value, Overflow;
4404 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4405
4406 if (CC == ISD::SETNE)
4407 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004408 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004409
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004410 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4411 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004412 }
4413
4414 if (LHS.getValueType().isInteger()) {
4415 assert((LHS.getValueType() == RHS.getValueType()) &&
4416 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4417
4418 // If the RHS of the comparison is zero, we can potentially fold this
4419 // to a specialized branch.
4420 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004421 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004422 if (CC == ISD::SETEQ) {
4423 // See if we can use a TBZ to fold in an AND as well.
4424 // TBZ has a smaller branch displacement than CBZ. If the offset is
4425 // out of bounds, a late MI-layer pass rewrites branches.
4426 // 403.gcc is an example that hits this case.
4427 if (LHS.getOpcode() == ISD::AND &&
4428 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4429 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4430 SDValue Test = LHS.getOperand(0);
4431 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004432 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004433 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4434 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004435 }
4436
4437 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4438 } else if (CC == ISD::SETNE) {
4439 // See if we can use a TBZ to fold in an AND as well.
4440 // TBZ has a smaller branch displacement than CBZ. If the offset is
4441 // out of bounds, a late MI-layer pass rewrites branches.
4442 // 403.gcc is an example that hits this case.
4443 if (LHS.getOpcode() == ISD::AND &&
4444 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4445 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4446 SDValue Test = LHS.getOperand(0);
4447 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004448 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004449 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4450 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004451 }
4452
4453 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004454 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4455 // Don't combine AND since emitComparison converts the AND to an ANDS
4456 // (a.k.a. TST) and the test in the test bit and branch instruction
4457 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004458 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004459 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004460 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004461 }
4462 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004463 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004464 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004465 // Don't combine AND since emitComparison converts the AND to an ANDS
4466 // (a.k.a. TST) and the test in the test bit and branch instruction
4467 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004468 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004469 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004470 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004471 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004472
4473 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004474 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004475 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4476 Cmp);
4477 }
4478
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004479 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4480 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004481
4482 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4483 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004484 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004485 AArch64CC::CondCode CC1, CC2;
4486 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004487 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004488 SDValue BR1 =
4489 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4490 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004491 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004492 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4493 Cmp);
4494 }
4495
4496 return BR1;
4497}
4498
4499SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4500 SelectionDAG &DAG) const {
4501 EVT VT = Op.getValueType();
4502 SDLoc DL(Op);
4503
4504 SDValue In1 = Op.getOperand(0);
4505 SDValue In2 = Op.getOperand(1);
4506 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004507
4508 if (SrcVT.bitsLT(VT))
4509 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4510 else if (SrcVT.bitsGT(VT))
4511 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004512
4513 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004514 uint64_t EltMask;
4515 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004516
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004517 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004518 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004519 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004520 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004521 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004522 DAG.getUNDEF(VecVT), In2);
4523 } else {
4524 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4525 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4526 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004527 };
4528
4529 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4530 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4531 EltMask = 0x80000000ULL;
4532 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004533 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004534 VecVT = MVT::v2i64;
4535
Eric Christopher572e03a2015-06-19 01:53:21 +00004536 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004537 // immediate moves cannot materialize that in a single instruction for
4538 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004539 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004540
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004541 setVecVal(AArch64::dsub);
4542 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4543 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4544 EltMask = 0x8000ULL;
4545 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004546 } else {
4547 llvm_unreachable("Invalid type for copysign!");
4548 }
4549
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004550 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004551
4552 // If we couldn't materialize the mask above, then the mask vector will be
4553 // the zero vector, and we need to negate it here.
4554 if (VT == MVT::f64 || VT == MVT::v2f64) {
4555 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4556 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4557 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4558 }
4559
4560 SDValue Sel =
4561 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4562
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004563 if (VT == MVT::f16)
4564 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004565 if (VT == MVT::f32)
4566 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4567 else if (VT == MVT::f64)
4568 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4569 else
4570 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4571}
4572
4573SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004574 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004575 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004576 return SDValue();
4577
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004578 if (!Subtarget->hasNEON())
4579 return SDValue();
4580
Tim Northover3b0846e2014-05-24 12:50:23 +00004581 // While there is no integer popcount instruction, it can
4582 // be more efficiently lowered to the following sequence that uses
4583 // AdvSIMD registers/instructions as long as the copies to/from
4584 // the AdvSIMD registers are cheap.
4585 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4586 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4587 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4588 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4589 SDValue Val = Op.getOperand(0);
4590 SDLoc DL(Op);
4591 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004592
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004593 if (VT == MVT::i32 || VT == MVT::i64) {
4594 if (VT == MVT::i32)
4595 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4596 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004597
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004598 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4599 SDValue UaddLV = DAG.getNode(
4600 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4601 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004602
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004603 if (VT == MVT::i64)
4604 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4605 return UaddLV;
4606 }
4607
4608 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4609 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4610 "Unexpected type for custom ctpop lowering");
4611
4612 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4613 Val = DAG.getBitcast(VT8Bit, Val);
4614 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4615
4616 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4617 unsigned EltSize = 8;
4618 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4619 while (EltSize != VT.getScalarSizeInBits()) {
4620 EltSize *= 2;
4621 NumElts /= 2;
4622 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4623 Val = DAG.getNode(
4624 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4625 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4626 }
4627
4628 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004629}
4630
4631SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4632
4633 if (Op.getValueType().isVector())
4634 return LowerVSETCC(Op, DAG);
4635
4636 SDValue LHS = Op.getOperand(0);
4637 SDValue RHS = Op.getOperand(1);
4638 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4639 SDLoc dl(Op);
4640
4641 // We chose ZeroOrOneBooleanContents, so use zero and one.
4642 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004643 SDValue TVal = DAG.getConstant(1, dl, VT);
4644 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004645
4646 // Handle f128 first, since one possible outcome is a normal integer
4647 // comparison which gets picked up by the next if statement.
4648 if (LHS.getValueType() == MVT::f128) {
4649 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4650
4651 // If softenSetCCOperands returned a scalar, use it.
4652 if (!RHS.getNode()) {
4653 assert(LHS.getValueType() == Op.getValueType() &&
4654 "Unexpected setcc expansion!");
4655 return LHS;
4656 }
4657 }
4658
4659 if (LHS.getValueType().isInteger()) {
4660 SDValue CCVal;
4661 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004662 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004663
4664 // Note that we inverted the condition above, so we reverse the order of
4665 // the true and false operands here. This will allow the setcc to be
4666 // matched to a single CSINC instruction.
4667 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4668 }
4669
4670 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004671 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4672 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004673
4674 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4675 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004676 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004677
4678 AArch64CC::CondCode CC1, CC2;
4679 changeFPCCToAArch64CC(CC, CC1, CC2);
4680 if (CC2 == AArch64CC::AL) {
4681 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004682 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004683
4684 // Note that we inverted the condition above, so we reverse the order of
4685 // the true and false operands here. This will allow the setcc to be
4686 // matched to a single CSINC instruction.
4687 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4688 } else {
4689 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4690 // totally clean. Some of them require two CSELs to implement. As is in
4691 // this case, we emit the first CSEL and then emit a second using the output
4692 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4693
4694 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004695 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004696 SDValue CS1 =
4697 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4698
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004699 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004700 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4701 }
4702}
4703
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004704SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4705 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004706 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004707 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004708 // Handle f128 first, because it will result in a comparison of some RTLIB
4709 // call result against zero.
4710 if (LHS.getValueType() == MVT::f128) {
4711 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4712
4713 // If softenSetCCOperands returned a scalar, we need to compare the result
4714 // against zero to select between true and false values.
4715 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004716 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004717 CC = ISD::SETNE;
4718 }
4719 }
4720
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004721 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004722 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004723 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4724 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4725 }
4726
4727 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004728 if (LHS.getValueType().isInteger()) {
4729 assert((LHS.getValueType() == RHS.getValueType()) &&
4730 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4731
4732 unsigned Opcode = AArch64ISD::CSEL;
4733
4734 // If both the TVal and the FVal are constants, see if we can swap them in
4735 // order to for a CSINV or CSINC out of them.
4736 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4737 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4738
4739 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4740 std::swap(TVal, FVal);
4741 std::swap(CTVal, CFVal);
4742 CC = ISD::getSetCCInverse(CC, true);
4743 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4744 std::swap(TVal, FVal);
4745 std::swap(CTVal, CFVal);
4746 CC = ISD::getSetCCInverse(CC, true);
4747 } else if (TVal.getOpcode() == ISD::XOR) {
4748 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4749 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004750 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004751 std::swap(TVal, FVal);
4752 std::swap(CTVal, CFVal);
4753 CC = ISD::getSetCCInverse(CC, true);
4754 }
4755 } else if (TVal.getOpcode() == ISD::SUB) {
4756 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4757 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004758 if (isNullConstant(TVal.getOperand(0))) {
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 (CTVal && CFVal) {
4764 const int64_t TrueVal = CTVal->getSExtValue();
4765 const int64_t FalseVal = CFVal->getSExtValue();
4766 bool Swap = false;
4767
4768 // If both TVal and FVal are constants, see if FVal is the
4769 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4770 // instead of a CSEL in that case.
4771 if (TrueVal == ~FalseVal) {
4772 Opcode = AArch64ISD::CSINV;
4773 } else if (TrueVal == -FalseVal) {
4774 Opcode = AArch64ISD::CSNEG;
4775 } else if (TVal.getValueType() == MVT::i32) {
4776 // If our operands are only 32-bit wide, make sure we use 32-bit
4777 // arithmetic for the check whether we can use CSINC. This ensures that
4778 // the addition in the check will wrap around properly in case there is
4779 // an overflow (which would not be the case if we do the check with
4780 // 64-bit arithmetic).
4781 const uint32_t TrueVal32 = CTVal->getZExtValue();
4782 const uint32_t FalseVal32 = CFVal->getZExtValue();
4783
4784 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4785 Opcode = AArch64ISD::CSINC;
4786
4787 if (TrueVal32 > FalseVal32) {
4788 Swap = true;
4789 }
4790 }
4791 // 64-bit check whether we can use CSINC.
4792 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4793 Opcode = AArch64ISD::CSINC;
4794
4795 if (TrueVal > FalseVal) {
4796 Swap = true;
4797 }
4798 }
4799
4800 // Swap TVal and FVal if necessary.
4801 if (Swap) {
4802 std::swap(TVal, FVal);
4803 std::swap(CTVal, CFVal);
4804 CC = ISD::getSetCCInverse(CC, true);
4805 }
4806
4807 if (Opcode != AArch64ISD::CSEL) {
4808 // Drop FVal since we can get its value by simply inverting/negating
4809 // TVal.
4810 FVal = TVal;
4811 }
4812 }
4813
Chad Rosier58f505b2016-08-26 18:05:50 +00004814 // Avoid materializing a constant when possible by reusing a known value in
4815 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004816 // is one, zero or negative one in the case of a CSEL. We can always
4817 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4818 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004819 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4820 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4821 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4822 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4823 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4824 // "a != C ? x : a" to avoid materializing C.
4825 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4826 TVal = LHS;
4827 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4828 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004829 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4830 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4831 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4832 // avoid materializing C.
4833 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4834 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4835 Opcode = AArch64ISD::CSINV;
4836 TVal = LHS;
4837 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4838 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004839 }
4840
Tim Northover3b0846e2014-05-24 12:50:23 +00004841 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004842 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004843 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004844 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4845 }
4846
4847 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004848 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4849 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004850 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004851 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004852 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004853
4854 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4855 // clean. Some of them require two CSELs to implement.
4856 AArch64CC::CondCode CC1, CC2;
4857 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004858
4859 if (DAG.getTarget().Options.UnsafeFPMath) {
4860 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4861 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4862 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4863 if (RHSVal && RHSVal->isZero()) {
4864 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4865 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4866
4867 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004868 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004869 TVal = LHS;
4870 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004871 CFVal && CFVal->isZero() &&
4872 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004873 FVal = LHS;
4874 }
4875 }
4876
4877 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004878 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004879 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4880
4881 // If we need a second CSEL, emit it, using the output of the first as the
4882 // RHS. We're effectively OR'ing the two CC's together.
4883 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004884 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004885 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4886 }
4887
4888 // Otherwise, return the output of the first CSEL.
4889 return CS1;
4890}
4891
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004892SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4893 SelectionDAG &DAG) const {
4894 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4895 SDValue LHS = Op.getOperand(0);
4896 SDValue RHS = Op.getOperand(1);
4897 SDValue TVal = Op.getOperand(2);
4898 SDValue FVal = Op.getOperand(3);
4899 SDLoc DL(Op);
4900 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4901}
4902
4903SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4904 SelectionDAG &DAG) const {
4905 SDValue CCVal = Op->getOperand(0);
4906 SDValue TVal = Op->getOperand(1);
4907 SDValue FVal = Op->getOperand(2);
4908 SDLoc DL(Op);
4909
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004910 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4911 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004912 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004913 // Only lower legal XALUO ops.
4914 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4915 return SDValue();
4916
4917 AArch64CC::CondCode OFCC;
4918 SDValue Value, Overflow;
4919 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004920 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004921
4922 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4923 CCVal, Overflow);
4924 }
4925
4926 // Lower it the same way as we would lower a SELECT_CC node.
4927 ISD::CondCode CC;
4928 SDValue LHS, RHS;
4929 if (CCVal.getOpcode() == ISD::SETCC) {
4930 LHS = CCVal.getOperand(0);
4931 RHS = CCVal.getOperand(1);
4932 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4933 } else {
4934 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004935 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004936 CC = ISD::SETNE;
4937 }
4938 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4939}
4940
Tim Northover3b0846e2014-05-24 12:50:23 +00004941SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4942 SelectionDAG &DAG) const {
4943 // Jump table entries as PC relative offsets. No additional tweaking
4944 // is necessary here. Just get the address of the jump table.
4945 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004946
4947 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4948 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004949 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004950 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4951 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004952 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004953 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004954}
4955
Tim Northover1c353412018-10-24 20:19:09 +00004956SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
4957 SelectionDAG &DAG) const {
4958 // Jump table entries as PC relative offsets. No additional tweaking
4959 // is necessary here. Just get the address of the jump table.
4960 SDLoc DL(Op);
4961 SDValue JT = Op.getOperand(1);
4962 SDValue Entry = Op.getOperand(2);
4963 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
4964
4965 SDNode *Dest =
4966 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
4967 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
4968 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
4969 SDValue(Dest, 0));
4970}
4971
Tim Northover3b0846e2014-05-24 12:50:23 +00004972SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4973 SelectionDAG &DAG) const {
4974 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004975
4976 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4977 // Use the GOT for the large code model on iOS.
4978 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004979 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004980 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004981 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004982 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4983 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004984 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004985 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004986 }
4987}
4988
4989SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4990 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004991 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004992 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4993 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004994 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004995 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4996 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004997 }
David Green9dd1d452018-08-22 11:31:39 +00004998 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004999}
5000
5001SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5002 SelectionDAG &DAG) const {
5003 AArch64FunctionInfo *FuncInfo =
5004 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5005
5006 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00005007 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5008 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005009 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5010 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00005011 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00005012}
5013
Martin Storsjo68266fa2017-07-13 17:03:12 +00005014SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5015 SelectionDAG &DAG) const {
5016 AArch64FunctionInfo *FuncInfo =
5017 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5018
5019 SDLoc DL(Op);
5020 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5021 ? FuncInfo->getVarArgsGPRIndex()
5022 : FuncInfo->getVarArgsStackIndex(),
5023 getPointerTy(DAG.getDataLayout()));
5024 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5025 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5026 MachinePointerInfo(SV));
5027}
5028
Tim Northover3b0846e2014-05-24 12:50:23 +00005029SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5030 SelectionDAG &DAG) const {
5031 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5032 // Standard, section B.3.
5033 MachineFunction &MF = DAG.getMachineFunction();
5034 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005035 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005036 SDLoc DL(Op);
5037
5038 SDValue Chain = Op.getOperand(0);
5039 SDValue VAList = Op.getOperand(1);
5040 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5041 SmallVector<SDValue, 4> MemOps;
5042
5043 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005044 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005045 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005046 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005047
5048 // void *__gr_top at offset 8
5049 int GPRSize = FuncInfo->getVarArgsGPRSize();
5050 if (GPRSize > 0) {
5051 SDValue GRTop, GRTopAddr;
5052
Mehdi Amini44ede332015-07-09 02:09:04 +00005053 GRTopAddr =
5054 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005055
Mehdi Amini44ede332015-07-09 02:09:04 +00005056 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5057 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5058 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005059
5060 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005061 MachinePointerInfo(SV, 8),
5062 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005063 }
5064
5065 // void *__vr_top at offset 16
5066 int FPRSize = FuncInfo->getVarArgsFPRSize();
5067 if (FPRSize > 0) {
5068 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005069 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5070 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005071
Mehdi Amini44ede332015-07-09 02:09:04 +00005072 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5073 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5074 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005075
5076 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005077 MachinePointerInfo(SV, 16),
5078 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005079 }
5080
5081 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005082 SDValue GROffsAddr =
5083 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005084 MemOps.push_back(DAG.getStore(
5085 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5086 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005087
5088 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005089 SDValue VROffsAddr =
5090 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005091 MemOps.push_back(DAG.getStore(
5092 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5093 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005094
5095 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5096}
5097
5098SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5099 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005100 MachineFunction &MF = DAG.getMachineFunction();
5101
Matthias Braunf1caa282017-12-15 22:22:58 +00005102 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005103 return LowerWin64_VASTART(Op, DAG);
5104 else if (Subtarget->isTargetDarwin())
5105 return LowerDarwin_VASTART(Op, DAG);
5106 else
5107 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005108}
5109
5110SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5111 SelectionDAG &DAG) const {
5112 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5113 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005114 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005115 unsigned VaListSize =
5116 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005117 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5118 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5119
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005120 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5121 Op.getOperand(2),
5122 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005123 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005124 MachinePointerInfo(SrcSV));
5125}
5126
5127SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5128 assert(Subtarget->isTargetDarwin() &&
5129 "automatic va_arg instruction only works on Darwin");
5130
5131 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5132 EVT VT = Op.getValueType();
5133 SDLoc DL(Op);
5134 SDValue Chain = Op.getOperand(0);
5135 SDValue Addr = Op.getOperand(1);
5136 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005137 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005138
Justin Lebar9c375812016-07-15 18:27:10 +00005139 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005140 Chain = VAList.getValue(1);
5141
5142 if (Align > 8) {
5143 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005144 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5145 DAG.getConstant(Align - 1, DL, PtrVT));
5146 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5147 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005148 }
5149
5150 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005151 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005152
5153 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5154 // up to 64 bits. At the very least, we have to increase the striding of the
5155 // vaargs list to match this, and for FP values we need to introduce
5156 // FP_ROUND nodes as well.
5157 if (VT.isInteger() && !VT.isVector())
5158 ArgSize = 8;
5159 bool NeedFPTrunc = false;
5160 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5161 ArgSize = 8;
5162 NeedFPTrunc = true;
5163 }
5164
5165 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005166 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5167 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005168 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005169 SDValue APStore =
5170 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005171
5172 // Load the actual argument out of the pointer VAList
5173 if (NeedFPTrunc) {
5174 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005175 SDValue WideFP =
5176 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005177 // Round the value down to an f32.
5178 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005179 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005180 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5181 // Merge the rounded value with the chain output of the load.
5182 return DAG.getMergeValues(Ops, DL);
5183 }
5184
Justin Lebar9c375812016-07-15 18:27:10 +00005185 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005186}
5187
5188SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5189 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005190 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5191 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005192
5193 EVT VT = Op.getValueType();
5194 SDLoc DL(Op);
5195 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5196 SDValue FrameAddr =
5197 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5198 while (Depth--)
5199 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005200 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005201 return FrameAddr;
5202}
5203
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005204SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5205 SelectionDAG &DAG) const {
5206 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5207
5208 EVT VT = getPointerTy(DAG.getDataLayout());
5209 SDLoc DL(Op);
5210 int FI = MFI.CreateFixedObject(4, 0, false);
5211 return DAG.getFrameIndex(FI, VT);
5212}
5213
Petr Hosekfcbec022019-02-13 17:28:47 +00005214#define GET_REGISTER_MATCHER
5215#include "AArch64GenAsmMatcher.inc"
5216
Tim Northover3b0846e2014-05-24 12:50:23 +00005217// FIXME? Maybe this could be a TableGen attribute on some registers and
5218// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005219unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5220 SelectionDAG &DAG) const {
Petr Hosekfcbec022019-02-13 17:28:47 +00005221 unsigned Reg = MatchRegisterName(RegName);
5222 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5223 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5224 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5225 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5226 Reg = 0;
5227 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005228 if (Reg)
5229 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005230 report_fatal_error(Twine("Invalid register name \""
5231 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005232}
5233
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005234SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5235 SelectionDAG &DAG) const {
5236 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5237
5238 EVT VT = Op.getValueType();
5239 SDLoc DL(Op);
5240
5241 SDValue FrameAddr =
5242 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5243 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5244
5245 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5246}
5247
Tim Northover3b0846e2014-05-24 12:50:23 +00005248SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5249 SelectionDAG &DAG) const {
5250 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005251 MachineFrameInfo &MFI = MF.getFrameInfo();
5252 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005253
5254 EVT VT = Op.getValueType();
5255 SDLoc DL(Op);
5256 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5257 if (Depth) {
5258 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005259 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005260 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5261 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005262 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005263 }
5264
5265 // Return LR, which contains the return address. Mark it an implicit live-in.
5266 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5267 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5268}
5269
5270/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5271/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5272SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5273 SelectionDAG &DAG) const {
5274 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5275 EVT VT = Op.getValueType();
5276 unsigned VTBits = VT.getSizeInBits();
5277 SDLoc dl(Op);
5278 SDValue ShOpLo = Op.getOperand(0);
5279 SDValue ShOpHi = Op.getOperand(1);
5280 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005281 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5282
5283 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5284
5285 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005286 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005287 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5288
5289 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5290 // is "undef". We wanted 0, so CSEL it directly.
5291 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5292 ISD::SETEQ, dl, DAG);
5293 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5294 HiBitsForLo =
5295 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5296 HiBitsForLo, CCVal, Cmp);
5297
Tim Northover3b0846e2014-05-24 12:50:23 +00005298 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005299 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005300
Tim Northoverf3be9d52015-12-02 00:33:54 +00005301 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5302 SDValue LoForNormalShift =
5303 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005304
Tim Northoverf3be9d52015-12-02 00:33:54 +00005305 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5306 dl, DAG);
5307 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5308 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5309 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5310 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005311
5312 // AArch64 shifts larger than the register width are wrapped rather than
5313 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005314 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5315 SDValue HiForBigShift =
5316 Opc == ISD::SRA
5317 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5318 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5319 : DAG.getConstant(0, dl, VT);
5320 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5321 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005322
5323 SDValue Ops[2] = { Lo, Hi };
5324 return DAG.getMergeValues(Ops, dl);
5325}
5326
5327/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5328/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5329SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005330 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005331 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5332 EVT VT = Op.getValueType();
5333 unsigned VTBits = VT.getSizeInBits();
5334 SDLoc dl(Op);
5335 SDValue ShOpLo = Op.getOperand(0);
5336 SDValue ShOpHi = Op.getOperand(1);
5337 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005338
5339 assert(Op.getOpcode() == ISD::SHL_PARTS);
5340 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005341 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005342 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5343
5344 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5345 // is "undef". We wanted 0, so CSEL it directly.
5346 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5347 ISD::SETEQ, dl, DAG);
5348 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5349 LoBitsForHi =
5350 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5351 LoBitsForHi, CCVal, Cmp);
5352
Tim Northover3b0846e2014-05-24 12:50:23 +00005353 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005354 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005355 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5356 SDValue HiForNormalShift =
5357 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005358
Tim Northoverf3be9d52015-12-02 00:33:54 +00005359 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005360
Tim Northoverf3be9d52015-12-02 00:33:54 +00005361 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5362 dl, DAG);
5363 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5364 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5365 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005366
5367 // AArch64 shifts of larger than register sizes are wrapped rather than
5368 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005369 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5370 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5371 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5372 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005373
5374 SDValue Ops[2] = { Lo, Hi };
5375 return DAG.getMergeValues(Ops, dl);
5376}
5377
5378bool AArch64TargetLowering::isOffsetFoldingLegal(
5379 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005380 // Offsets are folded in the DAG combine rather than here so that we can
5381 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005382 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005383}
5384
5385bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005386 bool IsLegal = false;
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005387 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5388 // 16-bit case when target has full fp16 support.
5389 // FIXME: We should be able to handle f128 as well with a clever lowering.
5390 const APInt ImmInt = Imm.bitcastToAPInt();
JF Bastienda339002018-09-05 23:38:11 +00005391 if (VT == MVT::f64)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005392 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005393 else if (VT == MVT::f32)
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005394 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
JF Bastienda339002018-09-05 23:38:11 +00005395 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005396 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5397 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5398 // generate that fmov.
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005399
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005400 // If we can not materialize in immediate field for fmov, check if the
5401 // value can be encoded as the immediate operand of a logical instruction.
5402 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5403 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32))
5404 IsLegal = AArch64_AM::isAnyMOVWMovAlias(ImmInt.getZExtValue(),
5405 VT.getSizeInBits());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005406
Adhemerval Zanellab3ccc552019-02-01 12:26:06 +00005407 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5408 << " imm value: "; Imm.dump(););
5409 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00005410}
5411
5412//===----------------------------------------------------------------------===//
5413// AArch64 Optimization Hooks
5414//===----------------------------------------------------------------------===//
5415
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005416static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5417 SDValue Operand, SelectionDAG &DAG,
5418 int &ExtraSteps) {
5419 EVT VT = Operand.getValueType();
5420 if (ST->hasNEON() &&
5421 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5422 VT == MVT::f32 || VT == MVT::v1f32 ||
5423 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5424 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5425 // For the reciprocal estimates, convergence is quadratic, so the number
5426 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5427 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5428 // the result for float (23 mantissa bits) is 2 and for double (52
5429 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005430 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005431
5432 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5433 }
5434
5435 return SDValue();
5436}
5437
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005438SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5439 SelectionDAG &DAG, int Enabled,
5440 int &ExtraSteps,
5441 bool &UseOneConst,
5442 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005443 if (Enabled == ReciprocalEstimate::Enabled ||
5444 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5445 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5446 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005447 SDLoc DL(Operand);
5448 EVT VT = Operand.getValueType();
5449
5450 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005451 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005452
5453 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5454 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5455 for (int i = ExtraSteps; i > 0; --i) {
5456 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005457 Flags);
5458 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5459 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005460 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005461 if (!Reciprocal) {
5462 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5463 VT);
5464 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5465 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5466
Amara Emersond28f0cd42017-05-01 15:17:51 +00005467 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005468 // Correct the result if the operand is 0.0.
5469 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5470 VT, Eq, Operand, Estimate);
5471 }
5472
5473 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005474 return Estimate;
5475 }
5476
5477 return SDValue();
5478}
5479
5480SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5481 SelectionDAG &DAG, int Enabled,
5482 int &ExtraSteps) const {
5483 if (Enabled == ReciprocalEstimate::Enabled)
5484 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005485 DAG, ExtraSteps)) {
5486 SDLoc DL(Operand);
5487 EVT VT = Operand.getValueType();
5488
5489 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005490 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005491
5492 // Newton reciprocal iteration: E * (2 - X * E)
5493 // AArch64 reciprocal iteration instruction: (2 - M * N)
5494 for (int i = ExtraSteps; i > 0; --i) {
5495 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005496 Estimate, Flags);
5497 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005498 }
5499
5500 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005501 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005502 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005503
5504 return SDValue();
5505}
5506
Tim Northover3b0846e2014-05-24 12:50:23 +00005507//===----------------------------------------------------------------------===//
5508// AArch64 Inline Assembly Support
5509//===----------------------------------------------------------------------===//
5510
5511// Table of Constraints
5512// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005513// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005514//
5515// r - A general register
5516// w - An FP/SIMD register of some size in the range v0-v31
5517// x - An FP/SIMD register of some size in the range v0-v15
5518// I - Constant that can be used with an ADD instruction
5519// J - Constant that can be used with a SUB instruction
5520// K - Constant that can be used with a 32-bit logical instruction
5521// L - Constant that can be used with a 64-bit logical instruction
5522// M - Constant that can be used as a 32-bit MOV immediate
5523// N - Constant that can be used as a 64-bit MOV immediate
5524// Q - A memory reference with base register and no offset
5525// S - A symbolic address
5526// Y - Floating point constant zero
5527// Z - Integer constant zero
5528//
5529// Note that general register operands will be output using their 64-bit x
5530// register name, whatever the size of the variable, unless the asm operand
5531// is prefixed by the %w modifier. Floating-point and SIMD register operands
5532// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5533// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005534const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5535 // At this point, we have to lower this constraint to something else, so we
5536 // lower it to an "r" or "w". However, by doing this we will force the result
5537 // to be in register, while the X constraint is much more permissive.
5538 //
5539 // Although we are correct (we are free to emit anything, without
5540 // constraints), we might break use cases that would expect us to be more
5541 // efficient and emit something else.
5542 if (!Subtarget->hasFPARMv8())
5543 return "r";
5544
5545 if (ConstraintVT.isFloatingPoint())
5546 return "w";
5547
5548 if (ConstraintVT.isVector() &&
5549 (ConstraintVT.getSizeInBits() == 64 ||
5550 ConstraintVT.getSizeInBits() == 128))
5551 return "w";
5552
5553 return "r";
5554}
Tim Northover3b0846e2014-05-24 12:50:23 +00005555
5556/// getConstraintType - Given a constraint letter, return the type of
5557/// constraint it is for this target.
5558AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005559AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005560 if (Constraint.size() == 1) {
5561 switch (Constraint[0]) {
5562 default:
5563 break;
5564 case 'z':
5565 return C_Other;
5566 case 'x':
5567 case 'w':
5568 return C_RegisterClass;
5569 // An address with a single base register. Due to the way we
5570 // currently handle addresses it is the same as 'r'.
5571 case 'Q':
5572 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005573 case 'S': // A symbolic address
5574 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005575 }
5576 }
5577 return TargetLowering::getConstraintType(Constraint);
5578}
5579
5580/// Examine constraint type and operand type and determine a weight value.
5581/// This object must already have been set up with the operand type
5582/// and the current alternative constraint selected.
5583TargetLowering::ConstraintWeight
5584AArch64TargetLowering::getSingleConstraintMatchWeight(
5585 AsmOperandInfo &info, const char *constraint) const {
5586 ConstraintWeight weight = CW_Invalid;
5587 Value *CallOperandVal = info.CallOperandVal;
5588 // If we don't have a value, we can't do a match,
5589 // but allow it at the lowest weight.
5590 if (!CallOperandVal)
5591 return CW_Default;
5592 Type *type = CallOperandVal->getType();
5593 // Look at the constraint type.
5594 switch (*constraint) {
5595 default:
5596 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5597 break;
5598 case 'x':
5599 case 'w':
5600 if (type->isFloatingPointTy() || type->isVectorTy())
5601 weight = CW_Register;
5602 break;
5603 case 'z':
5604 weight = CW_Constant;
5605 break;
5606 }
5607 return weight;
5608}
5609
5610std::pair<unsigned, const TargetRegisterClass *>
5611AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005612 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005613 if (Constraint.size() == 1) {
5614 switch (Constraint[0]) {
5615 case 'r':
5616 if (VT.getSizeInBits() == 64)
5617 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5618 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5619 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005620 if (!Subtarget->hasFPARMv8())
5621 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005622 if (VT.getSizeInBits() == 16)
5623 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005624 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005625 return std::make_pair(0U, &AArch64::FPR32RegClass);
5626 if (VT.getSizeInBits() == 64)
5627 return std::make_pair(0U, &AArch64::FPR64RegClass);
5628 if (VT.getSizeInBits() == 128)
5629 return std::make_pair(0U, &AArch64::FPR128RegClass);
5630 break;
5631 // The instructions that this constraint is designed for can
5632 // only take 128-bit registers so just use that regclass.
5633 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005634 if (!Subtarget->hasFPARMv8())
5635 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005636 if (VT.getSizeInBits() == 128)
5637 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5638 break;
5639 }
5640 }
5641 if (StringRef("{cc}").equals_lower(Constraint))
5642 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5643
5644 // Use the default implementation in TargetLowering to convert the register
5645 // constraint into a member of a register class.
5646 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005647 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005648
5649 // Not found as a standard register?
5650 if (!Res.second) {
5651 unsigned Size = Constraint.size();
5652 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5653 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005654 int RegNo;
5655 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5656 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005657 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005658 // By default we'll emit v0-v31 for this unless there's a modifier where
5659 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005660 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5661 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5662 Res.second = &AArch64::FPR64RegClass;
5663 } else {
5664 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5665 Res.second = &AArch64::FPR128RegClass;
5666 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005667 }
5668 }
5669 }
5670
Eli Friedman071203b2018-08-24 19:12:13 +00005671 if (Res.second && !Subtarget->hasFPARMv8() &&
5672 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5673 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5674 return std::make_pair(0U, nullptr);
5675
Tim Northover3b0846e2014-05-24 12:50:23 +00005676 return Res;
5677}
5678
5679/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5680/// vector. If it is invalid, don't add anything to Ops.
5681void AArch64TargetLowering::LowerAsmOperandForConstraint(
5682 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5683 SelectionDAG &DAG) const {
5684 SDValue Result;
5685
5686 // Currently only support length 1 constraints.
5687 if (Constraint.length() != 1)
5688 return;
5689
5690 char ConstraintLetter = Constraint[0];
5691 switch (ConstraintLetter) {
5692 default:
5693 break;
5694
5695 // This set of constraints deal with valid constants for various instructions.
5696 // Validate and return a target constant for them if we can.
5697 case 'z': {
5698 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005699 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005700 return;
5701
5702 if (Op.getValueType() == MVT::i64)
5703 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5704 else
5705 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5706 break;
5707 }
Peter Smithc8117582018-05-16 09:33:25 +00005708 case 'S': {
5709 // An absolute symbolic address or label reference.
5710 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5711 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5712 GA->getValueType(0));
5713 } else if (const BlockAddressSDNode *BA =
5714 dyn_cast<BlockAddressSDNode>(Op)) {
5715 Result =
5716 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5717 } else if (const ExternalSymbolSDNode *ES =
5718 dyn_cast<ExternalSymbolSDNode>(Op)) {
5719 Result =
5720 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5721 } else
5722 return;
5723 break;
5724 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005725
5726 case 'I':
5727 case 'J':
5728 case 'K':
5729 case 'L':
5730 case 'M':
5731 case 'N':
5732 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5733 if (!C)
5734 return;
5735
5736 // Grab the value and do some validation.
5737 uint64_t CVal = C->getZExtValue();
5738 switch (ConstraintLetter) {
5739 // The I constraint applies only to simple ADD or SUB immediate operands:
5740 // i.e. 0 to 4095 with optional shift by 12
5741 // The J constraint applies only to ADD or SUB immediates that would be
5742 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5743 // instruction [or vice versa], in other words -1 to -4095 with optional
5744 // left shift by 12.
5745 case 'I':
5746 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5747 break;
5748 return;
5749 case 'J': {
5750 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005751 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5752 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005753 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005754 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005755 return;
5756 }
5757 // The K and L constraints apply *only* to logical immediates, including
5758 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5759 // been removed and MOV should be used). So these constraints have to
5760 // distinguish between bit patterns that are valid 32-bit or 64-bit
5761 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5762 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5763 // versa.
5764 case 'K':
5765 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5766 break;
5767 return;
5768 case 'L':
5769 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5770 break;
5771 return;
5772 // The M and N constraints are a superset of K and L respectively, for use
5773 // with the MOV (immediate) alias. As well as the logical immediates they
5774 // also match 32 or 64-bit immediates that can be loaded either using a
5775 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5776 // (M) or 64-bit 0x1234000000000000 (N) etc.
5777 // As a note some of this code is liberally stolen from the asm parser.
5778 case 'M': {
5779 if (!isUInt<32>(CVal))
5780 return;
5781 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5782 break;
5783 if ((CVal & 0xFFFF) == CVal)
5784 break;
5785 if ((CVal & 0xFFFF0000ULL) == CVal)
5786 break;
5787 uint64_t NCVal = ~(uint32_t)CVal;
5788 if ((NCVal & 0xFFFFULL) == NCVal)
5789 break;
5790 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5791 break;
5792 return;
5793 }
5794 case 'N': {
5795 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5796 break;
5797 if ((CVal & 0xFFFFULL) == CVal)
5798 break;
5799 if ((CVal & 0xFFFF0000ULL) == CVal)
5800 break;
5801 if ((CVal & 0xFFFF00000000ULL) == CVal)
5802 break;
5803 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5804 break;
5805 uint64_t NCVal = ~CVal;
5806 if ((NCVal & 0xFFFFULL) == NCVal)
5807 break;
5808 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5809 break;
5810 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5811 break;
5812 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5813 break;
5814 return;
5815 }
5816 default:
5817 return;
5818 }
5819
5820 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005821 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005822 break;
5823 }
5824
5825 if (Result.getNode()) {
5826 Ops.push_back(Result);
5827 return;
5828 }
5829
5830 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5831}
5832
5833//===----------------------------------------------------------------------===//
5834// AArch64 Advanced SIMD Support
5835//===----------------------------------------------------------------------===//
5836
5837/// WidenVector - Given a value in the V64 register class, produce the
5838/// equivalent value in the V128 register class.
5839static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5840 EVT VT = V64Reg.getValueType();
5841 unsigned NarrowSize = VT.getVectorNumElements();
5842 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5843 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5844 SDLoc DL(V64Reg);
5845
5846 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005847 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005848}
5849
5850/// getExtFactor - Determine the adjustment factor for the position when
5851/// generating an "extract from vector registers" instruction.
5852static unsigned getExtFactor(SDValue &V) {
5853 EVT EltType = V.getValueType().getVectorElementType();
5854 return EltType.getSizeInBits() / 8;
5855}
5856
5857/// NarrowVector - Given a value in the V128 register class, produce the
5858/// equivalent value in the V64 register class.
5859static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5860 EVT VT = V128Reg.getValueType();
5861 unsigned WideSize = VT.getVectorNumElements();
5862 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5863 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5864 SDLoc DL(V128Reg);
5865
5866 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5867}
5868
5869// Gather data to see if the operation can be modelled as a
5870// shuffle in combination with VEXTs.
5871SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5872 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005873 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005874 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005875 SDLoc dl(Op);
5876 EVT VT = Op.getValueType();
5877 unsigned NumElts = VT.getVectorNumElements();
5878
Tim Northover7324e842014-07-24 15:39:55 +00005879 struct ShuffleSourceInfo {
5880 SDValue Vec;
5881 unsigned MinElt;
5882 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005883
Tim Northover7324e842014-07-24 15:39:55 +00005884 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5885 // be compatible with the shuffle we intend to construct. As a result
5886 // ShuffleVec will be some sliding window into the original Vec.
5887 SDValue ShuffleVec;
5888
5889 // Code should guarantee that element i in Vec starts at element "WindowBase
5890 // + i * WindowScale in ShuffleVec".
5891 int WindowBase;
5892 int WindowScale;
5893
Tim Northover7324e842014-07-24 15:39:55 +00005894 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005895 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5896 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5897
5898 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005899 };
5900
5901 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5902 // node.
5903 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005904 for (unsigned i = 0; i < NumElts; ++i) {
5905 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005906 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005907 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005908 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5909 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005910 LLVM_DEBUG(
5911 dbgs() << "Reshuffle failed: "
5912 "a shuffle can only come from building a vector from "
5913 "various elements of other vectors, provided their "
5914 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005915 return SDValue();
5916 }
5917
Tim Northover7324e842014-07-24 15:39:55 +00005918 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005919 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005920 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005921 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005922 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005923
Tim Northover7324e842014-07-24 15:39:55 +00005924 // Update the minimum and maximum lane number seen.
5925 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5926 Source->MinElt = std::min(Source->MinElt, EltNo);
5927 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005928 }
5929
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005930 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005931 LLVM_DEBUG(
5932 dbgs() << "Reshuffle failed: currently only do something sane when at "
5933 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005934 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005935 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005936
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005937 // Find out the smallest element size among result and two sources, and use
5938 // it as element size to build the shuffle_vector.
5939 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005940 for (auto &Source : Sources) {
5941 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005942 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5943 SmallestEltTy = SrcEltTy;
5944 }
5945 }
5946 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005947 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005948 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5949 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005950
Tim Northover7324e842014-07-24 15:39:55 +00005951 // If the source vector is too wide or too narrow, we may nevertheless be able
5952 // to construct a compatible shuffle either by concatenating it with UNDEF or
5953 // extracting a suitable range of elements.
5954 for (auto &Src : Sources) {
5955 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005956
Tim Northover7324e842014-07-24 15:39:55 +00005957 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005958 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005959
5960 // This stage of the search produces a source with the same element type as
5961 // the original, but with a total width matching the BUILD_VECTOR output.
5962 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005963 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5964 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005965
5966 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5967 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005968 // We can pad out the smaller vector for free, so if it's part of a
5969 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005970 Src.ShuffleVec =
5971 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5972 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005973 continue;
5974 }
5975
Tim Northover7324e842014-07-24 15:39:55 +00005976 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005977
James Molloyf497d552014-10-17 17:06:31 +00005978 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005979 LLVM_DEBUG(
5980 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005981 return SDValue();
5982 }
5983
James Molloyf497d552014-10-17 17:06:31 +00005984 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005985 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005986 Src.ShuffleVec =
5987 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005988 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005989 Src.WindowBase = -NumSrcElts;
5990 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005991 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005992 Src.ShuffleVec =
5993 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005994 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005995 } else {
5996 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005997 SDValue VEXTSrc1 =
5998 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005999 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006000 SDValue VEXTSrc2 =
6001 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006002 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006003 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6004
6005 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006006 VEXTSrc2,
6007 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006008 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006009 }
6010 }
6011
Tim Northover7324e842014-07-24 15:39:55 +00006012 // Another possible incompatibility occurs from the vector element types. We
6013 // can fix this by bitcasting the source vectors to the same type we intend
6014 // for the shuffle.
6015 for (auto &Src : Sources) {
6016 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6017 if (SrcEltTy == SmallestEltTy)
6018 continue;
6019 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6020 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6021 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6022 Src.WindowBase *= Src.WindowScale;
6023 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006024
Tim Northover7324e842014-07-24 15:39:55 +00006025 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006026 LLVM_DEBUG(for (auto Src
6027 : Sources)
6028 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006029
6030 // The stars all align, our next step is to produce the mask for the shuffle.
6031 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006032 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006033 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006034 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006035 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006036 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006037
David Majnemer0d955d02016-08-11 22:21:41 +00006038 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006039 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6040
6041 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6042 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6043 // segment.
6044 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006045 int BitsDefined =
6046 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006047 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6048
6049 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6050 // starting at the appropriate offset.
6051 int *LaneMask = &Mask[i * ResMultiplier];
6052
6053 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6054 ExtractBase += NumElts * (Src - Sources.begin());
6055 for (int j = 0; j < LanesDefined; ++j)
6056 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006057 }
6058
6059 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006060 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006061 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006062 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006063 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006064
Tim Northover7324e842014-07-24 15:39:55 +00006065 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6066 for (unsigned i = 0; i < Sources.size(); ++i)
6067 ShuffleOps[i] = Sources[i].ShuffleVec;
6068
6069 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006070 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006071 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6072
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006073 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6074 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006075
6076 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006077}
6078
6079// check if an EXT instruction can handle the shuffle mask when the
6080// vector sources of the shuffle are the same.
6081static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6082 unsigned NumElts = VT.getVectorNumElements();
6083
6084 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6085 if (M[0] < 0)
6086 return false;
6087
6088 Imm = M[0];
6089
6090 // If this is a VEXT shuffle, the immediate value is the index of the first
6091 // element. The other shuffle indices must be the successive elements after
6092 // the first one.
6093 unsigned ExpectedElt = Imm;
6094 for (unsigned i = 1; i < NumElts; ++i) {
6095 // Increment the expected index. If it wraps around, just follow it
6096 // back to index zero and keep going.
6097 ++ExpectedElt;
6098 if (ExpectedElt == NumElts)
6099 ExpectedElt = 0;
6100
6101 if (M[i] < 0)
6102 continue; // ignore UNDEF indices
6103 if (ExpectedElt != static_cast<unsigned>(M[i]))
6104 return false;
6105 }
6106
6107 return true;
6108}
6109
6110// check if an EXT instruction can handle the shuffle mask when the
6111// vector sources of the shuffle are different.
6112static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6113 unsigned &Imm) {
6114 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006115 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006116
6117 // Benefit form APInt to handle overflow when calculating expected element.
6118 unsigned NumElts = VT.getVectorNumElements();
6119 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6120 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6121 // The following shuffle indices must be the successive elements after the
6122 // first real element.
6123 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6124 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6125 if (FirstWrongElt != M.end())
6126 return false;
6127
6128 // The index of an EXT is the first element if it is not UNDEF.
6129 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006130 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006131 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6132 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6133 // ExpectedElt is the last mask index plus 1.
6134 Imm = ExpectedElt.getZExtValue();
6135
6136 // There are two difference cases requiring to reverse input vectors.
6137 // For example, for vector <4 x i32> we have the following cases,
6138 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6139 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6140 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6141 // to reverse two input vectors.
6142 if (Imm < NumElts)
6143 ReverseEXT = true;
6144 else
6145 Imm -= NumElts;
6146
6147 return true;
6148}
6149
6150/// isREVMask - Check if a vector shuffle corresponds to a REV
6151/// instruction with the specified blocksize. (The order of the elements
6152/// within each block of the vector is reversed.)
6153static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6154 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6155 "Only possible block sizes for REV are: 16, 32, 64");
6156
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006157 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006158 if (EltSz == 64)
6159 return false;
6160
6161 unsigned NumElts = VT.getVectorNumElements();
6162 unsigned BlockElts = M[0] + 1;
6163 // If the first shuffle index is UNDEF, be optimistic.
6164 if (M[0] < 0)
6165 BlockElts = BlockSize / EltSz;
6166
6167 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6168 return false;
6169
6170 for (unsigned i = 0; i < NumElts; ++i) {
6171 if (M[i] < 0)
6172 continue; // ignore UNDEF indices
6173 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6174 return false;
6175 }
6176
6177 return true;
6178}
6179
6180static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6181 unsigned NumElts = VT.getVectorNumElements();
6182 WhichResult = (M[0] == 0 ? 0 : 1);
6183 unsigned Idx = WhichResult * NumElts / 2;
6184 for (unsigned i = 0; i != NumElts; i += 2) {
6185 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6186 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6187 return false;
6188 Idx += 1;
6189 }
6190
6191 return true;
6192}
6193
6194static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6195 unsigned NumElts = VT.getVectorNumElements();
6196 WhichResult = (M[0] == 0 ? 0 : 1);
6197 for (unsigned i = 0; i != NumElts; ++i) {
6198 if (M[i] < 0)
6199 continue; // ignore UNDEF indices
6200 if ((unsigned)M[i] != 2 * i + WhichResult)
6201 return false;
6202 }
6203
6204 return true;
6205}
6206
6207static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6208 unsigned NumElts = VT.getVectorNumElements();
6209 WhichResult = (M[0] == 0 ? 0 : 1);
6210 for (unsigned i = 0; i < NumElts; i += 2) {
6211 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6212 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6213 return false;
6214 }
6215 return true;
6216}
6217
6218/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6219/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6220/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6221static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6222 unsigned NumElts = VT.getVectorNumElements();
6223 WhichResult = (M[0] == 0 ? 0 : 1);
6224 unsigned Idx = WhichResult * NumElts / 2;
6225 for (unsigned i = 0; i != NumElts; i += 2) {
6226 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6227 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6228 return false;
6229 Idx += 1;
6230 }
6231
6232 return true;
6233}
6234
6235/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6236/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6237/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6238static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6239 unsigned Half = VT.getVectorNumElements() / 2;
6240 WhichResult = (M[0] == 0 ? 0 : 1);
6241 for (unsigned j = 0; j != 2; ++j) {
6242 unsigned Idx = WhichResult;
6243 for (unsigned i = 0; i != Half; ++i) {
6244 int MIdx = M[i + j * Half];
6245 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6246 return false;
6247 Idx += 2;
6248 }
6249 }
6250
6251 return true;
6252}
6253
6254/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6255/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6256/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6257static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6258 unsigned NumElts = VT.getVectorNumElements();
6259 WhichResult = (M[0] == 0 ? 0 : 1);
6260 for (unsigned i = 0; i < NumElts; i += 2) {
6261 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6262 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6263 return false;
6264 }
6265 return true;
6266}
6267
6268static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6269 bool &DstIsLeft, int &Anomaly) {
6270 if (M.size() != static_cast<size_t>(NumInputElements))
6271 return false;
6272
6273 int NumLHSMatch = 0, NumRHSMatch = 0;
6274 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6275
6276 for (int i = 0; i < NumInputElements; ++i) {
6277 if (M[i] == -1) {
6278 ++NumLHSMatch;
6279 ++NumRHSMatch;
6280 continue;
6281 }
6282
6283 if (M[i] == i)
6284 ++NumLHSMatch;
6285 else
6286 LastLHSMismatch = i;
6287
6288 if (M[i] == i + NumInputElements)
6289 ++NumRHSMatch;
6290 else
6291 LastRHSMismatch = i;
6292 }
6293
6294 if (NumLHSMatch == NumInputElements - 1) {
6295 DstIsLeft = true;
6296 Anomaly = LastLHSMismatch;
6297 return true;
6298 } else if (NumRHSMatch == NumInputElements - 1) {
6299 DstIsLeft = false;
6300 Anomaly = LastRHSMismatch;
6301 return true;
6302 }
6303
6304 return false;
6305}
6306
6307static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6308 if (VT.getSizeInBits() != 128)
6309 return false;
6310
6311 unsigned NumElts = VT.getVectorNumElements();
6312
6313 for (int I = 0, E = NumElts / 2; I != E; I++) {
6314 if (Mask[I] != I)
6315 return false;
6316 }
6317
6318 int Offset = NumElts / 2;
6319 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6320 if (Mask[I] != I + SplitLHS * Offset)
6321 return false;
6322 }
6323
6324 return true;
6325}
6326
6327static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6328 SDLoc DL(Op);
6329 EVT VT = Op.getValueType();
6330 SDValue V0 = Op.getOperand(0);
6331 SDValue V1 = Op.getOperand(1);
6332 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6333
6334 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6335 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6336 return SDValue();
6337
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006338 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006339
6340 if (!isConcatMask(Mask, VT, SplitV0))
6341 return SDValue();
6342
6343 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6344 VT.getVectorNumElements() / 2);
6345 if (SplitV0) {
6346 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006347 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006348 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006349 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006350 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006351 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006352 }
6353 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6354}
6355
6356/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6357/// the specified operations to build the shuffle.
6358static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6359 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006360 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006361 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6362 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6363 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6364
6365 enum {
6366 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6367 OP_VREV,
6368 OP_VDUP0,
6369 OP_VDUP1,
6370 OP_VDUP2,
6371 OP_VDUP3,
6372 OP_VEXT1,
6373 OP_VEXT2,
6374 OP_VEXT3,
6375 OP_VUZPL, // VUZP, left result
6376 OP_VUZPR, // VUZP, right result
6377 OP_VZIPL, // VZIP, left result
6378 OP_VZIPR, // VZIP, right result
6379 OP_VTRNL, // VTRN, left result
6380 OP_VTRNR // VTRN, right result
6381 };
6382
6383 if (OpNum == OP_COPY) {
6384 if (LHSID == (1 * 9 + 2) * 9 + 3)
6385 return LHS;
6386 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6387 return RHS;
6388 }
6389
6390 SDValue OpLHS, OpRHS;
6391 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6392 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6393 EVT VT = OpLHS.getValueType();
6394
6395 switch (OpNum) {
6396 default:
6397 llvm_unreachable("Unknown shuffle opcode!");
6398 case OP_VREV:
6399 // VREV divides the vector in half and swaps within the half.
6400 if (VT.getVectorElementType() == MVT::i32 ||
6401 VT.getVectorElementType() == MVT::f32)
6402 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6403 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006404 if (VT.getVectorElementType() == MVT::i16 ||
6405 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006406 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6407 // vrev <4 x i8> -> REV16
6408 assert(VT.getVectorElementType() == MVT::i8);
6409 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6410 case OP_VDUP0:
6411 case OP_VDUP1:
6412 case OP_VDUP2:
6413 case OP_VDUP3: {
6414 EVT EltTy = VT.getVectorElementType();
6415 unsigned Opcode;
6416 if (EltTy == MVT::i8)
6417 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006418 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006419 Opcode = AArch64ISD::DUPLANE16;
6420 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6421 Opcode = AArch64ISD::DUPLANE32;
6422 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6423 Opcode = AArch64ISD::DUPLANE64;
6424 else
6425 llvm_unreachable("Invalid vector element type?");
6426
6427 if (VT.getSizeInBits() == 64)
6428 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006429 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006430 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6431 }
6432 case OP_VEXT1:
6433 case OP_VEXT2:
6434 case OP_VEXT3: {
6435 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6436 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006437 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006438 }
6439 case OP_VUZPL:
6440 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6441 OpRHS);
6442 case OP_VUZPR:
6443 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6444 OpRHS);
6445 case OP_VZIPL:
6446 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6447 OpRHS);
6448 case OP_VZIPR:
6449 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6450 OpRHS);
6451 case OP_VTRNL:
6452 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6453 OpRHS);
6454 case OP_VTRNR:
6455 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6456 OpRHS);
6457 }
6458}
6459
6460static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6461 SelectionDAG &DAG) {
6462 // Check to see if we can use the TBL instruction.
6463 SDValue V1 = Op.getOperand(0);
6464 SDValue V2 = Op.getOperand(1);
6465 SDLoc DL(Op);
6466
6467 EVT EltVT = Op.getValueType().getVectorElementType();
6468 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6469
6470 SmallVector<SDValue, 8> TBLMask;
6471 for (int Val : ShuffleMask) {
6472 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6473 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006474 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006475 }
6476 }
6477
6478 MVT IndexVT = MVT::v8i8;
6479 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006480 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006481 IndexVT = MVT::v16i8;
6482 IndexLen = 16;
6483 }
6484
6485 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6486 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6487
6488 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006489 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006490 if (IndexLen == 8)
6491 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6492 Shuffle = DAG.getNode(
6493 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006494 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006495 DAG.getBuildVector(IndexVT, DL,
6496 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006497 } else {
6498 if (IndexLen == 8) {
6499 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6500 Shuffle = DAG.getNode(
6501 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006502 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006503 DAG.getBuildVector(IndexVT, DL,
6504 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006505 } else {
6506 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6507 // cannot currently represent the register constraints on the input
6508 // table registers.
6509 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006510 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6511 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006512 Shuffle = DAG.getNode(
6513 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006514 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6515 V2Cst, DAG.getBuildVector(IndexVT, DL,
6516 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006517 }
6518 }
6519 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6520}
6521
6522static unsigned getDUPLANEOp(EVT EltType) {
6523 if (EltType == MVT::i8)
6524 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006525 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006526 return AArch64ISD::DUPLANE16;
6527 if (EltType == MVT::i32 || EltType == MVT::f32)
6528 return AArch64ISD::DUPLANE32;
6529 if (EltType == MVT::i64 || EltType == MVT::f64)
6530 return AArch64ISD::DUPLANE64;
6531
6532 llvm_unreachable("Invalid vector element type?");
6533}
6534
6535SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6536 SelectionDAG &DAG) const {
6537 SDLoc dl(Op);
6538 EVT VT = Op.getValueType();
6539
6540 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6541
6542 // Convert shuffles that are directly supported on NEON to target-specific
6543 // DAG nodes, instead of keeping them as shuffles and matching them again
6544 // during code selection. This is more efficient and avoids the possibility
6545 // of inconsistencies between legalization and selection.
6546 ArrayRef<int> ShuffleMask = SVN->getMask();
6547
6548 SDValue V1 = Op.getOperand(0);
6549 SDValue V2 = Op.getOperand(1);
6550
Craig Topperbc56e3b2016-06-30 04:38:51 +00006551 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006552 int Lane = SVN->getSplatIndex();
6553 // If this is undef splat, generate it via "just" vdup, if possible.
6554 if (Lane == -1)
6555 Lane = 0;
6556
6557 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6558 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6559 V1.getOperand(0));
6560 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6561 // constant. If so, we can just reference the lane's definition directly.
6562 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6563 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6564 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6565
6566 // Otherwise, duplicate from the lane of the input vector.
6567 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6568
6569 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6570 // to make a vector of the same size as this SHUFFLE. We can ignore the
6571 // extract entirely, and canonicalise the concat using WidenVector.
6572 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6573 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6574 V1 = V1.getOperand(0);
6575 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6576 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6577 Lane -= Idx * VT.getVectorNumElements() / 2;
6578 V1 = WidenVector(V1.getOperand(Idx), DAG);
6579 } else if (VT.getSizeInBits() == 64)
6580 V1 = WidenVector(V1, DAG);
6581
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006582 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006583 }
6584
6585 if (isREVMask(ShuffleMask, VT, 64))
6586 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6587 if (isREVMask(ShuffleMask, VT, 32))
6588 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6589 if (isREVMask(ShuffleMask, VT, 16))
6590 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6591
6592 bool ReverseEXT = false;
6593 unsigned Imm;
6594 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6595 if (ReverseEXT)
6596 std::swap(V1, V2);
6597 Imm *= getExtFactor(V1);
6598 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006599 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006600 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006601 Imm *= getExtFactor(V1);
6602 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006603 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006604 }
6605
6606 unsigned WhichResult;
6607 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6608 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6609 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6610 }
6611 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6612 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6613 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6614 }
6615 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6616 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6617 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6618 }
6619
6620 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6621 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6622 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6623 }
6624 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6625 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6626 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6627 }
6628 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6629 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6630 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6631 }
6632
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006633 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006634 return Concat;
6635
6636 bool DstIsLeft;
6637 int Anomaly;
6638 int NumInputElements = V1.getValueType().getVectorNumElements();
6639 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6640 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006641 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006642
6643 SDValue SrcVec = V1;
6644 int SrcLane = ShuffleMask[Anomaly];
6645 if (SrcLane >= NumInputElements) {
6646 SrcVec = V2;
6647 SrcLane -= VT.getVectorNumElements();
6648 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006649 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006650
6651 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006652
6653 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006654 ScalarVT = MVT::i32;
6655
6656 return DAG.getNode(
6657 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6658 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6659 DstLaneV);
6660 }
6661
6662 // If the shuffle is not directly supported and it has 4 elements, use
6663 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6664 unsigned NumElts = VT.getVectorNumElements();
6665 if (NumElts == 4) {
6666 unsigned PFIndexes[4];
6667 for (unsigned i = 0; i != 4; ++i) {
6668 if (ShuffleMask[i] < 0)
6669 PFIndexes[i] = 8;
6670 else
6671 PFIndexes[i] = ShuffleMask[i];
6672 }
6673
6674 // Compute the index in the perfect shuffle table.
6675 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6676 PFIndexes[2] * 9 + PFIndexes[3];
6677 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6678 unsigned Cost = (PFEntry >> 30);
6679
6680 if (Cost <= 4)
6681 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6682 }
6683
6684 return GenerateTBL(Op, ShuffleMask, DAG);
6685}
6686
6687static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6688 APInt &UndefBits) {
6689 EVT VT = BVN->getValueType(0);
6690 APInt SplatBits, SplatUndef;
6691 unsigned SplatBitSize;
6692 bool HasAnyUndefs;
6693 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6694 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6695
6696 for (unsigned i = 0; i < NumSplats; ++i) {
6697 CnstBits <<= SplatBitSize;
6698 UndefBits <<= SplatBitSize;
6699 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6700 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6701 }
6702
6703 return true;
6704 }
6705
6706 return false;
6707}
6708
Evandro Menezes72f39832018-02-20 20:31:45 +00006709// Try 64-bit splatted SIMD immediate.
6710static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6711 const APInt &Bits) {
6712 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6713 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6714 EVT VT = Op.getValueType();
6715 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6716
6717 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6718 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6719
6720 SDLoc dl(Op);
6721 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6722 DAG.getConstant(Value, dl, MVT::i32));
6723 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6724 }
6725 }
6726
6727 return SDValue();
6728}
6729
6730// Try 32-bit splatted SIMD immediate.
6731static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6732 const APInt &Bits,
6733 const SDValue *LHS = nullptr) {
6734 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6735 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6736 EVT VT = Op.getValueType();
6737 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6738 bool isAdvSIMDModImm = false;
6739 uint64_t Shift;
6740
6741 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6742 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6743 Shift = 0;
6744 }
6745 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6746 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6747 Shift = 8;
6748 }
6749 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6750 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6751 Shift = 16;
6752 }
6753 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6754 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6755 Shift = 24;
6756 }
6757
6758 if (isAdvSIMDModImm) {
6759 SDLoc dl(Op);
6760 SDValue Mov;
6761
6762 if (LHS)
6763 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6764 DAG.getConstant(Value, dl, MVT::i32),
6765 DAG.getConstant(Shift, dl, MVT::i32));
6766 else
6767 Mov = DAG.getNode(NewOp, dl, MovTy,
6768 DAG.getConstant(Value, dl, MVT::i32),
6769 DAG.getConstant(Shift, dl, MVT::i32));
6770
6771 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6772 }
6773 }
6774
6775 return SDValue();
6776}
6777
6778// Try 16-bit splatted SIMD immediate.
6779static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6780 const APInt &Bits,
6781 const SDValue *LHS = nullptr) {
6782 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6783 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6784 EVT VT = Op.getValueType();
6785 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6786 bool isAdvSIMDModImm = false;
6787 uint64_t Shift;
6788
6789 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6790 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6791 Shift = 0;
6792 }
6793 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6794 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6795 Shift = 8;
6796 }
6797
6798 if (isAdvSIMDModImm) {
6799 SDLoc dl(Op);
6800 SDValue Mov;
6801
6802 if (LHS)
6803 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006804 DAG.getConstant(Value, dl, MVT::i32),
6805 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006806 else
6807 Mov = DAG.getNode(NewOp, dl, MovTy,
6808 DAG.getConstant(Value, dl, MVT::i32),
6809 DAG.getConstant(Shift, dl, MVT::i32));
6810
6811 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6812 }
6813 }
6814
6815 return SDValue();
6816}
6817
6818// Try 32-bit splatted SIMD immediate with shifted ones.
6819static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6820 SelectionDAG &DAG, const APInt &Bits) {
6821 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6822 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6823 EVT VT = Op.getValueType();
6824 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6825 bool isAdvSIMDModImm = false;
6826 uint64_t Shift;
6827
6828 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6829 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6830 Shift = 264;
6831 }
6832 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6833 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6834 Shift = 272;
6835 }
6836
6837 if (isAdvSIMDModImm) {
6838 SDLoc dl(Op);
6839 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6840 DAG.getConstant(Value, dl, MVT::i32),
6841 DAG.getConstant(Shift, dl, MVT::i32));
6842 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6843 }
6844 }
6845
6846 return SDValue();
6847}
6848
6849// Try 8-bit splatted SIMD immediate.
6850static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6851 const APInt &Bits) {
6852 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6853 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6854 EVT VT = Op.getValueType();
6855 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6856
6857 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6858 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6859
6860 SDLoc dl(Op);
6861 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6862 DAG.getConstant(Value, dl, MVT::i32));
6863 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6864 }
6865 }
6866
6867 return SDValue();
6868}
6869
6870// Try FP splatted SIMD immediate.
6871static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6872 const APInt &Bits) {
6873 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6874 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6875 EVT VT = Op.getValueType();
6876 bool isWide = (VT.getSizeInBits() == 128);
6877 MVT MovTy;
6878 bool isAdvSIMDModImm = false;
6879
6880 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6881 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6882 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6883 }
6884 else if (isWide &&
6885 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6886 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6887 MovTy = MVT::v2f64;
6888 }
6889
6890 if (isAdvSIMDModImm) {
6891 SDLoc dl(Op);
6892 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6893 DAG.getConstant(Value, dl, MVT::i32));
6894 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6895 }
6896 }
6897
6898 return SDValue();
6899}
6900
Tim Northover3b0846e2014-05-24 12:50:23 +00006901SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6902 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006903 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006904 EVT VT = Op.getValueType();
6905
Evandro Menezes72f39832018-02-20 20:31:45 +00006906 BuildVectorSDNode *BVN =
6907 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6908 if (!BVN) {
6909 // AND commutes, so try swapping the operands.
6910 LHS = Op.getOperand(1);
6911 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6912 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006913 if (!BVN)
6914 return Op;
6915
Evandro Menezes72f39832018-02-20 20:31:45 +00006916 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006917 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006918 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6919 SDValue NewOp;
6920
Tim Northover3b0846e2014-05-24 12:50:23 +00006921 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006922 DefBits = ~DefBits;
6923 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6924 DefBits, &LHS)) ||
6925 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6926 DefBits, &LHS)))
6927 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006928
6929 UndefBits = ~UndefBits;
6930 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6931 UndefBits, &LHS)) ||
6932 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6933 UndefBits, &LHS)))
6934 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006935 }
6936
Evandro Menezes72f39832018-02-20 20:31:45 +00006937 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006938 return Op;
6939}
6940
6941// Specialized code to quickly find if PotentialBVec is a BuildVector that
6942// consists of only the same constant int value, returned in reference arg
6943// ConstVal
6944static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6945 uint64_t &ConstVal) {
6946 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6947 if (!Bvec)
6948 return false;
6949 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6950 if (!FirstElt)
6951 return false;
6952 EVT VT = Bvec->getValueType(0);
6953 unsigned NumElts = VT.getVectorNumElements();
6954 for (unsigned i = 1; i < NumElts; ++i)
6955 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6956 return false;
6957 ConstVal = FirstElt->getZExtValue();
6958 return true;
6959}
6960
6961static unsigned getIntrinsicID(const SDNode *N) {
6962 unsigned Opcode = N->getOpcode();
6963 switch (Opcode) {
6964 default:
6965 return Intrinsic::not_intrinsic;
6966 case ISD::INTRINSIC_WO_CHAIN: {
6967 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6968 if (IID < Intrinsic::num_intrinsics)
6969 return IID;
6970 return Intrinsic::not_intrinsic;
6971 }
6972 }
6973}
6974
6975// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6976// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6977// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6978// Also, logical shift right -> sri, with the same structure.
6979static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6980 EVT VT = N->getValueType(0);
6981
6982 if (!VT.isVector())
6983 return SDValue();
6984
6985 SDLoc DL(N);
6986
6987 // Is the first op an AND?
6988 const SDValue And = N->getOperand(0);
6989 if (And.getOpcode() != ISD::AND)
6990 return SDValue();
6991
6992 // Is the second op an shl or lshr?
6993 SDValue Shift = N->getOperand(1);
6994 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6995 // or AArch64ISD::VLSHR vector, #shift
6996 unsigned ShiftOpc = Shift.getOpcode();
6997 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6998 return SDValue();
6999 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7000
7001 // Is the shift amount constant?
7002 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7003 if (!C2node)
7004 return SDValue();
7005
7006 // Is the and mask vector all constant?
7007 uint64_t C1;
7008 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7009 return SDValue();
7010
7011 // Is C1 == ~C2, taking into account how much one can shift elements of a
7012 // particular size?
7013 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007014 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007015 if (C2 > ElemSizeInBits)
7016 return SDValue();
7017 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7018 if ((C1 & ElemMask) != (~C2 & ElemMask))
7019 return SDValue();
7020
7021 SDValue X = And.getOperand(0);
7022 SDValue Y = Shift.getOperand(0);
7023
7024 unsigned Intrin =
7025 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7026 SDValue ResultSLI =
7027 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007028 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7029 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007030
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007031 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7032 LLVM_DEBUG(N->dump(&DAG));
7033 LLVM_DEBUG(dbgs() << "into: \n");
7034 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007035
7036 ++NumShiftInserts;
7037 return ResultSLI;
7038}
7039
7040SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7041 SelectionDAG &DAG) const {
7042 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7043 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007044 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007045 return Res;
7046 }
7047
Tim Northover3b0846e2014-05-24 12:50:23 +00007048 EVT VT = Op.getValueType();
7049
Evandro Menezescd855f72018-03-05 17:02:47 +00007050 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007051 BuildVectorSDNode *BVN =
7052 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007053 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007054 // OR commutes, so try swapping the operands.
7055 LHS = Op.getOperand(1);
7056 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007057 }
7058 if (!BVN)
7059 return Op;
7060
Evandro Menezes72f39832018-02-20 20:31:45 +00007061 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007062 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007063 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7064 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007065
Evandro Menezes72f39832018-02-20 20:31:45 +00007066 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7067 DefBits, &LHS)) ||
7068 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7069 DefBits, &LHS)))
7070 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007071
7072 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7073 UndefBits, &LHS)) ||
7074 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7075 UndefBits, &LHS)))
7076 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007077 }
7078
Evandro Menezes72f39832018-02-20 20:31:45 +00007079 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007080 return Op;
7081}
7082
Kevin Qin4473c192014-07-07 02:45:40 +00007083// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7084// be truncated to fit element width.
7085static SDValue NormalizeBuildVector(SDValue Op,
7086 SelectionDAG &DAG) {
7087 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007088 SDLoc dl(Op);
7089 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007090 EVT EltTy= VT.getVectorElementType();
7091
7092 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7093 return Op;
7094
7095 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007096 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007097 // For integer vectors, type legalization would have promoted the
7098 // operands already. Otherwise, if Op is a floating-point splat
7099 // (with operands cast to integers), then the only possibilities
7100 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007101 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007102 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007103 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007104 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007105 } else if (Lane.getNode()->isUndef()) {
7106 Lane = DAG.getUNDEF(MVT::i32);
7107 } else {
7108 assert(Lane.getValueType() == MVT::i32 &&
7109 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007110 }
7111 Ops.push_back(Lane);
7112 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007113 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007114}
7115
Evandro Menezescd855f72018-03-05 17:02:47 +00007116static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007117 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007118
Evandro Menezes72f39832018-02-20 20:31:45 +00007119 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007120 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007121 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007122 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007123 SDValue NewOp;
7124 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7125 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7126 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7127 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7128 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7129 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7130 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007131
Evandro Menezes72f39832018-02-20 20:31:45 +00007132 DefBits = ~DefBits;
7133 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7134 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7135 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7136 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007137
Evandro Menezes72f39832018-02-20 20:31:45 +00007138 DefBits = UndefBits;
7139 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7140 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7141 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7142 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7143 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7144 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7145 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007146
Evandro Menezes72f39832018-02-20 20:31:45 +00007147 DefBits = ~UndefBits;
7148 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7149 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7150 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7151 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007152 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007153
Evandro Menezescd855f72018-03-05 17:02:47 +00007154 return SDValue();
7155}
7156
7157SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7158 SelectionDAG &DAG) const {
7159 EVT VT = Op.getValueType();
7160
7161 // Try to build a simple constant vector.
7162 Op = NormalizeBuildVector(Op, DAG);
7163 if (VT.isInteger()) {
7164 // Certain vector constants, used to express things like logical NOT and
7165 // arithmetic NEG, are passed through unmodified. This allows special
7166 // patterns for these operations to match, which will lower these constants
7167 // to whatever is proven necessary.
7168 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7169 if (BVN->isConstant())
7170 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7171 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7172 APInt Val(BitSize,
7173 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7174 if (Val.isNullValue() || Val.isAllOnesValue())
7175 return Op;
7176 }
7177 }
7178
7179 if (SDValue V = ConstantBuildVector(Op, DAG))
7180 return V;
7181
Tim Northover3b0846e2014-05-24 12:50:23 +00007182 // Scan through the operands to find some interesting properties we can
7183 // exploit:
7184 // 1) If only one value is used, we can use a DUP, or
7185 // 2) if only the low element is not undef, we can just insert that, or
7186 // 3) if only one constant value is used (w/ some non-constant lanes),
7187 // we can splat the constant value into the whole vector then fill
7188 // in the non-constant lanes.
7189 // 4) FIXME: If different constant values are used, but we can intelligently
7190 // select the values we'll be overwriting for the non-constant
7191 // lanes such that we can directly materialize the vector
7192 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007193 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007194 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007195 unsigned NumElts = VT.getVectorNumElements();
7196 bool isOnlyLowElement = true;
7197 bool usesOnlyOneValue = true;
7198 bool usesOnlyOneConstantValue = true;
7199 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007200 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007201 unsigned NumConstantLanes = 0;
7202 SDValue Value;
7203 SDValue ConstantValue;
7204 for (unsigned i = 0; i < NumElts; ++i) {
7205 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007206 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7207 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007208 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007209 continue;
7210 if (i > 0)
7211 isOnlyLowElement = false;
7212 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7213 isConstant = false;
7214
7215 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7216 ++NumConstantLanes;
7217 if (!ConstantValue.getNode())
7218 ConstantValue = V;
7219 else if (ConstantValue != V)
7220 usesOnlyOneConstantValue = false;
7221 }
7222
7223 if (!Value.getNode())
7224 Value = V;
7225 else if (V != Value)
7226 usesOnlyOneValue = false;
7227 }
7228
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007229 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007230 LLVM_DEBUG(
7231 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007232 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007233 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007234
John Brawnd6e0ebe2018-11-22 11:45:23 +00007235 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7236 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7237 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7238 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007239 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7240 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007241 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007242 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007243
Sebastian Popc33af712018-03-01 15:47:39 +00007244 if (AllLanesExtractElt) {
7245 SDNode *Vector = nullptr;
7246 bool Even = false;
7247 bool Odd = false;
7248 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7249 // the Odd pattern <1,3,5,...>.
7250 for (unsigned i = 0; i < NumElts; ++i) {
7251 SDValue V = Op.getOperand(i);
7252 const SDNode *N = V.getNode();
7253 if (!isa<ConstantSDNode>(N->getOperand(1)))
7254 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007255 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007256
7257 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007258 if (!Vector) {
7259 Vector = N0.getNode();
7260 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7261 // BUILD_VECTOR.
7262 if (VT.getVectorElementType() !=
7263 N0.getValueType().getVectorElementType())
7264 break;
7265 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007266 Odd = false;
7267 Even = false;
7268 break;
7269 }
7270
7271 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7272 // indices <1,3,5,...>.
7273 uint64_t Val = N->getConstantOperandVal(1);
7274 if (Val == 2 * i) {
7275 Even = true;
7276 continue;
7277 }
7278 if (Val - 1 == 2 * i) {
7279 Odd = true;
7280 continue;
7281 }
7282
7283 // Something does not match: abort.
7284 Odd = false;
7285 Even = false;
7286 break;
7287 }
7288 if (Even || Odd) {
7289 SDValue LHS =
7290 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7291 DAG.getConstant(0, dl, MVT::i64));
7292 SDValue RHS =
7293 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7294 DAG.getConstant(NumElts, dl, MVT::i64));
7295
7296 if (Even && !Odd)
7297 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7298 RHS);
7299 if (Odd && !Even)
7300 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7301 RHS);
7302 }
7303 }
7304
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007305 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007306 // i32 and try again.
7307 if (usesOnlyOneValue) {
7308 if (!isConstant) {
7309 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007310 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007311 LLVM_DEBUG(
7312 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007313 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007314 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007315
7316 // This is actually a DUPLANExx operation, which keeps everything vectory.
7317
Tim Northover3b0846e2014-05-24 12:50:23 +00007318 SDValue Lane = Value.getOperand(1);
7319 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007320 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007321 LLVM_DEBUG(
7322 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7323 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007324 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007325 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007326
7327 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7328 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7329 }
7330
7331 if (VT.getVectorElementType().isFloatingPoint()) {
7332 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007333 EVT EltTy = VT.getVectorElementType();
7334 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7335 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007336 LLVM_DEBUG(
7337 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7338 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007339 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007340 for (unsigned i = 0; i < NumElts; ++i)
7341 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7342 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007343 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007344 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7345 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007346 Val = LowerBUILD_VECTOR(Val, DAG);
7347 if (Val.getNode())
7348 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7349 }
7350 }
7351
7352 // If there was only one constant value used and for more than one lane,
7353 // start by splatting that value, then replace the non-constant lanes. This
7354 // is better than the default, which will perform a separate initialization
7355 // for each lane.
7356 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007357 // Firstly, try to materialize the splat constant.
7358 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7359 Val = ConstantBuildVector(Vec, DAG);
7360 if (!Val) {
7361 // Otherwise, materialize the constant and splat it.
7362 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7363 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7364 }
7365
Tim Northover3b0846e2014-05-24 12:50:23 +00007366 // Now insert the non-constant lanes.
7367 for (unsigned i = 0; i < NumElts; ++i) {
7368 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007369 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007370 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007371 // Note that type legalization likely mucked about with the VT of the
7372 // source operand, so we may have to convert it here before inserting.
7373 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007374 }
7375 return Val;
7376 }
7377
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007378 // This will generate a load from the constant pool.
7379 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007380 LLVM_DEBUG(
7381 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7382 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007383 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007384 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007385
7386 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7387 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007388 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007389 return shuffle;
7390 }
7391
7392 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7393 // know the default expansion would otherwise fall back on something even
7394 // worse. For a vector with one or two non-undef values, that's
7395 // scalar_to_vector for the elements followed by a shuffle (provided the
7396 // shuffle is valid for the target) and materialization element by element
7397 // on the stack followed by a load for everything else.
7398 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007399 LLVM_DEBUG(
7400 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7401 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007402
Tim Northover3b0846e2014-05-24 12:50:23 +00007403 SDValue Vec = DAG.getUNDEF(VT);
7404 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007405 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007406
7407 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007408 // a) Avoid a RMW dependency on the full vector register, and
7409 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007410 // value is already in an S or D register, and we're forced to emit an
7411 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007412 //
7413 // We also allow types like i8 and i16 which are illegal scalar but legal
7414 // vector element types. After type-legalization the inserted value is
7415 // extended (i32) and it is safe to cast them to the vector type by ignoring
7416 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7417 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007418 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007419 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007420 ++i;
7421 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007422 LLVM_DEBUG(if (i < NumElts) dbgs()
7423 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007424 for (; i < NumElts; ++i) {
7425 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007426 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007427 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007428 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007429 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7430 }
7431 return Vec;
7432 }
7433
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007434 LLVM_DEBUG(
7435 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7436 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007437 return SDValue();
7438}
7439
7440SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7441 SelectionDAG &DAG) const {
7442 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7443
Tim Northovere4b8e132014-07-15 10:00:26 +00007444 // Check for non-constant or out of range lane.
7445 EVT VT = Op.getOperand(0).getValueType();
7446 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7447 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007448 return SDValue();
7449
Tim Northover3b0846e2014-05-24 12:50:23 +00007450
7451 // Insertion/extraction are legal for V128 types.
7452 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007453 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7454 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007455 return Op;
7456
7457 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007458 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007459 return SDValue();
7460
7461 // For V64 types, we perform insertion by expanding the value
7462 // to a V128 type and perform the insertion on that.
7463 SDLoc DL(Op);
7464 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7465 EVT WideTy = WideVec.getValueType();
7466
7467 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7468 Op.getOperand(1), Op.getOperand(2));
7469 // Re-narrow the resultant vector.
7470 return NarrowVector(Node, DAG);
7471}
7472
7473SDValue
7474AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7475 SelectionDAG &DAG) const {
7476 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7477
Tim Northovere4b8e132014-07-15 10:00:26 +00007478 // Check for non-constant or out of range lane.
7479 EVT VT = Op.getOperand(0).getValueType();
7480 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7481 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007482 return SDValue();
7483
Tim Northover3b0846e2014-05-24 12:50:23 +00007484
7485 // Insertion/extraction are legal for V128 types.
7486 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007487 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7488 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007489 return Op;
7490
7491 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007492 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007493 return SDValue();
7494
7495 // For V64 types, we perform extraction by expanding the value
7496 // to a V128 type and perform the extraction on that.
7497 SDLoc DL(Op);
7498 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7499 EVT WideTy = WideVec.getValueType();
7500
7501 EVT ExtrTy = WideTy.getVectorElementType();
7502 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7503 ExtrTy = MVT::i32;
7504
7505 // For extractions, we just return the result directly.
7506 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7507 Op.getOperand(1));
7508}
7509
7510SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7511 SelectionDAG &DAG) const {
7512 EVT VT = Op.getOperand(0).getValueType();
7513 SDLoc dl(Op);
7514 // Just in case...
7515 if (!VT.isVector())
7516 return SDValue();
7517
7518 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7519 if (!Cst)
7520 return SDValue();
7521 unsigned Val = Cst->getZExtValue();
7522
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007523 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007524
7525 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7526 if (Val == 0)
7527 return Op;
7528
Tim Northover3b0846e2014-05-24 12:50:23 +00007529 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7530 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007531 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007532 return Op;
7533
7534 return SDValue();
7535}
7536
Zvi Rackover1b736822017-07-26 08:06:58 +00007537bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007538 if (VT.getVectorNumElements() == 4 &&
7539 (VT.is128BitVector() || VT.is64BitVector())) {
7540 unsigned PFIndexes[4];
7541 for (unsigned i = 0; i != 4; ++i) {
7542 if (M[i] < 0)
7543 PFIndexes[i] = 8;
7544 else
7545 PFIndexes[i] = M[i];
7546 }
7547
7548 // Compute the index in the perfect shuffle table.
7549 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7550 PFIndexes[2] * 9 + PFIndexes[3];
7551 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7552 unsigned Cost = (PFEntry >> 30);
7553
7554 if (Cost <= 4)
7555 return true;
7556 }
7557
7558 bool DummyBool;
7559 int DummyInt;
7560 unsigned DummyUnsigned;
7561
7562 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7563 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7564 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7565 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7566 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7567 isZIPMask(M, VT, DummyUnsigned) ||
7568 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7569 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7570 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7571 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7572 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7573}
7574
7575/// getVShiftImm - Check if this is a valid build_vector for the immediate
7576/// operand of a vector shift operation, where all the elements of the
7577/// build_vector must have the same constant integer value.
7578static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7579 // Ignore bit_converts.
7580 while (Op.getOpcode() == ISD::BITCAST)
7581 Op = Op.getOperand(0);
7582 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7583 APInt SplatBits, SplatUndef;
7584 unsigned SplatBitSize;
7585 bool HasAnyUndefs;
7586 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7587 HasAnyUndefs, ElementBits) ||
7588 SplatBitSize > ElementBits)
7589 return false;
7590 Cnt = SplatBits.getSExtValue();
7591 return true;
7592}
7593
7594/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7595/// operand of a vector shift left operation. That value must be in the range:
7596/// 0 <= Value < ElementBits for a left shift; or
7597/// 0 <= Value <= ElementBits for a long left shift.
7598static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7599 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007600 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007601 if (!getVShiftImm(Op, ElementBits, Cnt))
7602 return false;
7603 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7604}
7605
7606/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007607/// operand of a vector shift right operation. The value must be in the range:
7608/// 1 <= Value <= ElementBits for a right shift; or
7609static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007610 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007611 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007612 if (!getVShiftImm(Op, ElementBits, Cnt))
7613 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007614 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7615}
7616
7617SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7618 SelectionDAG &DAG) const {
7619 EVT VT = Op.getValueType();
7620 SDLoc DL(Op);
7621 int64_t Cnt;
7622
7623 if (!Op.getOperand(1).getValueType().isVector())
7624 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007625 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007626
7627 switch (Op.getOpcode()) {
7628 default:
7629 llvm_unreachable("unexpected shift opcode");
7630
7631 case ISD::SHL:
7632 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007633 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7634 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007635 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007636 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7637 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007638 Op.getOperand(0), Op.getOperand(1));
7639 case ISD::SRA:
7640 case ISD::SRL:
7641 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007642 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007643 unsigned Opc =
7644 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007645 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7646 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007647 }
7648
7649 // Right shift register. Note, there is not a shift right register
7650 // instruction, but the shift left register instruction takes a signed
7651 // value, where negative numbers specify a right shift.
7652 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7653 : Intrinsic::aarch64_neon_ushl;
7654 // negate the shift amount
7655 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7656 SDValue NegShiftLeft =
7657 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007658 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7659 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007660 return NegShiftLeft;
7661 }
7662
7663 return SDValue();
7664}
7665
7666static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7667 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007668 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007669 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007670 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7671 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007672
7673 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7674 APInt CnstBits(VT.getSizeInBits(), 0);
7675 APInt UndefBits(VT.getSizeInBits(), 0);
7676 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7677 bool IsZero = IsCnst && (CnstBits == 0);
7678
7679 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7680 switch (CC) {
7681 default:
7682 return SDValue();
7683 case AArch64CC::NE: {
7684 SDValue Fcmeq;
7685 if (IsZero)
7686 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7687 else
7688 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7689 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7690 }
7691 case AArch64CC::EQ:
7692 if (IsZero)
7693 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7694 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7695 case AArch64CC::GE:
7696 if (IsZero)
7697 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7698 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7699 case AArch64CC::GT:
7700 if (IsZero)
7701 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7702 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7703 case AArch64CC::LS:
7704 if (IsZero)
7705 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7706 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7707 case AArch64CC::LT:
7708 if (!NoNans)
7709 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007710 // If we ignore NaNs then we can use to the MI implementation.
7711 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007712 case AArch64CC::MI:
7713 if (IsZero)
7714 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7715 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7716 }
7717 }
7718
7719 switch (CC) {
7720 default:
7721 return SDValue();
7722 case AArch64CC::NE: {
7723 SDValue Cmeq;
7724 if (IsZero)
7725 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7726 else
7727 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7728 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7729 }
7730 case AArch64CC::EQ:
7731 if (IsZero)
7732 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7733 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7734 case AArch64CC::GE:
7735 if (IsZero)
7736 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7737 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7738 case AArch64CC::GT:
7739 if (IsZero)
7740 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7741 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7742 case AArch64CC::LE:
7743 if (IsZero)
7744 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7745 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7746 case AArch64CC::LS:
7747 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7748 case AArch64CC::LO:
7749 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7750 case AArch64CC::LT:
7751 if (IsZero)
7752 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7753 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7754 case AArch64CC::HI:
7755 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7756 case AArch64CC::HS:
7757 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7758 }
7759}
7760
7761SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7762 SelectionDAG &DAG) const {
7763 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7764 SDValue LHS = Op.getOperand(0);
7765 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007766 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007767 SDLoc dl(Op);
7768
7769 if (LHS.getValueType().getVectorElementType().isInteger()) {
7770 assert(LHS.getValueType() == RHS.getValueType());
7771 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007772 SDValue Cmp =
7773 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7774 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007775 }
7776
Carey Williamsda15b5b2018-01-22 14:16:11 +00007777 const bool FullFP16 =
7778 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7779
7780 // Make v4f16 (only) fcmp operations utilise vector instructions
7781 // v8f16 support will be a litle more complicated
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007782 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7783 if (LHS.getValueType().getVectorNumElements() == 4) {
Carey Williamsda15b5b2018-01-22 14:16:11 +00007784 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7785 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7786 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7787 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7788 CmpVT = MVT::v4i32;
7789 } else
7790 return SDValue();
7791 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007792
Abderrazek Zaafrani2fc498a2019-02-28 00:31:38 +00007793 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7794 LHS.getValueType().getVectorElementType() != MVT::f128);
Tim Northover3b0846e2014-05-24 12:50:23 +00007795
7796 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7797 // clean. Some of them require two branches to implement.
7798 AArch64CC::CondCode CC1, CC2;
7799 bool ShouldInvert;
7800 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7801
7802 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7803 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007804 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007805 if (!Cmp.getNode())
7806 return SDValue();
7807
7808 if (CC2 != AArch64CC::AL) {
7809 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007810 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007811 if (!Cmp2.getNode())
7812 return SDValue();
7813
Tim Northover45aa89c2015-02-08 00:50:47 +00007814 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007815 }
7816
Tim Northover45aa89c2015-02-08 00:50:47 +00007817 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7818
Tim Northover3b0846e2014-05-24 12:50:23 +00007819 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007820 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007821
7822 return Cmp;
7823}
7824
Amara Emersonc9916d72017-05-16 21:29:22 +00007825static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7826 SelectionDAG &DAG) {
7827 SDValue VecOp = ScalarOp.getOperand(0);
7828 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7829 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7830 DAG.getConstant(0, DL, MVT::i64));
7831}
7832
7833SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7834 SelectionDAG &DAG) const {
7835 SDLoc dl(Op);
7836 switch (Op.getOpcode()) {
7837 case ISD::VECREDUCE_ADD:
7838 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7839 case ISD::VECREDUCE_SMAX:
7840 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7841 case ISD::VECREDUCE_SMIN:
7842 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7843 case ISD::VECREDUCE_UMAX:
7844 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7845 case ISD::VECREDUCE_UMIN:
7846 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7847 case ISD::VECREDUCE_FMAX: {
7848 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7849 return DAG.getNode(
7850 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7851 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7852 Op.getOperand(0));
7853 }
7854 case ISD::VECREDUCE_FMIN: {
7855 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7856 return DAG.getNode(
7857 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7858 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7859 Op.getOperand(0));
7860 }
7861 default:
7862 llvm_unreachable("Unhandled reduction");
7863 }
7864}
7865
Oliver Stannard42699172018-02-12 14:22:03 +00007866SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7867 SelectionDAG &DAG) const {
7868 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7869 if (!Subtarget.hasLSE())
7870 return SDValue();
7871
7872 // LSE has an atomic load-add instruction, but not a load-sub.
7873 SDLoc dl(Op);
7874 MVT VT = Op.getSimpleValueType();
7875 SDValue RHS = Op.getOperand(2);
7876 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7877 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7878 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7879 Op.getOperand(0), Op.getOperand(1), RHS,
7880 AN->getMemOperand());
7881}
7882
Oliver Stannard02f08c92018-02-12 17:03:11 +00007883SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7884 SelectionDAG &DAG) const {
7885 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7886 if (!Subtarget.hasLSE())
7887 return SDValue();
7888
7889 // LSE has an atomic load-clear instruction, but not a load-and.
7890 SDLoc dl(Op);
7891 MVT VT = Op.getSimpleValueType();
7892 SDValue RHS = Op.getOperand(2);
7893 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7894 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7895 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7896 Op.getOperand(0), Op.getOperand(1), RHS,
7897 AN->getMemOperand());
7898}
7899
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007900SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7901 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7902 SDLoc dl(Op);
7903 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7904 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7905
Tri Vo6c47c622018-09-22 22:17:50 +00007906 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7907 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7908 if (Subtarget->hasCustomCallingConv())
7909 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007910
7911 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7912 DAG.getConstant(4, dl, MVT::i64));
7913 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7914 Chain =
7915 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7916 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7917 DAG.getRegisterMask(Mask), Chain.getValue(1));
7918 // To match the actual intent better, we should read the output from X15 here
7919 // again (instead of potentially spilling it to the stack), but rereading Size
7920 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7921 // here.
7922
7923 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7924 DAG.getConstant(4, dl, MVT::i64));
7925 return Chain;
7926}
7927
7928SDValue
7929AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7930 SelectionDAG &DAG) const {
7931 assert(Subtarget->isTargetWindows() &&
7932 "Only Windows alloca probing supported");
7933 SDLoc dl(Op);
7934 // Get the inputs.
7935 SDNode *Node = Op.getNode();
7936 SDValue Chain = Op.getOperand(0);
7937 SDValue Size = Op.getOperand(1);
7938 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7939 EVT VT = Node->getValueType(0);
7940
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00007941 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7942 "no-stack-arg-probe")) {
7943 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7944 Chain = SP.getValue(1);
7945 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7946 if (Align)
7947 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7948 DAG.getConstant(-(uint64_t)Align, dl, VT));
7949 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7950 SDValue Ops[2] = {SP, Chain};
7951 return DAG.getMergeValues(Ops, dl);
7952 }
7953
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007954 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7955
7956 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7957
7958 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7959 Chain = SP.getValue(1);
7960 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00007961 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007962 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7963 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00007964 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007965
7966 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7967 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7968
7969 SDValue Ops[2] = {SP, Chain};
7970 return DAG.getMergeValues(Ops, dl);
7971}
7972
Tim Northover3b0846e2014-05-24 12:50:23 +00007973/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7974/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7975/// specified in the intrinsic calls.
7976bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7977 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00007978 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00007979 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007980 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007981 switch (Intrinsic) {
7982 case Intrinsic::aarch64_neon_ld2:
7983 case Intrinsic::aarch64_neon_ld3:
7984 case Intrinsic::aarch64_neon_ld4:
7985 case Intrinsic::aarch64_neon_ld1x2:
7986 case Intrinsic::aarch64_neon_ld1x3:
7987 case Intrinsic::aarch64_neon_ld1x4:
7988 case Intrinsic::aarch64_neon_ld2lane:
7989 case Intrinsic::aarch64_neon_ld3lane:
7990 case Intrinsic::aarch64_neon_ld4lane:
7991 case Intrinsic::aarch64_neon_ld2r:
7992 case Intrinsic::aarch64_neon_ld3r:
7993 case Intrinsic::aarch64_neon_ld4r: {
7994 Info.opc = ISD::INTRINSIC_W_CHAIN;
7995 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007996 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007997 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7998 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7999 Info.offset = 0;
8000 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008001 // volatile loads with NEON intrinsics not supported
8002 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008003 return true;
8004 }
8005 case Intrinsic::aarch64_neon_st2:
8006 case Intrinsic::aarch64_neon_st3:
8007 case Intrinsic::aarch64_neon_st4:
8008 case Intrinsic::aarch64_neon_st1x2:
8009 case Intrinsic::aarch64_neon_st1x3:
8010 case Intrinsic::aarch64_neon_st1x4:
8011 case Intrinsic::aarch64_neon_st2lane:
8012 case Intrinsic::aarch64_neon_st3lane:
8013 case Intrinsic::aarch64_neon_st4lane: {
8014 Info.opc = ISD::INTRINSIC_VOID;
8015 // Conservatively set memVT to the entire set of vectors stored.
8016 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008017 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008018 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8019 if (!ArgTy->isVectorTy())
8020 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008021 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008022 }
8023 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8024 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8025 Info.offset = 0;
8026 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008027 // volatile stores with NEON intrinsics not supported
8028 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008029 return true;
8030 }
8031 case Intrinsic::aarch64_ldaxr:
8032 case Intrinsic::aarch64_ldxr: {
8033 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8034 Info.opc = ISD::INTRINSIC_W_CHAIN;
8035 Info.memVT = MVT::getVT(PtrTy->getElementType());
8036 Info.ptrVal = I.getArgOperand(0);
8037 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008038 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008039 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008040 return true;
8041 }
8042 case Intrinsic::aarch64_stlxr:
8043 case Intrinsic::aarch64_stxr: {
8044 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8045 Info.opc = ISD::INTRINSIC_W_CHAIN;
8046 Info.memVT = MVT::getVT(PtrTy->getElementType());
8047 Info.ptrVal = I.getArgOperand(1);
8048 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008049 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008050 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008051 return true;
8052 }
8053 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008054 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008055 Info.opc = ISD::INTRINSIC_W_CHAIN;
8056 Info.memVT = MVT::i128;
8057 Info.ptrVal = I.getArgOperand(0);
8058 Info.offset = 0;
8059 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008060 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008061 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008062 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008063 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008064 Info.opc = ISD::INTRINSIC_W_CHAIN;
8065 Info.memVT = MVT::i128;
8066 Info.ptrVal = I.getArgOperand(2);
8067 Info.offset = 0;
8068 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008069 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008070 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008071 default:
8072 break;
8073 }
8074
8075 return false;
8076}
8077
John Brawne3b44f92018-03-23 14:47:07 +00008078bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8079 ISD::LoadExtType ExtTy,
8080 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008081 // TODO: This may be worth removing. Check regression tests for diffs.
8082 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8083 return false;
8084
John Brawne3b44f92018-03-23 14:47:07 +00008085 // If we're reducing the load width in order to avoid having to use an extra
8086 // instruction to do extension then it's probably a good idea.
8087 if (ExtTy != ISD::NON_EXTLOAD)
8088 return true;
8089 // Don't reduce load width if it would prevent us from combining a shift into
8090 // the offset.
8091 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8092 assert(Mem);
8093 const SDValue &Base = Mem->getBasePtr();
8094 if (Base.getOpcode() == ISD::ADD &&
8095 Base.getOperand(1).getOpcode() == ISD::SHL &&
8096 Base.getOperand(1).hasOneUse() &&
8097 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8098 // The shift can be combined if it matches the size of the value being
8099 // loaded (and so reducing the width would make it not match).
8100 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8101 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8102 if (ShiftAmount == Log2_32(LoadBytes))
8103 return false;
8104 }
8105 // We have no reason to disallow reducing the load width, so allow it.
8106 return true;
8107}
8108
Tim Northover3b0846e2014-05-24 12:50:23 +00008109// Truncations from 64-bit GPR to 32-bit GPR is free.
8110bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8111 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8112 return false;
8113 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8114 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008115 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008116}
8117bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008118 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008119 return false;
8120 unsigned NumBits1 = VT1.getSizeInBits();
8121 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008122 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008123}
8124
Chad Rosier54390052015-02-23 19:15:16 +00008125/// Check if it is profitable to hoist instruction in then/else to if.
8126/// Not profitable if I and it's user can form a FMA instruction
8127/// because we prefer FMSUB/FMADD.
8128bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8129 if (I->getOpcode() != Instruction::FMul)
8130 return true;
8131
Davide Italiano3e9986f2017-04-18 00:29:54 +00008132 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008133 return true;
8134
8135 Instruction *User = I->user_back();
8136
8137 if (User &&
8138 !(User->getOpcode() == Instruction::FSub ||
8139 User->getOpcode() == Instruction::FAdd))
8140 return true;
8141
8142 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008143 const DataLayout &DL = I->getModule()->getDataLayout();
8144 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008145
Eric Christopher114fa1c2016-02-29 22:50:49 +00008146 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8147 isOperationLegalOrCustom(ISD::FMA, VT) &&
8148 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8149 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008150}
8151
Tim Northover3b0846e2014-05-24 12:50:23 +00008152// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8153// 64-bit GPR.
8154bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8155 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8156 return false;
8157 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8158 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008159 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008160}
8161bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008162 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008163 return false;
8164 unsigned NumBits1 = VT1.getSizeInBits();
8165 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008166 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008167}
8168
8169bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8170 EVT VT1 = Val.getValueType();
8171 if (isZExtFree(VT1, VT2)) {
8172 return true;
8173 }
8174
8175 if (Val.getOpcode() != ISD::LOAD)
8176 return false;
8177
8178 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008179 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8180 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8181 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008182}
8183
Quentin Colombet6843ac42015-03-31 20:52:32 +00008184bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8185 if (isa<FPExtInst>(Ext))
8186 return false;
8187
Haicheng Wu50692a22017-08-01 21:26:45 +00008188 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008189 if (Ext->getType()->isVectorTy())
8190 return false;
8191
8192 for (const Use &U : Ext->uses()) {
8193 // The extension is free if we can fold it with a left shift in an
8194 // addressing mode or an arithmetic operation: add, sub, and cmp.
8195
8196 // Is there a shift?
8197 const Instruction *Instr = cast<Instruction>(U.getUser());
8198
8199 // Is this a constant shift?
8200 switch (Instr->getOpcode()) {
8201 case Instruction::Shl:
8202 if (!isa<ConstantInt>(Instr->getOperand(1)))
8203 return false;
8204 break;
8205 case Instruction::GetElementPtr: {
8206 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008207 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008208 std::advance(GTI, U.getOperandNo()-1);
8209 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008210 // This extension will end up with a shift because of the scaling factor.
8211 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8212 // Get the shift amount based on the scaling factor:
8213 // log2(sizeof(IdxTy)) - log2(8).
8214 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008215 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008216 // Is the constant foldable in the shift of the addressing mode?
8217 // I.e., shift amount is between 1 and 4 inclusive.
8218 if (ShiftAmt == 0 || ShiftAmt > 4)
8219 return false;
8220 break;
8221 }
8222 case Instruction::Trunc:
8223 // Check if this is a noop.
8224 // trunc(sext ty1 to ty2) to ty1.
8225 if (Instr->getType() == Ext->getOperand(0)->getType())
8226 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008227 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008228 default:
8229 return false;
8230 }
8231
8232 // At this point we can use the bfm family, so this extension is free
8233 // for that use.
8234 }
8235 return true;
8236}
8237
Florian Hahn3b251962019-02-05 10:27:40 +00008238/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8239/// or upper half of the vector elements.
8240static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8241 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8242 auto *FullVT = cast<VectorType>(FullV->getType());
8243 auto *HalfVT = cast<VectorType>(HalfV->getType());
8244 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8245 };
8246
8247 auto extractHalf = [](Value *FullV, Value *HalfV) {
8248 auto *FullVT = cast<VectorType>(FullV->getType());
8249 auto *HalfVT = cast<VectorType>(HalfV->getType());
8250 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8251 };
8252
8253 Constant *M1, *M2;
8254 Value *S1Op1, *S2Op1;
8255 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8256 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8257 return false;
8258
8259 // Check that the operands are half as wide as the result and we extract
8260 // half of the elements of the input vectors.
8261 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8262 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8263 return false;
8264
8265 // Check the mask extracts either the lower or upper half of vector
8266 // elements.
8267 int M1Start = -1;
8268 int M2Start = -1;
8269 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8270 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8271 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8272 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8273 return false;
8274
8275 return true;
8276}
8277
8278/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8279/// of the vector elements.
8280static bool areExtractExts(Value *Ext1, Value *Ext2) {
8281 auto areExtDoubled = [](Instruction *Ext) {
8282 return Ext->getType()->getScalarSizeInBits() ==
8283 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8284 };
8285
8286 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8287 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8288 !areExtDoubled(cast<Instruction>(Ext1)) ||
8289 !areExtDoubled(cast<Instruction>(Ext2)))
8290 return false;
8291
8292 return true;
8293}
8294
8295/// Check if sinking \p I's operands to I's basic block is profitable, because
8296/// the operands can be folded into a target instruction, e.g.
8297/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8298bool AArch64TargetLowering::shouldSinkOperands(
8299 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8300 if (!I->getType()->isVectorTy())
8301 return false;
8302
8303 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8304 switch (II->getIntrinsicID()) {
8305 case Intrinsic::aarch64_neon_umull:
8306 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8307 return false;
8308 Ops.push_back(&II->getOperandUse(0));
8309 Ops.push_back(&II->getOperandUse(1));
8310 return true;
8311 default:
8312 return false;
8313 }
8314 }
8315
8316 switch (I->getOpcode()) {
8317 case Instruction::Sub:
8318 case Instruction::Add: {
8319 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8320 return false;
8321
8322 // If the exts' operands extract either the lower or upper elements, we
8323 // can sink them too.
8324 auto Ext1 = cast<Instruction>(I->getOperand(0));
8325 auto Ext2 = cast<Instruction>(I->getOperand(1));
8326 if (areExtractShuffleVectors(Ext1, Ext2)) {
8327 Ops.push_back(&Ext1->getOperandUse(0));
8328 Ops.push_back(&Ext2->getOperandUse(0));
8329 }
8330
8331 Ops.push_back(&I->getOperandUse(0));
8332 Ops.push_back(&I->getOperandUse(1));
8333
8334 return true;
8335 }
8336 default:
8337 return false;
8338 }
8339 return false;
8340}
8341
Tim Northover3b0846e2014-05-24 12:50:23 +00008342bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8343 unsigned &RequiredAligment) const {
8344 if (!LoadedType.isSimple() ||
8345 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8346 return false;
8347 // Cyclone supports unaligned accesses.
8348 RequiredAligment = 0;
8349 unsigned NumBits = LoadedType.getSizeInBits();
8350 return NumBits == 32 || NumBits == 64;
8351}
8352
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008353/// A helper function for determining the number of interleaved accesses we
8354/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008355unsigned
8356AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8357 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008358 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8359}
8360
Geoff Berryb1e87142017-07-14 21:44:12 +00008361MachineMemOperand::Flags
8362AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8363 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8364 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8365 return MOStridedAccess;
8366 return MachineMemOperand::MONone;
8367}
8368
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008369bool AArch64TargetLowering::isLegalInterleavedAccessType(
8370 VectorType *VecTy, const DataLayout &DL) const {
8371
8372 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8373 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8374
8375 // Ensure the number of vector elements is greater than 1.
8376 if (VecTy->getNumElements() < 2)
8377 return false;
8378
8379 // Ensure the element type is legal.
8380 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8381 return false;
8382
8383 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8384 // 128 will be split into multiple interleaved accesses.
8385 return VecSize == 64 || VecSize % 128 == 0;
8386}
8387
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008388/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008389///
8390/// E.g. Lower an interleaved load (Factor = 2):
8391/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8392/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8393/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8394///
8395/// Into:
8396/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8397/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8398/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8399bool AArch64TargetLowering::lowerInterleavedLoad(
8400 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8401 ArrayRef<unsigned> Indices, unsigned Factor) const {
8402 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8403 "Invalid interleave factor");
8404 assert(!Shuffles.empty() && "Empty shufflevector input");
8405 assert(Shuffles.size() == Indices.size() &&
8406 "Unmatched number of shufflevectors and indices");
8407
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008408 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008409
8410 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008411
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008412 // Skip if we do not have NEON and skip illegal vector types. We can
8413 // "legalize" wide vector types into multiple interleaved accesses as long as
8414 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008415 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008416 return false;
8417
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008418 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8419
Hao Liu7ec8ee32015-06-26 02:32:07 +00008420 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8421 // load integer vectors first and then convert to pointer vectors.
8422 Type *EltTy = VecTy->getVectorElementType();
8423 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008424 VecTy =
8425 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008426
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008427 IRBuilder<> Builder(LI);
8428
8429 // The base address of the load.
8430 Value *BaseAddr = LI->getPointerOperand();
8431
8432 if (NumLoads > 1) {
8433 // If we're going to generate more than one load, reset the sub-vector type
8434 // to something legal.
8435 VecTy = VectorType::get(VecTy->getVectorElementType(),
8436 VecTy->getVectorNumElements() / NumLoads);
8437
8438 // We will compute the pointer operand of each load from the original base
8439 // address using GEPs. Cast the base address to a pointer to the scalar
8440 // element type.
8441 BaseAddr = Builder.CreateBitCast(
8442 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8443 LI->getPointerAddressSpace()));
8444 }
8445
Hao Liu7ec8ee32015-06-26 02:32:07 +00008446 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8447 Type *Tys[2] = {VecTy, PtrTy};
8448 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8449 Intrinsic::aarch64_neon_ld3,
8450 Intrinsic::aarch64_neon_ld4};
8451 Function *LdNFunc =
8452 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8453
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008454 // Holds sub-vectors extracted from the load intrinsic return values. The
8455 // sub-vectors are associated with the shufflevector instructions they will
8456 // replace.
8457 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008458
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008459 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008460
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008461 // If we're generating more than one load, compute the base address of
8462 // subsequent loads as an offset from the previous.
8463 if (LoadCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008464 BaseAddr =
8465 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8466 VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008467
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008468 CallInst *LdN = Builder.CreateCall(
8469 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008470
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008471 // Extract and store the sub-vectors returned by the load intrinsic.
8472 for (unsigned i = 0; i < Shuffles.size(); i++) {
8473 ShuffleVectorInst *SVI = Shuffles[i];
8474 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008475
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008476 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8477
8478 // Convert the integer vector to pointer vector if the element is pointer.
8479 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008480 SubVec = Builder.CreateIntToPtr(
8481 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8482 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008483 SubVecs[SVI].push_back(SubVec);
8484 }
8485 }
8486
8487 // Replace uses of the shufflevector instructions with the sub-vectors
8488 // returned by the load intrinsic. If a shufflevector instruction is
8489 // associated with more than one sub-vector, those sub-vectors will be
8490 // concatenated into a single wide vector.
8491 for (ShuffleVectorInst *SVI : Shuffles) {
8492 auto &SubVec = SubVecs[SVI];
8493 auto *WideVec =
8494 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8495 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008496 }
8497
8498 return true;
8499}
8500
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008501/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008502///
8503/// E.g. Lower an interleaved store (Factor = 3):
8504/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008505/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008506/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8507///
8508/// Into:
8509/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8510/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8511/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8512/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8513///
8514/// Note that the new shufflevectors will be removed and we'll only generate one
8515/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008516///
8517/// Example for a more general valid mask (Factor 3). Lower:
8518/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8519/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8520/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8521///
8522/// Into:
8523/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8524/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8525/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8526/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008527bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8528 ShuffleVectorInst *SVI,
8529 unsigned Factor) const {
8530 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8531 "Invalid interleave factor");
8532
8533 VectorType *VecTy = SVI->getType();
8534 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8535 "Invalid interleaved store");
8536
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008537 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008538 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008539 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008540
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008541 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008542
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008543 // Skip if we do not have NEON and skip illegal vector types. We can
8544 // "legalize" wide vector types into multiple interleaved accesses as long as
8545 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008546 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008547 return false;
8548
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008549 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8550
Hao Liu7ec8ee32015-06-26 02:32:07 +00008551 Value *Op0 = SVI->getOperand(0);
8552 Value *Op1 = SVI->getOperand(1);
8553 IRBuilder<> Builder(SI);
8554
8555 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8556 // vectors to integer vectors.
8557 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008558 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008559 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008560
8561 // Convert to the corresponding integer vector.
8562 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8563 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8564 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8565
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008566 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008567 }
8568
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008569 // The base address of the store.
8570 Value *BaseAddr = SI->getPointerOperand();
8571
8572 if (NumStores > 1) {
8573 // If we're going to generate more than one store, reset the lane length
8574 // and sub-vector type to something legal.
8575 LaneLen /= NumStores;
8576 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8577
8578 // We will compute the pointer operand of each store from the original base
8579 // address using GEPs. Cast the base address to a pointer to the scalar
8580 // element type.
8581 BaseAddr = Builder.CreateBitCast(
8582 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8583 SI->getPointerAddressSpace()));
8584 }
8585
8586 auto Mask = SVI->getShuffleMask();
8587
Hao Liu7ec8ee32015-06-26 02:32:07 +00008588 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8589 Type *Tys[2] = {SubVecTy, PtrTy};
8590 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8591 Intrinsic::aarch64_neon_st3,
8592 Intrinsic::aarch64_neon_st4};
8593 Function *StNFunc =
8594 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8595
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008596 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008597
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008598 SmallVector<Value *, 5> Ops;
8599
8600 // Split the shufflevector operands into sub vectors for the new stN call.
8601 for (unsigned i = 0; i < Factor; i++) {
8602 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8603 if (Mask[IdxI] >= 0) {
8604 Ops.push_back(Builder.CreateShuffleVector(
8605 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8606 } else {
8607 unsigned StartMask = 0;
8608 for (unsigned j = 1; j < LaneLen; j++) {
8609 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8610 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8611 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8612 break;
8613 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008614 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008615 // Note: Filling undef gaps with random elements is ok, since
8616 // those elements were being written anyway (with undefs).
8617 // In the case of all undefs we're defaulting to using elems from 0
8618 // Note: StartMask cannot be negative, it's checked in
8619 // isReInterleaveMask
8620 Ops.push_back(Builder.CreateShuffleVector(
8621 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008622 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008623 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008624
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008625 // If we generating more than one store, we compute the base address of
8626 // subsequent stores as an offset from the previous.
8627 if (StoreCount > 0)
James Y Knight77160752019-02-01 20:44:47 +00008628 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8629 BaseAddr, LaneLen * Factor);
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008630
8631 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8632 Builder.CreateCall(StNFunc, Ops);
8633 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008634 return true;
8635}
8636
Tim Northover3b0846e2014-05-24 12:50:23 +00008637static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8638 unsigned AlignCheck) {
8639 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8640 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8641}
8642
8643EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8644 unsigned SrcAlign, bool IsMemset,
8645 bool ZeroMemset,
8646 bool MemcpyStrSrc,
8647 MachineFunction &MF) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008648 const Function &F = MF.getFunction();
JF Bastien29200612018-09-06 16:03:32 +00008649 bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8650 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8651 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8652 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8653 // taken one instruction to materialize the v2i64 zero and one store (with
8654 // restrictive addressing mode). Just do i64 stores.
8655 bool IsSmallMemset = IsMemset && Size < 32;
8656 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8657 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8658 return true;
8659 bool Fast;
8660 return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8661 };
8662
8663 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8664 AlignmentIsAcceptable(MVT::v2i64, 16))
8665 return MVT::v2i64;
8666 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008667 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008668 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008669 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008670 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008671 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008672 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008673}
8674
8675// 12-bit optionally shifted immediates are legal for adds.
8676bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008677 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008678 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8679 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008680 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008681 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008682 // Same encoding for add/sub, just flip the sign.
8683 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008684 bool IsLegal = ((Immed >> 12) == 0 ||
8685 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008686 LLVM_DEBUG(dbgs() << "Is " << Immed
8687 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008688 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008689}
8690
8691// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8692// immediates is the same as for an add or a sub.
8693bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008694 return isLegalAddImmediate(Immed);
8695}
8696
8697/// isLegalAddressingMode - Return true if the addressing mode represented
8698/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008699bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8700 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008701 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008702 // AArch64 has five basic addressing modes:
8703 // reg
8704 // reg + 9-bit signed offset
8705 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8706 // reg1 + reg2
8707 // reg + SIZE_IN_BYTES * reg
8708
8709 // No global is ever allowed as a base.
8710 if (AM.BaseGV)
8711 return false;
8712
8713 // No reg+reg+imm addressing.
8714 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8715 return false;
8716
8717 // check reg + imm case:
8718 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8719 uint64_t NumBytes = 0;
8720 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008721 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008722 NumBytes = NumBits / 8;
8723 if (!isPowerOf2_64(NumBits))
8724 NumBytes = 0;
8725 }
8726
8727 if (!AM.Scale) {
8728 int64_t Offset = AM.BaseOffs;
8729
8730 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008731 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008732 return true;
8733
8734 // 12-bit unsigned offset
8735 unsigned shift = Log2_64(NumBytes);
8736 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8737 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8738 (Offset >> shift) << shift == Offset)
8739 return true;
8740 return false;
8741 }
8742
8743 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8744
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008745 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008746}
8747
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008748bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8749 // Consider splitting large offset of struct or array.
8750 return true;
8751}
8752
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008753int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8754 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008755 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008756 // Scaling factors are not free at all.
8757 // Operands | Rt Latency
8758 // -------------------------------------------
8759 // Rt, [Xn, Xm] | 4
8760 // -------------------------------------------
8761 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8762 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008763 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008764 // Scale represents reg2 * scale, thus account for 1 if
8765 // it is not equal to 0 or 1.
8766 return AM.Scale != 0 && AM.Scale != 1;
8767 return -1;
8768}
8769
8770bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8771 VT = VT.getScalarType();
8772
8773 if (!VT.isSimple())
8774 return false;
8775
8776 switch (VT.getSimpleVT().SimpleTy) {
8777 case MVT::f32:
8778 case MVT::f64:
8779 return true;
8780 default:
8781 break;
8782 }
8783
8784 return false;
8785}
8786
8787const MCPhysReg *
8788AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8789 // LR is a callee-save register, but we must treat it as clobbered by any call
8790 // site. Hence we include LR in the scratch registers, which are in turn added
8791 // as implicit-defs for stackmaps and patchpoints.
8792 static const MCPhysReg ScratchRegs[] = {
8793 AArch64::X16, AArch64::X17, AArch64::LR, 0
8794 };
8795 return ScratchRegs;
8796}
8797
8798bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008799AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8800 CombineLevel Level) const {
8801 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008802 EVT VT = N->getValueType(0);
8803 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8804 // it with shift to let it be lowered to UBFX.
8805 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8806 isa<ConstantSDNode>(N->getOperand(1))) {
8807 uint64_t TruncMask = N->getConstantOperandVal(1);
8808 if (isMask_64(TruncMask) &&
8809 N->getOperand(0).getOpcode() == ISD::SRL &&
8810 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8811 return false;
8812 }
8813 return true;
8814}
8815
8816bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8817 Type *Ty) const {
8818 assert(Ty->isIntegerTy());
8819
8820 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8821 if (BitSize == 0)
8822 return false;
8823
8824 int64_t Val = Imm.getSExtValue();
8825 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8826 return true;
8827
8828 if ((int64_t)Val < 0)
8829 Val = ~Val;
8830 if (BitSize == 32)
8831 Val &= (1LL << 32) - 1;
8832
8833 unsigned LZ = countLeadingZeros((uint64_t)Val);
8834 unsigned Shift = (63 - LZ) / 16;
8835 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008836 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008837}
8838
Sebastian Pop41073e82018-03-06 16:54:55 +00008839bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8840 unsigned Index) const {
8841 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8842 return false;
8843
8844 return (Index == 0 || Index == ResVT.getVectorNumElements());
8845}
8846
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008847/// Turn vector tests of the signbit in the form of:
8848/// xor (sra X, elt_size(X)-1), -1
8849/// into:
8850/// cmge X, X, #0
8851static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8852 const AArch64Subtarget *Subtarget) {
8853 EVT VT = N->getValueType(0);
8854 if (!Subtarget->hasNEON() || !VT.isVector())
8855 return SDValue();
8856
8857 // There must be a shift right algebraic before the xor, and the xor must be a
8858 // 'not' operation.
8859 SDValue Shift = N->getOperand(0);
8860 SDValue Ones = N->getOperand(1);
8861 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8862 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8863 return SDValue();
8864
8865 // The shift should be smearing the sign bit across each vector element.
8866 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8867 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8868 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8869 return SDValue();
8870
8871 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8872}
8873
Tim Northover3b0846e2014-05-24 12:50:23 +00008874// Generate SUBS and CSEL for integer abs.
8875static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8876 EVT VT = N->getValueType(0);
8877
8878 SDValue N0 = N->getOperand(0);
8879 SDValue N1 = N->getOperand(1);
8880 SDLoc DL(N);
8881
8882 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8883 // and change it to SUB and CSEL.
8884 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8885 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8886 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8887 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8888 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008889 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008890 N0.getOperand(0));
8891 // Generate SUBS & CSEL.
8892 SDValue Cmp =
8893 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008894 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008895 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008896 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008897 SDValue(Cmp.getNode(), 1));
8898 }
8899 return SDValue();
8900}
8901
Tim Northover3b0846e2014-05-24 12:50:23 +00008902static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8903 TargetLowering::DAGCombinerInfo &DCI,
8904 const AArch64Subtarget *Subtarget) {
8905 if (DCI.isBeforeLegalizeOps())
8906 return SDValue();
8907
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008908 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8909 return Cmp;
8910
Tim Northover3b0846e2014-05-24 12:50:23 +00008911 return performIntegerAbsCombine(N, DAG);
8912}
8913
Chad Rosier17020f92014-07-23 14:57:52 +00008914SDValue
8915AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8916 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00008917 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008918 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008919 if (isIntDivCheap(N->getValueType(0), Attr))
8920 return SDValue(N,0); // Lower SDIV as SDIV
8921
Chad Rosier17020f92014-07-23 14:57:52 +00008922 // fold (sdiv X, pow2)
8923 EVT VT = N->getValueType(0);
8924 if ((VT != MVT::i32 && VT != MVT::i64) ||
8925 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8926 return SDValue();
8927
8928 SDLoc DL(N);
8929 SDValue N0 = N->getOperand(0);
8930 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008931 SDValue Zero = DAG.getConstant(0, DL, VT);
8932 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008933
8934 // Add (N0 < 0) ? Pow2 - 1 : 0;
8935 SDValue CCVal;
8936 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8937 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8938 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8939
Craig Toppera568a272018-07-30 21:04:34 +00008940 Created.push_back(Cmp.getNode());
8941 Created.push_back(Add.getNode());
8942 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00008943
8944 // Divide by pow2.
8945 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008946 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008947
8948 // If we're dividing by a positive value, we're done. Otherwise, we must
8949 // negate the result.
8950 if (Divisor.isNonNegative())
8951 return SRA;
8952
Craig Toppera568a272018-07-30 21:04:34 +00008953 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008954 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008955}
8956
Tim Northover3b0846e2014-05-24 12:50:23 +00008957static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8958 TargetLowering::DAGCombinerInfo &DCI,
8959 const AArch64Subtarget *Subtarget) {
8960 if (DCI.isBeforeLegalizeOps())
8961 return SDValue();
8962
Chad Rosier31ee8132016-11-11 17:07:37 +00008963 // The below optimizations require a constant RHS.
8964 if (!isa<ConstantSDNode>(N->getOperand(1)))
8965 return SDValue();
8966
8967 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8968 const APInt &ConstValue = C->getAPIntValue();
8969
Tim Northover3b0846e2014-05-24 12:50:23 +00008970 // Multiplication of a power of two plus/minus one can be done more
8971 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8972 // future CPUs have a cheaper MADD instruction, this may need to be
8973 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8974 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008975 // More aggressively, some multiplications N0 * C can be lowered to
8976 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8977 // e.g. 6=3*2=(2+1)*2.
8978 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8979 // which equals to (1+2)*16-(1+2).
8980 SDValue N0 = N->getOperand(0);
8981 // TrailingZeroes is used to test if the mul can be lowered to
8982 // shift+add+shift.
8983 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8984 if (TrailingZeroes) {
8985 // Conservatively do not lower to shift+add+shift if the mul might be
8986 // folded into smul or umul.
8987 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8988 isZeroExtended(N0.getNode(), DAG)))
8989 return SDValue();
8990 // Conservatively do not lower to shift+add+shift if the mul might be
8991 // folded into madd or msub.
8992 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8993 N->use_begin()->getOpcode() == ISD::SUB))
8994 return SDValue();
8995 }
8996 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8997 // and shift+add+shift.
8998 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8999
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009000 unsigned ShiftAmt, AddSubOpc;
9001 // Is the shifted value the LHS operand of the add/sub?
9002 bool ShiftValUseIsN0 = true;
9003 // Do we need to negate the result?
9004 bool NegateResult = false;
9005
Chad Rosier31ee8132016-11-11 17:07:37 +00009006 if (ConstValue.isNonNegative()) {
9007 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00009008 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00009009 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9010 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009011 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00009012 if (SCVMinus1.isPowerOf2()) {
9013 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009014 AddSubOpc = ISD::ADD;
9015 } else if (CVPlus1.isPowerOf2()) {
9016 ShiftAmt = CVPlus1.logBase2();
9017 AddSubOpc = ISD::SUB;
9018 } else
9019 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00009020 } else {
9021 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00009022 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009023 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00009024 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009025 if (CVNegPlus1.isPowerOf2()) {
9026 ShiftAmt = CVNegPlus1.logBase2();
9027 AddSubOpc = ISD::SUB;
9028 ShiftValUseIsN0 = false;
9029 } else if (CVNegMinus1.isPowerOf2()) {
9030 ShiftAmt = CVNegMinus1.logBase2();
9031 AddSubOpc = ISD::ADD;
9032 NegateResult = true;
9033 } else
9034 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009035 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009036
9037 SDLoc DL(N);
9038 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009039 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009040 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9041
9042 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9043 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9044 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00009045 assert(!(NegateResult && TrailingZeroes) &&
9046 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00009047 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00009048 if (NegateResult)
9049 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9050 // Shift the result.
9051 if (TrailingZeroes)
9052 return DAG.getNode(ISD::SHL, DL, VT, Res,
9053 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9054 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00009055}
9056
Jim Grosbachf7502c42014-07-18 00:40:52 +00009057static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9058 SelectionDAG &DAG) {
9059 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9060 // optimize away operation when it's from a constant.
9061 //
9062 // The general transformation is:
9063 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9064 // AND(VECTOR_CMP(x,y), constant2)
9065 // constant2 = UNARYOP(constant)
9066
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009067 // Early exit if this isn't a vector operation, the operand of the
9068 // unary operation isn't a bitwise AND, or if the sizes of the operations
9069 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00009070 EVT VT = N->getValueType(0);
9071 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00009072 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9073 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009074 return SDValue();
9075
Jim Grosbach724e4382014-07-23 20:41:43 +00009076 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00009077 // make the transformation for non-constant splats as well, but it's unclear
9078 // that would be a benefit as it would not eliminate any operations, just
9079 // perform one more step in scalar code before moving to the vector unit.
9080 if (BuildVectorSDNode *BV =
9081 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00009082 // Bail out if the vector isn't a constant.
9083 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00009084 return SDValue();
9085
9086 // Everything checks out. Build up the new and improved node.
9087 SDLoc DL(N);
9088 EVT IntVT = BV->getValueType(0);
9089 // Create a new constant of the appropriate type for the transformed
9090 // DAG.
9091 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9092 // The AND node needs bitcasts to/from an integer vector type around it.
9093 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9094 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9095 N->getOperand(0)->getOperand(0), MaskConst);
9096 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9097 return Res;
9098 }
9099
9100 return SDValue();
9101}
9102
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009103static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9104 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009105 // First try to optimize away the conversion when it's conditionally from
9106 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009107 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009108 return Res;
9109
Tim Northover3b0846e2014-05-24 12:50:23 +00009110 EVT VT = N->getValueType(0);
9111 if (VT != MVT::f32 && VT != MVT::f64)
9112 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009113
Tim Northover3b0846e2014-05-24 12:50:23 +00009114 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009115 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009116 return SDValue();
9117
9118 // If the result of an integer load is only used by an integer-to-float
9119 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009120 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009121 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009122 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009123 // Do not change the width of a volatile load.
9124 !cast<LoadSDNode>(N0)->isVolatile()) {
9125 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9126 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009127 LN0->getPointerInfo(), LN0->getAlignment(),
9128 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009129
9130 // Make sure successors of the original load stay after it by updating them
9131 // to use the new Chain.
9132 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9133
9134 unsigned Opcode =
9135 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9136 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9137 }
9138
9139 return SDValue();
9140}
9141
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009142/// Fold a floating-point multiply by power of two into floating-point to
9143/// fixed-point conversion.
9144static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009145 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009146 const AArch64Subtarget *Subtarget) {
9147 if (!Subtarget->hasNEON())
9148 return SDValue();
9149
9150 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009151 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9152 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009153 return SDValue();
9154
9155 SDValue ConstVec = Op->getOperand(1);
9156 if (!isa<BuildVectorSDNode>(ConstVec))
9157 return SDValue();
9158
9159 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9160 uint32_t FloatBits = FloatTy.getSizeInBits();
9161 if (FloatBits != 32 && FloatBits != 64)
9162 return SDValue();
9163
9164 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9165 uint32_t IntBits = IntTy.getSizeInBits();
9166 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9167 return SDValue();
9168
9169 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9170 if (IntBits > FloatBits)
9171 return SDValue();
9172
9173 BitVector UndefElements;
9174 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9175 int32_t Bits = IntBits == 64 ? 64 : 32;
9176 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9177 if (C == -1 || C == 0 || C > Bits)
9178 return SDValue();
9179
9180 MVT ResTy;
9181 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9182 switch (NumLanes) {
9183 default:
9184 return SDValue();
9185 case 2:
9186 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9187 break;
9188 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009189 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009190 break;
9191 }
9192
Silviu Barangafa00ba32016-08-08 13:13:57 +00009193 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9194 return SDValue();
9195
9196 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9197 "Illegal vector type after legalization");
9198
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009199 SDLoc DL(N);
9200 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9201 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9202 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9203 SDValue FixConv =
9204 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9205 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9206 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9207 // We can handle smaller integers by generating an extra trunc.
9208 if (IntBits < FloatBits)
9209 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9210
9211 return FixConv;
9212}
9213
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009214/// Fold a floating-point divide by power of two into fixed-point to
9215/// floating-point conversion.
9216static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009217 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009218 const AArch64Subtarget *Subtarget) {
9219 if (!Subtarget->hasNEON())
9220 return SDValue();
9221
9222 SDValue Op = N->getOperand(0);
9223 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009224 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9225 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009226 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9227 return SDValue();
9228
9229 SDValue ConstVec = N->getOperand(1);
9230 if (!isa<BuildVectorSDNode>(ConstVec))
9231 return SDValue();
9232
9233 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9234 int32_t IntBits = IntTy.getSizeInBits();
9235 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9236 return SDValue();
9237
9238 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9239 int32_t FloatBits = FloatTy.getSizeInBits();
9240 if (FloatBits != 32 && FloatBits != 64)
9241 return SDValue();
9242
9243 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9244 if (IntBits > FloatBits)
9245 return SDValue();
9246
9247 BitVector UndefElements;
9248 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9249 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9250 if (C == -1 || C == 0 || C > FloatBits)
9251 return SDValue();
9252
9253 MVT ResTy;
9254 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9255 switch (NumLanes) {
9256 default:
9257 return SDValue();
9258 case 2:
9259 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9260 break;
9261 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009262 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009263 break;
9264 }
9265
Tim Northover85cf5642016-08-26 18:52:31 +00009266 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9267 return SDValue();
9268
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009269 SDLoc DL(N);
9270 SDValue ConvInput = Op.getOperand(0);
9271 bool IsSigned = Opc == ISD::SINT_TO_FP;
9272 if (IntBits < FloatBits)
9273 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9274 ResTy, ConvInput);
9275
9276 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9277 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9278 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9279 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9280 DAG.getConstant(C, DL, MVT::i32));
9281}
9282
Tim Northover3b0846e2014-05-24 12:50:23 +00009283/// An EXTR instruction is made up of two shifts, ORed together. This helper
9284/// searches for and classifies those shifts.
9285static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9286 bool &FromHi) {
9287 if (N.getOpcode() == ISD::SHL)
9288 FromHi = false;
9289 else if (N.getOpcode() == ISD::SRL)
9290 FromHi = true;
9291 else
9292 return false;
9293
9294 if (!isa<ConstantSDNode>(N.getOperand(1)))
9295 return false;
9296
9297 ShiftAmount = N->getConstantOperandVal(1);
9298 Src = N->getOperand(0);
9299 return true;
9300}
9301
9302/// EXTR instruction extracts a contiguous chunk of bits from two existing
9303/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009304/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9305/// with an EXTR. Can't quite be done in TableGen because the two immediates
9306/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009307static SDValue tryCombineToEXTR(SDNode *N,
9308 TargetLowering::DAGCombinerInfo &DCI) {
9309 SelectionDAG &DAG = DCI.DAG;
9310 SDLoc DL(N);
9311 EVT VT = N->getValueType(0);
9312
9313 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9314
9315 if (VT != MVT::i32 && VT != MVT::i64)
9316 return SDValue();
9317
9318 SDValue LHS;
9319 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009320 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009321 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9322 return SDValue();
9323
9324 SDValue RHS;
9325 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009326 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009327 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9328 return SDValue();
9329
9330 // If they're both trying to come from the high part of the register, they're
9331 // not really an EXTR.
9332 if (LHSFromHi == RHSFromHi)
9333 return SDValue();
9334
9335 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9336 return SDValue();
9337
9338 if (LHSFromHi) {
9339 std::swap(LHS, RHS);
9340 std::swap(ShiftLHS, ShiftRHS);
9341 }
9342
9343 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009344 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009345}
9346
9347static SDValue tryCombineToBSL(SDNode *N,
9348 TargetLowering::DAGCombinerInfo &DCI) {
9349 EVT VT = N->getValueType(0);
9350 SelectionDAG &DAG = DCI.DAG;
9351 SDLoc DL(N);
9352
9353 if (!VT.isVector())
9354 return SDValue();
9355
9356 SDValue N0 = N->getOperand(0);
9357 if (N0.getOpcode() != ISD::AND)
9358 return SDValue();
9359
9360 SDValue N1 = N->getOperand(1);
9361 if (N1.getOpcode() != ISD::AND)
9362 return SDValue();
9363
9364 // We only have to look for constant vectors here since the general, variable
9365 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009366 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009367 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9368 for (int i = 1; i >= 0; --i)
9369 for (int j = 1; j >= 0; --j) {
9370 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9371 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9372 if (!BVN0 || !BVN1)
9373 continue;
9374
9375 bool FoundMatch = true;
9376 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9377 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9378 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9379 if (!CN0 || !CN1 ||
9380 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9381 FoundMatch = false;
9382 break;
9383 }
9384 }
9385
9386 if (FoundMatch)
9387 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9388 N0->getOperand(1 - i), N1->getOperand(1 - j));
9389 }
9390
9391 return SDValue();
9392}
9393
9394static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9395 const AArch64Subtarget *Subtarget) {
9396 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009397 SelectionDAG &DAG = DCI.DAG;
9398 EVT VT = N->getValueType(0);
9399
9400 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9401 return SDValue();
9402
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009403 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009404 return Res;
9405
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009406 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009407 return Res;
9408
9409 return SDValue();
9410}
9411
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009412static SDValue performSRLCombine(SDNode *N,
9413 TargetLowering::DAGCombinerInfo &DCI) {
9414 SelectionDAG &DAG = DCI.DAG;
9415 EVT VT = N->getValueType(0);
9416 if (VT != MVT::i32 && VT != MVT::i64)
9417 return SDValue();
9418
9419 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9420 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9421 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9422 SDValue N0 = N->getOperand(0);
9423 if (N0.getOpcode() == ISD::BSWAP) {
9424 SDLoc DL(N);
9425 SDValue N1 = N->getOperand(1);
9426 SDValue N00 = N0.getOperand(0);
9427 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9428 uint64_t ShiftAmt = C->getZExtValue();
9429 if (VT == MVT::i32 && ShiftAmt == 16 &&
9430 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9431 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9432 if (VT == MVT::i64 && ShiftAmt == 32 &&
9433 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9434 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9435 }
9436 }
9437 return SDValue();
9438}
9439
Tim Northover3b0846e2014-05-24 12:50:23 +00009440static SDValue performBitcastCombine(SDNode *N,
9441 TargetLowering::DAGCombinerInfo &DCI,
9442 SelectionDAG &DAG) {
9443 // Wait 'til after everything is legalized to try this. That way we have
9444 // legal vector types and such.
9445 if (DCI.isBeforeLegalizeOps())
9446 return SDValue();
9447
9448 // Remove extraneous bitcasts around an extract_subvector.
9449 // For example,
9450 // (v4i16 (bitconvert
9451 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9452 // becomes
9453 // (extract_subvector ((v8i16 ...), (i64 4)))
9454
9455 // Only interested in 64-bit vectors as the ultimate result.
9456 EVT VT = N->getValueType(0);
9457 if (!VT.isVector())
9458 return SDValue();
9459 if (VT.getSimpleVT().getSizeInBits() != 64)
9460 return SDValue();
9461 // Is the operand an extract_subvector starting at the beginning or halfway
9462 // point of the vector? A low half may also come through as an
9463 // EXTRACT_SUBREG, so look for that, too.
9464 SDValue Op0 = N->getOperand(0);
9465 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9466 !(Op0->isMachineOpcode() &&
9467 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9468 return SDValue();
9469 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9470 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9471 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9472 return SDValue();
9473 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9474 if (idx != AArch64::dsub)
9475 return SDValue();
9476 // The dsub reference is equivalent to a lane zero subvector reference.
9477 idx = 0;
9478 }
9479 // Look through the bitcast of the input to the extract.
9480 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9481 return SDValue();
9482 SDValue Source = Op0->getOperand(0)->getOperand(0);
9483 // If the source type has twice the number of elements as our destination
9484 // type, we know this is an extract of the high or low half of the vector.
9485 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009486 if (!SVT.isVector() ||
9487 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009488 return SDValue();
9489
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009490 LLVM_DEBUG(
9491 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009492
9493 // Create the simplified form to just extract the low or high half of the
9494 // vector directly rather than bothering with the bitcasts.
9495 SDLoc dl(N);
9496 unsigned NumElements = VT.getVectorNumElements();
9497 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009498 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009499 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9500 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009501 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009502 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9503 Source, SubReg),
9504 0);
9505 }
9506}
9507
9508static SDValue performConcatVectorsCombine(SDNode *N,
9509 TargetLowering::DAGCombinerInfo &DCI,
9510 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009511 SDLoc dl(N);
9512 EVT VT = N->getValueType(0);
9513 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9514
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009515 // Optimize concat_vectors of truncated vectors, where the intermediate
9516 // type is illegal, to avoid said illegality, e.g.,
9517 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9518 // (v2i16 (truncate (v2i64)))))
9519 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009520 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9521 // (v4i32 (bitcast (v2i64))),
9522 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009523 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9524 // on both input and result type, so we might generate worse code.
9525 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9526 if (N->getNumOperands() == 2 &&
9527 N0->getOpcode() == ISD::TRUNCATE &&
9528 N1->getOpcode() == ISD::TRUNCATE) {
9529 SDValue N00 = N0->getOperand(0);
9530 SDValue N10 = N1->getOperand(0);
9531 EVT N00VT = N00.getValueType();
9532
9533 if (N00VT == N10.getValueType() &&
9534 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9535 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009536 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9537 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9538 for (size_t i = 0; i < Mask.size(); ++i)
9539 Mask[i] = i * 2;
9540 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9541 DAG.getVectorShuffle(
9542 MidVT, dl,
9543 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9544 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009545 }
9546 }
9547
Tim Northover3b0846e2014-05-24 12:50:23 +00009548 // Wait 'til after everything is legalized to try this. That way we have
9549 // legal vector types and such.
9550 if (DCI.isBeforeLegalizeOps())
9551 return SDValue();
9552
Tim Northover3b0846e2014-05-24 12:50:23 +00009553 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9554 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9555 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009556 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009557 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009558 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009559 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009560 }
9561
9562 // Canonicalise concat_vectors so that the right-hand vector has as few
9563 // bit-casts as possible before its real operation. The primary matching
9564 // destination for these operations will be the narrowing "2" instructions,
9565 // which depend on the operation being performed on this right-hand vector.
9566 // For example,
9567 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9568 // becomes
9569 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9570
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009571 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009572 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009573 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009574 MVT RHSTy = RHS.getValueType().getSimpleVT();
9575 // If the RHS is not a vector, this is not the pattern we're looking for.
9576 if (!RHSTy.isVector())
9577 return SDValue();
9578
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009579 LLVM_DEBUG(
9580 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009581
9582 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9583 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009584 return DAG.getNode(ISD::BITCAST, dl, VT,
9585 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9586 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9587 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009588}
9589
9590static SDValue tryCombineFixedPointConvert(SDNode *N,
9591 TargetLowering::DAGCombinerInfo &DCI,
9592 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009593 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009594 // legal vector types and such.
9595 if (DCI.isBeforeLegalizeOps())
9596 return SDValue();
9597 // Transform a scalar conversion of a value from a lane extract into a
9598 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9599 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9600 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9601 //
9602 // The second form interacts better with instruction selection and the
9603 // register allocator to avoid cross-class register copies that aren't
9604 // coalescable due to a lane reference.
9605
9606 // Check the operand and see if it originates from a lane extract.
9607 SDValue Op1 = N->getOperand(1);
9608 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9609 // Yep, no additional predication needed. Perform the transform.
9610 SDValue IID = N->getOperand(0);
9611 SDValue Shift = N->getOperand(2);
9612 SDValue Vec = Op1.getOperand(0);
9613 SDValue Lane = Op1.getOperand(1);
9614 EVT ResTy = N->getValueType(0);
9615 EVT VecResTy;
9616 SDLoc DL(N);
9617
9618 // The vector width should be 128 bits by the time we get here, even
9619 // if it started as 64 bits (the extract_vector handling will have
9620 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009621 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009622 "unexpected vector size on extract_vector_elt!");
9623 if (Vec.getValueType() == MVT::v4i32)
9624 VecResTy = MVT::v4f32;
9625 else if (Vec.getValueType() == MVT::v2i64)
9626 VecResTy = MVT::v2f64;
9627 else
Craig Topper2a30d782014-06-18 05:05:13 +00009628 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009629
9630 SDValue Convert =
9631 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9632 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9633 }
9634 return SDValue();
9635}
9636
9637// AArch64 high-vector "long" operations are formed by performing the non-high
9638// version on an extract_subvector of each operand which gets the high half:
9639//
9640// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9641//
9642// However, there are cases which don't have an extract_high explicitly, but
9643// have another operation that can be made compatible with one for free. For
9644// example:
9645//
9646// (dupv64 scalar) --> (extract_high (dup128 scalar))
9647//
9648// This routine does the actual conversion of such DUPs, once outer routines
9649// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009650// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9651// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009652static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009653 switch (N.getOpcode()) {
9654 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009655 case AArch64ISD::DUPLANE8:
9656 case AArch64ISD::DUPLANE16:
9657 case AArch64ISD::DUPLANE32:
9658 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009659 case AArch64ISD::MOVI:
9660 case AArch64ISD::MOVIshift:
9661 case AArch64ISD::MOVIedit:
9662 case AArch64ISD::MOVImsl:
9663 case AArch64ISD::MVNIshift:
9664 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009665 break;
9666 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009667 // FMOV could be supported, but isn't very useful, as it would only occur
9668 // if you passed a bitcast' floating point immediate to an eligible long
9669 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009670 return SDValue();
9671 }
9672
9673 MVT NarrowTy = N.getSimpleValueType();
9674 if (!NarrowTy.is64BitVector())
9675 return SDValue();
9676
9677 MVT ElementTy = NarrowTy.getVectorElementType();
9678 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009679 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009680
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009681 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009682 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9683 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009684 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009685}
9686
Eli Friedman29c06092019-02-08 00:23:35 +00009687static bool isEssentiallyExtractHighSubvector(SDValue N) {
9688 if (N.getOpcode() == ISD::BITCAST)
9689 N = N.getOperand(0);
9690 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9691 return false;
9692 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9693 N.getOperand(0).getValueType().getVectorNumElements() / 2;
Tim Northover3b0846e2014-05-24 12:50:23 +00009694}
9695
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009696/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009697struct GenericSetCCInfo {
9698 const SDValue *Opnd0;
9699 const SDValue *Opnd1;
9700 ISD::CondCode CC;
9701};
9702
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009703/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009704struct AArch64SetCCInfo {
9705 const SDValue *Cmp;
9706 AArch64CC::CondCode CC;
9707};
9708
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009709/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009710union SetCCInfo {
9711 GenericSetCCInfo Generic;
9712 AArch64SetCCInfo AArch64;
9713};
9714
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009715/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009716/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9717/// GenericSetCCInfo.
9718struct SetCCInfoAndKind {
9719 SetCCInfo Info;
9720 bool IsAArch64;
9721};
9722
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009723/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009724/// an
9725/// AArch64 lowered one.
9726/// \p SetCCInfo is filled accordingly.
9727/// \post SetCCInfo is meanginfull only when this function returns true.
9728/// \return True when Op is a kind of SET_CC operation.
9729static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9730 // If this is a setcc, this is straight forward.
9731 if (Op.getOpcode() == ISD::SETCC) {
9732 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9733 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9734 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9735 SetCCInfo.IsAArch64 = false;
9736 return true;
9737 }
9738 // Otherwise, check if this is a matching csel instruction.
9739 // In other words:
9740 // - csel 1, 0, cc
9741 // - csel 0, 1, !cc
9742 if (Op.getOpcode() != AArch64ISD::CSEL)
9743 return false;
9744 // Set the information about the operands.
9745 // TODO: we want the operands of the Cmp not the csel
9746 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9747 SetCCInfo.IsAArch64 = true;
9748 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9749 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9750
9751 // Check that the operands matches the constraints:
9752 // (1) Both operands must be constants.
9753 // (2) One must be 1 and the other must be 0.
9754 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9755 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9756
9757 // Check (1).
9758 if (!TValue || !FValue)
9759 return false;
9760
9761 // Check (2).
9762 if (!TValue->isOne()) {
9763 // Update the comparison when we are interested in !cc.
9764 std::swap(TValue, FValue);
9765 SetCCInfo.Info.AArch64.CC =
9766 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9767 }
9768 return TValue->isOne() && FValue->isNullValue();
9769}
9770
9771// Returns true if Op is setcc or zext of setcc.
9772static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9773 if (isSetCC(Op, Info))
9774 return true;
9775 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9776 isSetCC(Op->getOperand(0), Info));
9777}
9778
9779// The folding we want to perform is:
9780// (add x, [zext] (setcc cc ...) )
9781// -->
9782// (csel x, (add x, 1), !cc ...)
9783//
9784// The latter will get matched to a CSINC instruction.
9785static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9786 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9787 SDValue LHS = Op->getOperand(0);
9788 SDValue RHS = Op->getOperand(1);
9789 SetCCInfoAndKind InfoAndKind;
9790
9791 // If neither operand is a SET_CC, give up.
9792 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9793 std::swap(LHS, RHS);
9794 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9795 return SDValue();
9796 }
9797
9798 // FIXME: This could be generatized to work for FP comparisons.
9799 EVT CmpVT = InfoAndKind.IsAArch64
9800 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9801 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9802 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9803 return SDValue();
9804
9805 SDValue CCVal;
9806 SDValue Cmp;
9807 SDLoc dl(Op);
9808 if (InfoAndKind.IsAArch64) {
9809 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009810 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9811 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009812 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9813 } else
9814 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9815 *InfoAndKind.Info.Generic.Opnd1,
9816 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9817 CCVal, DAG, dl);
9818
9819 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009820 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009821 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9822}
9823
9824// The basic add/sub long vector instructions have variants with "2" on the end
9825// which act on the high-half of their inputs. They are normally matched by
9826// patterns like:
9827//
9828// (add (zeroext (extract_high LHS)),
9829// (zeroext (extract_high RHS)))
9830// -> uaddl2 vD, vN, vM
9831//
9832// However, if one of the extracts is something like a duplicate, this
9833// instruction can still be used profitably. This function puts the DAG into a
9834// more appropriate form for those patterns to trigger.
9835static SDValue performAddSubLongCombine(SDNode *N,
9836 TargetLowering::DAGCombinerInfo &DCI,
9837 SelectionDAG &DAG) {
9838 if (DCI.isBeforeLegalizeOps())
9839 return SDValue();
9840
9841 MVT VT = N->getSimpleValueType(0);
9842 if (!VT.is128BitVector()) {
9843 if (N->getOpcode() == ISD::ADD)
9844 return performSetccAddFolding(N, DAG);
9845 return SDValue();
9846 }
9847
9848 // Make sure both branches are extended in the same way.
9849 SDValue LHS = N->getOperand(0);
9850 SDValue RHS = N->getOperand(1);
9851 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9852 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9853 LHS.getOpcode() != RHS.getOpcode())
9854 return SDValue();
9855
9856 unsigned ExtType = LHS.getOpcode();
9857
9858 // It's not worth doing if at least one of the inputs isn't already an
9859 // extract, but we don't know which it'll be so we have to try both.
Eli Friedman29c06092019-02-08 00:23:35 +00009860 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009861 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9862 if (!RHS.getNode())
9863 return SDValue();
9864
9865 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
Eli Friedman29c06092019-02-08 00:23:35 +00009866 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009867 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9868 if (!LHS.getNode())
9869 return SDValue();
9870
9871 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9872 }
9873
9874 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9875}
9876
9877// Massage DAGs which we can use the high-half "long" operations on into
9878// something isel will recognize better. E.g.
9879//
9880// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9881// (aarch64_neon_umull (extract_high (v2i64 vec)))
9882// (extract_high (v2i64 (dup128 scalar)))))
9883//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009884static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009885 TargetLowering::DAGCombinerInfo &DCI,
9886 SelectionDAG &DAG) {
9887 if (DCI.isBeforeLegalizeOps())
9888 return SDValue();
9889
Hal Finkelcd8664c2015-12-11 23:11:52 +00009890 SDValue LHS = N->getOperand(1);
9891 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009892 assert(LHS.getValueType().is64BitVector() &&
9893 RHS.getValueType().is64BitVector() &&
9894 "unexpected shape for long operation");
9895
9896 // Either node could be a DUP, but it's not worth doing both of them (you'd
9897 // just as well use the non-high version) so look for a corresponding extract
9898 // operation on the other "wing".
Eli Friedman29c06092019-02-08 00:23:35 +00009899 if (isEssentiallyExtractHighSubvector(LHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009900 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9901 if (!RHS.getNode())
9902 return SDValue();
Eli Friedman29c06092019-02-08 00:23:35 +00009903 } else if (isEssentiallyExtractHighSubvector(RHS)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009904 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9905 if (!LHS.getNode())
9906 return SDValue();
9907 }
9908
Hal Finkelcd8664c2015-12-11 23:11:52 +00009909 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9910 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009911}
9912
9913static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9914 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9915 unsigned ElemBits = ElemTy.getSizeInBits();
9916
9917 int64_t ShiftAmount;
9918 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9919 APInt SplatValue, SplatUndef;
9920 unsigned SplatBitSize;
9921 bool HasAnyUndefs;
9922 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9923 HasAnyUndefs, ElemBits) ||
9924 SplatBitSize != ElemBits)
9925 return SDValue();
9926
9927 ShiftAmount = SplatValue.getSExtValue();
9928 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9929 ShiftAmount = CVN->getSExtValue();
9930 } else
9931 return SDValue();
9932
9933 unsigned Opcode;
9934 bool IsRightShift;
9935 switch (IID) {
9936 default:
9937 llvm_unreachable("Unknown shift intrinsic");
9938 case Intrinsic::aarch64_neon_sqshl:
9939 Opcode = AArch64ISD::SQSHL_I;
9940 IsRightShift = false;
9941 break;
9942 case Intrinsic::aarch64_neon_uqshl:
9943 Opcode = AArch64ISD::UQSHL_I;
9944 IsRightShift = false;
9945 break;
9946 case Intrinsic::aarch64_neon_srshl:
9947 Opcode = AArch64ISD::SRSHR_I;
9948 IsRightShift = true;
9949 break;
9950 case Intrinsic::aarch64_neon_urshl:
9951 Opcode = AArch64ISD::URSHR_I;
9952 IsRightShift = true;
9953 break;
9954 case Intrinsic::aarch64_neon_sqshlu:
9955 Opcode = AArch64ISD::SQSHLU_I;
9956 IsRightShift = false;
9957 break;
9958 }
9959
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009960 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9961 SDLoc dl(N);
9962 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9963 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9964 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9965 SDLoc dl(N);
9966 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9967 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9968 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009969
9970 return SDValue();
9971}
9972
9973// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9974// the intrinsics must be legal and take an i32, this means there's almost
9975// certainly going to be a zext in the DAG which we can eliminate.
9976static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9977 SDValue AndN = N->getOperand(2);
9978 if (AndN.getOpcode() != ISD::AND)
9979 return SDValue();
9980
9981 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9982 if (!CMask || CMask->getZExtValue() != Mask)
9983 return SDValue();
9984
9985 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9986 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9987}
9988
Ahmed Bougachafab58922015-03-10 20:45:38 +00009989static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9990 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009991 SDLoc dl(N);
9992 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9993 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00009994 N->getOperand(1).getSimpleValueType(),
9995 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009996 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00009997}
9998
Tim Northover3b0846e2014-05-24 12:50:23 +00009999static SDValue performIntrinsicCombine(SDNode *N,
10000 TargetLowering::DAGCombinerInfo &DCI,
10001 const AArch64Subtarget *Subtarget) {
10002 SelectionDAG &DAG = DCI.DAG;
10003 unsigned IID = getIntrinsicID(N);
10004 switch (IID) {
10005 default:
10006 break;
10007 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10008 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10009 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +000010010 case Intrinsic::aarch64_neon_saddv:
10011 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10012 case Intrinsic::aarch64_neon_uaddv:
10013 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10014 case Intrinsic::aarch64_neon_sminv:
10015 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10016 case Intrinsic::aarch64_neon_uminv:
10017 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10018 case Intrinsic::aarch64_neon_smaxv:
10019 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10020 case Intrinsic::aarch64_neon_umaxv:
10021 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010022 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +000010023 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010024 N->getOperand(1), N->getOperand(2));
10025 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +000010026 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +000010027 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +000010028 case Intrinsic::aarch64_neon_fmaxnm:
10029 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10030 N->getOperand(1), N->getOperand(2));
10031 case Intrinsic::aarch64_neon_fminnm:
10032 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10033 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010034 case Intrinsic::aarch64_neon_smull:
10035 case Intrinsic::aarch64_neon_umull:
10036 case Intrinsic::aarch64_neon_pmull:
10037 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +000010038 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +000010039 case Intrinsic::aarch64_neon_sqshl:
10040 case Intrinsic::aarch64_neon_uqshl:
10041 case Intrinsic::aarch64_neon_sqshlu:
10042 case Intrinsic::aarch64_neon_srshl:
10043 case Intrinsic::aarch64_neon_urshl:
10044 return tryCombineShiftImm(IID, N, DAG);
10045 case Intrinsic::aarch64_crc32b:
10046 case Intrinsic::aarch64_crc32cb:
10047 return tryCombineCRC32(0xff, N, DAG);
10048 case Intrinsic::aarch64_crc32h:
10049 case Intrinsic::aarch64_crc32ch:
10050 return tryCombineCRC32(0xffff, N, DAG);
10051 }
10052 return SDValue();
10053}
10054
10055static SDValue performExtendCombine(SDNode *N,
10056 TargetLowering::DAGCombinerInfo &DCI,
10057 SelectionDAG &DAG) {
10058 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10059 // we can convert that DUP into another extract_high (of a bigger DUP), which
10060 // helps the backend to decide that an sabdl2 would be useful, saving a real
10061 // extract_high operation.
10062 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +000010063 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010064 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +000010065 unsigned IID = getIntrinsicID(ABDNode);
10066 if (IID == Intrinsic::aarch64_neon_sabd ||
10067 IID == Intrinsic::aarch64_neon_uabd) {
10068 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10069 if (!NewABD.getNode())
10070 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010071
Hal Finkelcd8664c2015-12-11 23:11:52 +000010072 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10073 NewABD);
10074 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010075 }
10076
10077 // This is effectively a custom type legalization for AArch64.
10078 //
10079 // Type legalization will split an extend of a small, legal, type to a larger
10080 // illegal type by first splitting the destination type, often creating
10081 // illegal source types, which then get legalized in isel-confusing ways,
10082 // leading to really terrible codegen. E.g.,
10083 // %result = v8i32 sext v8i8 %value
10084 // becomes
10085 // %losrc = extract_subreg %value, ...
10086 // %hisrc = extract_subreg %value, ...
10087 // %lo = v4i32 sext v4i8 %losrc
10088 // %hi = v4i32 sext v4i8 %hisrc
10089 // Things go rapidly downhill from there.
10090 //
10091 // For AArch64, the [sz]ext vector instructions can only go up one element
10092 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10093 // take two instructions.
10094 //
10095 // This implies that the most efficient way to do the extend from v8i8
10096 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10097 // the normal splitting to happen for the v8i16->v8i32.
10098
10099 // This is pre-legalization to catch some cases where the default
10100 // type legalization will create ill-tempered code.
10101 if (!DCI.isBeforeLegalizeOps())
10102 return SDValue();
10103
10104 // We're only interested in cleaning things up for non-legal vector types
10105 // here. If both the source and destination are legal, things will just
10106 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010107 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010108 EVT ResVT = N->getValueType(0);
10109 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10110 return SDValue();
10111 // If the vector type isn't a simple VT, it's beyond the scope of what
10112 // we're worried about here. Let legalization do its thing and hope for
10113 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010114 SDValue Src = N->getOperand(0);
10115 EVT SrcVT = Src->getValueType(0);
10116 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010117 return SDValue();
10118
Tim Northover3b0846e2014-05-24 12:50:23 +000010119 // If the source VT is a 64-bit vector, we can play games and get the
10120 // better results we want.
10121 if (SrcVT.getSizeInBits() != 64)
10122 return SDValue();
10123
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010124 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010125 unsigned ElementCount = SrcVT.getVectorNumElements();
10126 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10127 SDLoc DL(N);
10128 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10129
10130 // Now split the rest of the operation into two halves, each with a 64
10131 // bit source.
10132 EVT LoVT, HiVT;
10133 SDValue Lo, Hi;
10134 unsigned NumElements = ResVT.getVectorNumElements();
10135 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10136 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10137 ResVT.getVectorElementType(), NumElements / 2);
10138
10139 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10140 LoVT.getVectorNumElements());
10141 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010142 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010143 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010144 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010145 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10146 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10147
10148 // Now combine the parts back together so we still have a single result
10149 // like the combiner expects.
10150 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10151}
10152
Geoff Berry8301c642016-11-16 19:35:19 +000010153static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10154 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010155 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010156 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010157 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010158
10159 // Create scalar stores. This is at least as good as the code sequence for a
10160 // split unaligned store which is a dup.s, ext.b, and two stores.
10161 // Most of the time the three stores should be replaced by store pair
10162 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010163 SDLoc DL(&St);
10164 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010165 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010166
John Brawn3a9c8422017-02-06 18:07:20 +000010167 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010168 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010169 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010170 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010171
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010172 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010173 if (BasePtr->getOpcode() == ISD::ADD &&
10174 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10175 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10176 BasePtr = BasePtr->getOperand(0);
10177 }
10178
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010179 unsigned Offset = EltOffset;
10180 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010181 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010182 SDValue OffsetPtr =
10183 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10184 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010185 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010186 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010187 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010188 Offset += EltOffset;
10189 }
10190 return NewST1;
10191}
10192
Geoff Berry526c5052016-11-14 19:39:04 +000010193/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10194/// load store optimizer pass will merge them to store pair stores. This should
10195/// be better than a movi to create the vector zero followed by a vector store
10196/// if the zero constant is not re-used, since one instructions and one register
10197/// live range will be removed.
10198///
10199/// For example, the final generated code should be:
10200///
10201/// stp xzr, xzr, [x0]
10202///
10203/// instead of:
10204///
10205/// movi v0.2d, #0
10206/// str q0, [x0]
10207///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010208static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10209 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010210 EVT VT = StVal.getValueType();
10211
Geoff Berry8301c642016-11-16 19:35:19 +000010212 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10213 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010214 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010215 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10216 VT.getVectorElementType().getSizeInBits() == 64) ||
10217 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10218 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010219 return SDValue();
10220
10221 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10222 return SDValue();
10223
10224 // If the zero constant has more than one use then the vector store could be
10225 // better since the constant mov will be amortized and stp q instructions
10226 // should be able to be formed.
10227 if (!StVal.hasOneUse())
10228 return SDValue();
10229
Tim Northover964eea72019-01-08 13:30:27 +000010230 // If the store is truncating then it's going down to i16 or smaller, which
10231 // means it can be implemented in a single store anyway.
10232 if (St.isTruncatingStore())
10233 return SDValue();
10234
Geoff Berry526c5052016-11-14 19:39:04 +000010235 // If the immediate offset of the address operand is too large for the stp
10236 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010237 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10238 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010239 if (Offset < -512 || Offset > 504)
10240 return SDValue();
10241 }
10242
10243 for (int I = 0; I < NumVecElts; ++I) {
10244 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010245 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010246 return SDValue();
10247 }
Geoff Berry8301c642016-11-16 19:35:19 +000010248
Geoff Berrybb23df92017-09-21 21:10:06 +000010249 // Use a CopyFromReg WZR/XZR here to prevent
10250 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10251 SDLoc DL(&St);
10252 unsigned ZeroReg;
10253 EVT ZeroVT;
10254 if (VT.getVectorElementType().getSizeInBits() == 32) {
10255 ZeroReg = AArch64::WZR;
10256 ZeroVT = MVT::i32;
10257 } else {
10258 ZeroReg = AArch64::XZR;
10259 ZeroVT = MVT::i64;
10260 }
10261 SDValue SplatVal =
10262 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010263 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010264}
10265
Tim Northover3b0846e2014-05-24 12:50:23 +000010266/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10267/// value. The load store optimizer pass will merge them to store pair stores.
10268/// This has better performance than a splat of the scalar followed by a split
10269/// vector store. Even if the stores are not merged it is four stores vs a dup,
10270/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010271static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10272 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010273 EVT VT = StVal.getValueType();
10274
10275 // Don't replace floating point stores, they possibly won't be transformed to
10276 // stp because of the store pair suppress pass.
10277 if (VT.isFloatingPoint())
10278 return SDValue();
10279
Tim Northover3b0846e2014-05-24 12:50:23 +000010280 // We can express a splat as store pair(s) for 2 or 4 elements.
10281 unsigned NumVecElts = VT.getVectorNumElements();
10282 if (NumVecElts != 4 && NumVecElts != 2)
10283 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010284
Tim Northover964eea72019-01-08 13:30:27 +000010285 // If the store is truncating then it's going down to i16 or smaller, which
10286 // means it can be implemented in a single store anyway.
10287 if (St.isTruncatingStore())
10288 return SDValue();
10289
Tim Northover3b0846e2014-05-24 12:50:23 +000010290 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010291 // Make sure that each of the relevant vector element locations are inserted
10292 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10293 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10294 SDValue SplatVal;
10295 for (unsigned I = 0; I < NumVecElts; ++I) {
10296 // Check for insert vector elements.
10297 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010298 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010299
10300 // Check that same value is inserted at each vector element.
10301 if (I == 0)
10302 SplatVal = StVal.getOperand(1);
10303 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010304 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010305
10306 // Check insert element index.
10307 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10308 if (!CIndex)
10309 return SDValue();
10310 uint64_t IndexVal = CIndex->getZExtValue();
10311 if (IndexVal >= NumVecElts)
10312 return SDValue();
10313 IndexNotInserted.reset(IndexVal);
10314
10315 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010316 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010317 // Check that all vector element locations were inserted to.
10318 if (IndexNotInserted.any())
10319 return SDValue();
10320
Geoff Berry8301c642016-11-16 19:35:19 +000010321 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010322}
10323
Geoff Berry8301c642016-11-16 19:35:19 +000010324static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10325 SelectionDAG &DAG,
10326 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010327
10328 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010329 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010330 return SDValue();
10331
Geoff Berry526c5052016-11-14 19:39:04 +000010332 SDValue StVal = S->getValue();
10333 EVT VT = StVal.getValueType();
10334 if (!VT.isVector())
10335 return SDValue();
10336
10337 // If we get a splat of zeros, convert this vector store to a store of
10338 // scalars. They will be merged into store pairs of xzr thereby removing one
10339 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010340 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010341 return ReplacedZeroSplat;
10342
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010343 // FIXME: The logic for deciding if an unaligned store should be split should
10344 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10345 // a call to that function here.
10346
Matthias Braun651cff42016-06-02 18:03:53 +000010347 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010348 return SDValue();
10349
Sanjay Patel924879a2015-08-04 15:49:57 +000010350 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +000010351 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010352 return SDValue();
10353
Tim Northover3b0846e2014-05-24 12:50:23 +000010354 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10355 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010356 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010357 return SDValue();
10358
10359 // Split unaligned 16B stores. They are terrible for performance.
10360 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10361 // extensions can use this to mark that it does not want splitting to happen
10362 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10363 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10364 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10365 S->getAlignment() <= 2)
10366 return SDValue();
10367
10368 // If we get a splat of a scalar convert this vector store to a store of
10369 // scalars. They will be merged into store pairs thereby removing two
10370 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010371 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010372 return ReplacedSplat;
10373
10374 SDLoc DL(S);
10375 unsigned NumElts = VT.getVectorNumElements() / 2;
10376 // Split VT into two.
10377 EVT HalfVT =
10378 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10379 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010380 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010381 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010382 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010383 SDValue BasePtr = S->getBasePtr();
10384 SDValue NewST1 =
10385 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010386 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010387 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010388 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010389 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010390 S->getPointerInfo(), S->getAlignment(),
10391 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010392}
10393
10394/// Target-specific DAG combine function for post-increment LD1 (lane) and
10395/// post-increment LD1R.
10396static SDValue performPostLD1Combine(SDNode *N,
10397 TargetLowering::DAGCombinerInfo &DCI,
10398 bool IsLaneOp) {
10399 if (DCI.isBeforeLegalizeOps())
10400 return SDValue();
10401
10402 SelectionDAG &DAG = DCI.DAG;
10403 EVT VT = N->getValueType(0);
10404
10405 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10406 SDNode *LD = N->getOperand(LoadIdx).getNode();
10407 // If it is not LOAD, can not do such combine.
10408 if (LD->getOpcode() != ISD::LOAD)
10409 return SDValue();
10410
Geoff Berry60460262018-05-11 16:25:06 +000010411 // The vector lane must be a constant in the LD1LANE opcode.
10412 SDValue Lane;
10413 if (IsLaneOp) {
10414 Lane = N->getOperand(2);
10415 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10416 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10417 return SDValue();
10418 }
10419
Tim Northover3b0846e2014-05-24 12:50:23 +000010420 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10421 EVT MemVT = LoadSDN->getMemoryVT();
10422 // Check if memory operand is the same type as the vector element.
10423 if (MemVT != VT.getVectorElementType())
10424 return SDValue();
10425
10426 // Check if there are other uses. If so, do not combine as it will introduce
10427 // an extra load.
10428 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10429 ++UI) {
10430 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10431 continue;
10432 if (*UI != N)
10433 return SDValue();
10434 }
10435
10436 SDValue Addr = LD->getOperand(1);
10437 SDValue Vector = N->getOperand(0);
10438 // Search for a use of the address operand that is an increment.
10439 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10440 Addr.getNode()->use_end(); UI != UE; ++UI) {
10441 SDNode *User = *UI;
10442 if (User->getOpcode() != ISD::ADD
10443 || UI.getUse().getResNo() != Addr.getResNo())
10444 continue;
10445
Tim Northover3b0846e2014-05-24 12:50:23 +000010446 // If the increment is a constant, it must match the memory ref size.
10447 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10448 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10449 uint32_t IncVal = CInc->getZExtValue();
10450 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10451 if (IncVal != NumBytes)
10452 continue;
10453 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10454 }
10455
Nirav Davee40e2bb2018-09-25 15:30:22 +000010456 // To avoid cycle construction make sure that neither the load nor the add
10457 // are predecessors to each other or the Vector.
10458 SmallPtrSet<const SDNode *, 32> Visited;
10459 SmallVector<const SDNode *, 16> Worklist;
10460 Visited.insert(N);
10461 Worklist.push_back(User);
10462 Worklist.push_back(LD);
10463 Worklist.push_back(Vector.getNode());
10464 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10465 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010466 continue;
10467
Tim Northover3b0846e2014-05-24 12:50:23 +000010468 SmallVector<SDValue, 8> Ops;
10469 Ops.push_back(LD->getOperand(0)); // Chain
10470 if (IsLaneOp) {
10471 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010472 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010473 }
10474 Ops.push_back(Addr);
10475 Ops.push_back(Inc);
10476
10477 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010478 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010479 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10480 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10481 MemVT,
10482 LoadSDN->getMemOperand());
10483
10484 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010485 SDValue NewResults[] = {
10486 SDValue(LD, 0), // The result of load
10487 SDValue(UpdN.getNode(), 2) // Chain
10488 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010489 DCI.CombineTo(LD, NewResults);
10490 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10491 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10492
10493 break;
10494 }
10495 return SDValue();
10496}
10497
Joel Jones7466ccf2017-07-10 22:11:50 +000010498/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010499/// address translation.
10500static bool performTBISimplification(SDValue Addr,
10501 TargetLowering::DAGCombinerInfo &DCI,
10502 SelectionDAG &DAG) {
10503 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010504 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010505 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10506 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010507 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010508 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010509 DCI.CommitTargetLoweringOpt(TLO);
10510 return true;
10511 }
10512 return false;
10513}
10514
10515static SDValue performSTORECombine(SDNode *N,
10516 TargetLowering::DAGCombinerInfo &DCI,
10517 SelectionDAG &DAG,
10518 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010519 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010520 return Split;
10521
10522 if (Subtarget->supportsAddressTopByteIgnored() &&
10523 performTBISimplification(N->getOperand(2), DCI, DAG))
10524 return SDValue(N, 0);
10525
10526 return SDValue();
10527}
10528
Chad Rosier6c36eff2015-09-03 18:13:57 +000010529
Tim Northover3b0846e2014-05-24 12:50:23 +000010530/// Target-specific DAG combine function for NEON load/store intrinsics
10531/// to merge base address updates.
10532static SDValue performNEONPostLDSTCombine(SDNode *N,
10533 TargetLowering::DAGCombinerInfo &DCI,
10534 SelectionDAG &DAG) {
10535 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10536 return SDValue();
10537
10538 unsigned AddrOpIdx = N->getNumOperands() - 1;
10539 SDValue Addr = N->getOperand(AddrOpIdx);
10540
10541 // Search for a use of the address operand that is an increment.
10542 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10543 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10544 SDNode *User = *UI;
10545 if (User->getOpcode() != ISD::ADD ||
10546 UI.getUse().getResNo() != Addr.getResNo())
10547 continue;
10548
10549 // Check that the add is independent of the load/store. Otherwise, folding
10550 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010551 SmallPtrSet<const SDNode *, 32> Visited;
10552 SmallVector<const SDNode *, 16> Worklist;
10553 Visited.insert(Addr.getNode());
10554 Worklist.push_back(N);
10555 Worklist.push_back(User);
10556 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10557 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010558 continue;
10559
10560 // Find the new opcode for the updating load/store.
10561 bool IsStore = false;
10562 bool IsLaneOp = false;
10563 bool IsDupOp = false;
10564 unsigned NewOpc = 0;
10565 unsigned NumVecs = 0;
10566 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10567 switch (IntNo) {
10568 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10569 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10570 NumVecs = 2; break;
10571 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10572 NumVecs = 3; break;
10573 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10574 NumVecs = 4; break;
10575 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10576 NumVecs = 2; IsStore = true; break;
10577 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10578 NumVecs = 3; IsStore = true; break;
10579 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10580 NumVecs = 4; IsStore = true; break;
10581 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10582 NumVecs = 2; break;
10583 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10584 NumVecs = 3; break;
10585 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10586 NumVecs = 4; break;
10587 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10588 NumVecs = 2; IsStore = true; break;
10589 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10590 NumVecs = 3; IsStore = true; break;
10591 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10592 NumVecs = 4; IsStore = true; break;
10593 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10594 NumVecs = 2; IsDupOp = true; break;
10595 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10596 NumVecs = 3; IsDupOp = true; break;
10597 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10598 NumVecs = 4; IsDupOp = true; break;
10599 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10600 NumVecs = 2; IsLaneOp = true; break;
10601 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10602 NumVecs = 3; IsLaneOp = true; break;
10603 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10604 NumVecs = 4; IsLaneOp = true; break;
10605 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10606 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10607 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10608 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10609 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10610 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10611 }
10612
10613 EVT VecTy;
10614 if (IsStore)
10615 VecTy = N->getOperand(2).getValueType();
10616 else
10617 VecTy = N->getValueType(0);
10618
10619 // If the increment is a constant, it must match the memory ref size.
10620 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10621 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10622 uint32_t IncVal = CInc->getZExtValue();
10623 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10624 if (IsLaneOp || IsDupOp)
10625 NumBytes /= VecTy.getVectorNumElements();
10626 if (IncVal != NumBytes)
10627 continue;
10628 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10629 }
10630 SmallVector<SDValue, 8> Ops;
10631 Ops.push_back(N->getOperand(0)); // Incoming chain
10632 // Load lane and store have vector list as input.
10633 if (IsLaneOp || IsStore)
10634 for (unsigned i = 2; i < AddrOpIdx; ++i)
10635 Ops.push_back(N->getOperand(i));
10636 Ops.push_back(Addr); // Base register
10637 Ops.push_back(Inc);
10638
10639 // Return Types.
10640 EVT Tys[6];
10641 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10642 unsigned n;
10643 for (n = 0; n < NumResultVecs; ++n)
10644 Tys[n] = VecTy;
10645 Tys[n++] = MVT::i64; // Type of write back register
10646 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010647 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010648
10649 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10650 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10651 MemInt->getMemoryVT(),
10652 MemInt->getMemOperand());
10653
10654 // Update the uses.
10655 std::vector<SDValue> NewResults;
10656 for (unsigned i = 0; i < NumResultVecs; ++i) {
10657 NewResults.push_back(SDValue(UpdN.getNode(), i));
10658 }
10659 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10660 DCI.CombineTo(N, NewResults);
10661 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10662
10663 break;
10664 }
10665 return SDValue();
10666}
10667
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010668// Checks to see if the value is the prescribed width and returns information
10669// about its extension mode.
10670static
10671bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10672 ExtType = ISD::NON_EXTLOAD;
10673 switch(V.getNode()->getOpcode()) {
10674 default:
10675 return false;
10676 case ISD::LOAD: {
10677 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10678 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10679 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10680 ExtType = LoadNode->getExtensionType();
10681 return true;
10682 }
10683 return false;
10684 }
10685 case ISD::AssertSext: {
10686 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10687 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10688 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10689 ExtType = ISD::SEXTLOAD;
10690 return true;
10691 }
10692 return false;
10693 }
10694 case ISD::AssertZext: {
10695 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10696 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10697 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10698 ExtType = ISD::ZEXTLOAD;
10699 return true;
10700 }
10701 return false;
10702 }
10703 case ISD::Constant:
10704 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010705 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10706 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010707 }
10708 }
10709
10710 return true;
10711}
10712
10713// This function does a whole lot of voodoo to determine if the tests are
10714// equivalent without and with a mask. Essentially what happens is that given a
10715// DAG resembling:
10716//
10717// +-------------+ +-------------+ +-------------+ +-------------+
10718// | Input | | AddConstant | | CompConstant| | CC |
10719// +-------------+ +-------------+ +-------------+ +-------------+
10720// | | | |
10721// V V | +----------+
10722// +-------------+ +----+ | |
10723// | ADD | |0xff| | |
10724// +-------------+ +----+ | |
10725// | | | |
10726// V V | |
10727// +-------------+ | |
10728// | AND | | |
10729// +-------------+ | |
10730// | | |
10731// +-----+ | |
10732// | | |
10733// V V V
10734// +-------------+
10735// | CMP |
10736// +-------------+
10737//
10738// The AND node may be safely removed for some combinations of inputs. In
10739// particular we need to take into account the extension type of the Input,
10740// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10741// width of the input (this can work for any width inputs, the above graph is
10742// specific to 8 bits.
10743//
10744// The specific equations were worked out by generating output tables for each
10745// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10746// problem was simplified by working with 4 bit inputs, which means we only
10747// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10748// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10749// patterns present in both extensions (0,7). For every distinct set of
10750// AddConstant and CompConstants bit patterns we can consider the masked and
10751// unmasked versions to be equivalent if the result of this function is true for
10752// all 16 distinct bit patterns of for the current extension type of Input (w0).
10753//
10754// sub w8, w0, w1
10755// and w10, w8, #0x0f
10756// cmp w8, w2
10757// cset w9, AArch64CC
10758// cmp w10, w2
10759// cset w11, AArch64CC
10760// cmp w9, w11
10761// cset w0, eq
10762// ret
10763//
10764// Since the above function shows when the outputs are equivalent it defines
10765// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10766// would be expensive to run during compiles. The equations below were written
10767// in a test harness that confirmed they gave equivalent outputs to the above
10768// for all inputs function, so they can be used determine if the removal is
10769// legal instead.
10770//
10771// isEquivalentMaskless() is the code for testing if the AND can be removed
10772// factored out of the DAG recognition as the DAG can take several forms.
10773
David Majnemere61e4bf2016-06-21 05:10:24 +000010774static bool isEquivalentMaskless(unsigned CC, unsigned width,
10775 ISD::LoadExtType ExtType, int AddConstant,
10776 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010777 // By being careful about our equations and only writing the in term
10778 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10779 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010780 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010781
10782 // For the purposes of these comparisons sign extending the type is
10783 // equivalent to zero extending the add and displacing it by half the integer
10784 // width. Provided we are careful and make sure our equations are valid over
10785 // the whole range we can just adjust the input and avoid writing equations
10786 // for sign extended inputs.
10787 if (ExtType == ISD::SEXTLOAD)
10788 AddConstant -= (1 << (width-1));
10789
10790 switch(CC) {
10791 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010792 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010793 if ((AddConstant == 0) ||
10794 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10795 (AddConstant >= 0 && CompConstant < 0) ||
10796 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10797 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010798 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010799 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010800 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010801 if ((AddConstant == 0) ||
10802 (AddConstant >= 0 && CompConstant <= 0) ||
10803 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10804 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010805 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010806 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010807 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010808 if ((AddConstant >= 0 && CompConstant < 0) ||
10809 (AddConstant <= 0 && CompConstant >= -1 &&
10810 CompConstant < AddConstant + MaxUInt))
10811 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010812 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010813 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010814 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010815 if ((AddConstant == 0) ||
10816 (AddConstant > 0 && CompConstant <= 0) ||
10817 (AddConstant < 0 && CompConstant <= AddConstant))
10818 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010819 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010820 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010821 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010822 if ((AddConstant >= 0 && CompConstant <= 0) ||
10823 (AddConstant <= 0 && CompConstant >= 0 &&
10824 CompConstant <= AddConstant + MaxUInt))
10825 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010826 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010827 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010828 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010829 if ((AddConstant > 0 && CompConstant < 0) ||
10830 (AddConstant < 0 && CompConstant >= 0 &&
10831 CompConstant < AddConstant + MaxUInt) ||
10832 (AddConstant >= 0 && CompConstant >= 0 &&
10833 CompConstant >= AddConstant) ||
10834 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010835 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010836 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010837 case AArch64CC::VS:
10838 case AArch64CC::VC:
10839 case AArch64CC::AL:
10840 case AArch64CC::NV:
10841 return true;
10842 case AArch64CC::Invalid:
10843 break;
10844 }
10845
10846 return false;
10847}
10848
10849static
10850SDValue performCONDCombine(SDNode *N,
10851 TargetLowering::DAGCombinerInfo &DCI,
10852 SelectionDAG &DAG, unsigned CCIndex,
10853 unsigned CmpIndex) {
10854 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10855 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10856 unsigned CondOpcode = SubsNode->getOpcode();
10857
10858 if (CondOpcode != AArch64ISD::SUBS)
10859 return SDValue();
10860
10861 // There is a SUBS feeding this condition. Is it fed by a mask we can
10862 // use?
10863
10864 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10865 unsigned MaskBits = 0;
10866
10867 if (AndNode->getOpcode() != ISD::AND)
10868 return SDValue();
10869
10870 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10871 uint32_t CNV = CN->getZExtValue();
10872 if (CNV == 255)
10873 MaskBits = 8;
10874 else if (CNV == 65535)
10875 MaskBits = 16;
10876 }
10877
10878 if (!MaskBits)
10879 return SDValue();
10880
10881 SDValue AddValue = AndNode->getOperand(0);
10882
10883 if (AddValue.getOpcode() != ISD::ADD)
10884 return SDValue();
10885
10886 // The basic dag structure is correct, grab the inputs and validate them.
10887
10888 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10889 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10890 SDValue SubsInputValue = SubsNode->getOperand(1);
10891
10892 // The mask is present and the provenance of all the values is a smaller type,
10893 // lets see if the mask is superfluous.
10894
10895 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10896 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10897 return SDValue();
10898
10899 ISD::LoadExtType ExtType;
10900
10901 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10902 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10903 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10904 return SDValue();
10905
10906 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10907 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10908 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10909 return SDValue();
10910
10911 // The AND is not necessary, remove it.
10912
10913 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10914 SubsNode->getValueType(1));
10915 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10916
10917 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10918 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10919
10920 return SDValue(N, 0);
10921}
10922
Tim Northover3b0846e2014-05-24 12:50:23 +000010923// Optimize compare with zero and branch.
10924static SDValue performBRCONDCombine(SDNode *N,
10925 TargetLowering::DAGCombinerInfo &DCI,
10926 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000010927 MachineFunction &MF = DAG.getMachineFunction();
10928 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
10929 // will not be produced, as they are conditional branch instructions that do
10930 // not set flags.
10931 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
10932 return SDValue();
10933
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010934 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010935 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010936 SDValue Chain = N->getOperand(0);
10937 SDValue Dest = N->getOperand(1);
10938 SDValue CCVal = N->getOperand(2);
10939 SDValue Cmp = N->getOperand(3);
10940
10941 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10942 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10943 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10944 return SDValue();
10945
10946 unsigned CmpOpc = Cmp.getOpcode();
10947 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10948 return SDValue();
10949
10950 // Only attempt folding if there is only one use of the flag and no use of the
10951 // value.
10952 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10953 return SDValue();
10954
10955 SDValue LHS = Cmp.getOperand(0);
10956 SDValue RHS = Cmp.getOperand(1);
10957
10958 assert(LHS.getValueType() == RHS.getValueType() &&
10959 "Expected the value type to be the same for both operands!");
10960 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10961 return SDValue();
10962
Artyom Skrobov314ee042015-11-25 19:41:11 +000010963 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010964 std::swap(LHS, RHS);
10965
Artyom Skrobov314ee042015-11-25 19:41:11 +000010966 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010967 return SDValue();
10968
10969 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10970 LHS.getOpcode() == ISD::SRL)
10971 return SDValue();
10972
10973 // Fold the compare into the branch instruction.
10974 SDValue BR;
10975 if (CC == AArch64CC::EQ)
10976 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10977 else
10978 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10979
10980 // Do not add new nodes to DAG combiner worklist.
10981 DCI.CombineTo(N, BR, false);
10982
10983 return SDValue();
10984}
10985
Geoff Berry9e934b02016-01-04 18:55:47 +000010986// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10987// as well as whether the test should be inverted. This code is required to
10988// catch these cases (as opposed to standard dag combines) because
10989// AArch64ISD::TBZ is matched during legalization.
10990static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10991 SelectionDAG &DAG) {
10992
10993 if (!Op->hasOneUse())
10994 return Op;
10995
10996 // We don't handle undef/constant-fold cases below, as they should have
10997 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10998 // etc.)
10999
11000 // (tbz (trunc x), b) -> (tbz x, b)
11001 // This case is just here to enable more of the below cases to be caught.
11002 if (Op->getOpcode() == ISD::TRUNCATE &&
11003 Bit < Op->getValueType(0).getSizeInBits()) {
11004 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11005 }
11006
11007 if (Op->getNumOperands() != 2)
11008 return Op;
11009
11010 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11011 if (!C)
11012 return Op;
11013
11014 switch (Op->getOpcode()) {
11015 default:
11016 return Op;
11017
11018 // (tbz (and x, m), b) -> (tbz x, b)
11019 case ISD::AND:
11020 if ((C->getZExtValue() >> Bit) & 1)
11021 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11022 return Op;
11023
11024 // (tbz (shl x, c), b) -> (tbz x, b-c)
11025 case ISD::SHL:
11026 if (C->getZExtValue() <= Bit &&
11027 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11028 Bit = Bit - C->getZExtValue();
11029 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11030 }
11031 return Op;
11032
11033 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11034 case ISD::SRA:
11035 Bit = Bit + C->getZExtValue();
11036 if (Bit >= Op->getValueType(0).getSizeInBits())
11037 Bit = Op->getValueType(0).getSizeInBits() - 1;
11038 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11039
11040 // (tbz (srl x, c), b) -> (tbz x, b+c)
11041 case ISD::SRL:
11042 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11043 Bit = Bit + C->getZExtValue();
11044 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11045 }
11046 return Op;
11047
11048 // (tbz (xor x, -1), b) -> (tbnz x, b)
11049 case ISD::XOR:
11050 if ((C->getZExtValue() >> Bit) & 1)
11051 Invert = !Invert;
11052 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11053 }
11054}
11055
11056// Optimize test single bit zero/non-zero and branch.
11057static SDValue performTBZCombine(SDNode *N,
11058 TargetLowering::DAGCombinerInfo &DCI,
11059 SelectionDAG &DAG) {
11060 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11061 bool Invert = false;
11062 SDValue TestSrc = N->getOperand(1);
11063 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11064
11065 if (TestSrc == NewTestSrc)
11066 return SDValue();
11067
11068 unsigned NewOpc = N->getOpcode();
11069 if (Invert) {
11070 if (NewOpc == AArch64ISD::TBZ)
11071 NewOpc = AArch64ISD::TBNZ;
11072 else {
11073 assert(NewOpc == AArch64ISD::TBNZ);
11074 NewOpc = AArch64ISD::TBZ;
11075 }
11076 }
11077
11078 SDLoc DL(N);
11079 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11080 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11081}
11082
Tim Northover3b0846e2014-05-24 12:50:23 +000011083// vselect (v1i1 setcc) ->
11084// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11085// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11086// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11087// such VSELECT.
11088static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11089 SDValue N0 = N->getOperand(0);
11090 EVT CCVT = N0.getValueType();
11091
11092 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11093 CCVT.getVectorElementType() != MVT::i1)
11094 return SDValue();
11095
11096 EVT ResVT = N->getValueType(0);
11097 EVT CmpVT = N0.getOperand(0).getValueType();
11098 // Only combine when the result type is of the same size as the compared
11099 // operands.
11100 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11101 return SDValue();
11102
11103 SDValue IfTrue = N->getOperand(1);
11104 SDValue IfFalse = N->getOperand(2);
11105 SDValue SetCC =
11106 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11107 N0.getOperand(0), N0.getOperand(1),
11108 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11109 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11110 IfTrue, IfFalse);
11111}
11112
11113/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11114/// the compare-mask instructions rather than going via NZCV, even if LHS and
11115/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11116/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011117static SDValue performSelectCombine(SDNode *N,
11118 TargetLowering::DAGCombinerInfo &DCI) {
11119 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011120 SDValue N0 = N->getOperand(0);
11121 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011122
Ahmed Bougachac004c602015-04-27 21:43:12 +000011123 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011124 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011125
Ahmed Bougachac004c602015-04-27 21:43:12 +000011126 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11127 // scalar SetCCResultType. We also don't expect vectors, because we assume
11128 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11129 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11130 "Scalar-SETCC feeding SELECT has unexpected result type!");
11131
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011132 // If NumMaskElts == 0, the comparison is larger than select result. The
11133 // largest real NEON comparison is 64-bits per lane, which means the result is
11134 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011135 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011136
11137 // Don't try to do this optimization when the setcc itself has i1 operands.
11138 // There are no legal vectors of i1, so this would be pointless.
11139 if (SrcVT == MVT::i1)
11140 return SDValue();
11141
Tim Northover3c0915e2014-08-29 15:34:58 +000011142 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011143 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011144 return SDValue();
11145
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011146 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011147 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11148
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011149 // Also bail out if the vector CCVT isn't the same size as ResVT.
11150 // This can happen if the SETCC operand size doesn't divide the ResVT size
11151 // (e.g., f64 vs v3f32).
11152 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11153 return SDValue();
11154
Ahmed Bougachac004c602015-04-27 21:43:12 +000011155 // Make sure we didn't create illegal types, if we're not supposed to.
11156 assert(DCI.isBeforeLegalize() ||
11157 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11158
Tim Northover3b0846e2014-05-24 12:50:23 +000011159 // First perform a vector comparison, where lane 0 is the one we're interested
11160 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011161 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011162 SDValue LHS =
11163 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11164 SDValue RHS =
11165 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11166 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11167
11168 // Now duplicate the comparison mask we want across all other lanes.
11169 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011170 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011171 Mask = DAG.getNode(ISD::BITCAST, DL,
11172 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011173
11174 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11175}
11176
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011177/// Get rid of unnecessary NVCASTs (that don't change the type).
11178static SDValue performNVCASTCombine(SDNode *N) {
11179 if (N->getValueType(0) == N->getOperand(0).getValueType())
11180 return N->getOperand(0);
11181
11182 return SDValue();
11183}
11184
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011185// If all users of the globaladdr are of the form (globaladdr + constant), find
11186// the smallest constant, fold it into the globaladdr's offset and rewrite the
11187// globaladdr as (globaladdr + constant) - constant.
11188static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11189 const AArch64Subtarget *Subtarget,
11190 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011191 auto *GN = cast<GlobalAddressSDNode>(N);
11192 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11193 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011194 return SDValue();
11195
11196 uint64_t MinOffset = -1ull;
11197 for (SDNode *N : GN->uses()) {
11198 if (N->getOpcode() != ISD::ADD)
11199 return SDValue();
11200 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11201 if (!C)
11202 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11203 if (!C)
11204 return SDValue();
11205 MinOffset = std::min(MinOffset, C->getZExtValue());
11206 }
11207 uint64_t Offset = MinOffset + GN->getOffset();
11208
11209 // Require that the new offset is larger than the existing one. Otherwise, we
11210 // can end up oscillating between two possible DAGs, for example,
11211 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11212 if (Offset <= uint64_t(GN->getOffset()))
11213 return SDValue();
11214
11215 // Check whether folding this offset is legal. It must not go out of bounds of
11216 // the referenced object to avoid violating the code model, and must be
11217 // smaller than 2^21 because this is the largest offset expressible in all
11218 // object formats.
11219 //
11220 // This check also prevents us from folding negative offsets, which will end
11221 // up being treated in the same way as large positive ones. They could also
11222 // cause code model violations, and aren't really common enough to matter.
11223 if (Offset >= (1 << 21))
11224 return SDValue();
11225
11226 const GlobalValue *GV = GN->getGlobal();
11227 Type *T = GV->getValueType();
11228 if (!T->isSized() ||
11229 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11230 return SDValue();
11231
11232 SDLoc DL(GN);
11233 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11234 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11235 DAG.getConstant(MinOffset, DL, MVT::i64));
11236}
11237
Tim Northover3b0846e2014-05-24 12:50:23 +000011238SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11239 DAGCombinerInfo &DCI) const {
11240 SelectionDAG &DAG = DCI.DAG;
11241 switch (N->getOpcode()) {
11242 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011243 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011244 break;
11245 case ISD::ADD:
11246 case ISD::SUB:
11247 return performAddSubLongCombine(N, DCI, DAG);
11248 case ISD::XOR:
11249 return performXorCombine(N, DAG, DCI, Subtarget);
11250 case ISD::MUL:
11251 return performMulCombine(N, DAG, DCI, Subtarget);
11252 case ISD::SINT_TO_FP:
11253 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011254 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011255 case ISD::FP_TO_SINT:
11256 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011257 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011258 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011259 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011260 case ISD::OR:
11261 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011262 case ISD::SRL:
11263 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011264 case ISD::INTRINSIC_WO_CHAIN:
11265 return performIntrinsicCombine(N, DCI, Subtarget);
11266 case ISD::ANY_EXTEND:
11267 case ISD::ZERO_EXTEND:
11268 case ISD::SIGN_EXTEND:
11269 return performExtendCombine(N, DCI, DAG);
11270 case ISD::BITCAST:
11271 return performBitcastCombine(N, DCI, DAG);
11272 case ISD::CONCAT_VECTORS:
11273 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011274 case ISD::SELECT:
11275 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011276 case ISD::VSELECT:
11277 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011278 case ISD::LOAD:
11279 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11280 return SDValue(N, 0);
11281 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011282 case ISD::STORE:
11283 return performSTORECombine(N, DCI, DAG, Subtarget);
11284 case AArch64ISD::BRCOND:
11285 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011286 case AArch64ISD::TBNZ:
11287 case AArch64ISD::TBZ:
11288 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011289 case AArch64ISD::CSEL:
11290 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011291 case AArch64ISD::DUP:
11292 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011293 case AArch64ISD::NVCAST:
11294 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011295 case ISD::INSERT_VECTOR_ELT:
11296 return performPostLD1Combine(N, DCI, true);
11297 case ISD::INTRINSIC_VOID:
11298 case ISD::INTRINSIC_W_CHAIN:
11299 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11300 case Intrinsic::aarch64_neon_ld2:
11301 case Intrinsic::aarch64_neon_ld3:
11302 case Intrinsic::aarch64_neon_ld4:
11303 case Intrinsic::aarch64_neon_ld1x2:
11304 case Intrinsic::aarch64_neon_ld1x3:
11305 case Intrinsic::aarch64_neon_ld1x4:
11306 case Intrinsic::aarch64_neon_ld2lane:
11307 case Intrinsic::aarch64_neon_ld3lane:
11308 case Intrinsic::aarch64_neon_ld4lane:
11309 case Intrinsic::aarch64_neon_ld2r:
11310 case Intrinsic::aarch64_neon_ld3r:
11311 case Intrinsic::aarch64_neon_ld4r:
11312 case Intrinsic::aarch64_neon_st2:
11313 case Intrinsic::aarch64_neon_st3:
11314 case Intrinsic::aarch64_neon_st4:
11315 case Intrinsic::aarch64_neon_st1x2:
11316 case Intrinsic::aarch64_neon_st1x3:
11317 case Intrinsic::aarch64_neon_st1x4:
11318 case Intrinsic::aarch64_neon_st2lane:
11319 case Intrinsic::aarch64_neon_st3lane:
11320 case Intrinsic::aarch64_neon_st4lane:
11321 return performNEONPostLDSTCombine(N, DCI, DAG);
11322 default:
11323 break;
11324 }
Reid Klecknereb568942018-11-01 18:02:27 +000011325 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011326 case ISD::GlobalAddress:
11327 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011328 }
11329 return SDValue();
11330}
11331
11332// Check if the return value is used as only a return value, as otherwise
11333// we can't perform a tail-call. In particular, we need to check for
11334// target ISD nodes that are returns and any other "odd" constructs
11335// that the generic analysis code won't necessarily catch.
11336bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11337 SDValue &Chain) const {
11338 if (N->getNumValues() != 1)
11339 return false;
11340 if (!N->hasNUsesOfValue(1, 0))
11341 return false;
11342
11343 SDValue TCChain = Chain;
11344 SDNode *Copy = *N->use_begin();
11345 if (Copy->getOpcode() == ISD::CopyToReg) {
11346 // If the copy has a glue operand, we conservatively assume it isn't safe to
11347 // perform a tail call.
11348 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11349 MVT::Glue)
11350 return false;
11351 TCChain = Copy->getOperand(0);
11352 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11353 return false;
11354
11355 bool HasRet = false;
11356 for (SDNode *Node : Copy->uses()) {
11357 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11358 return false;
11359 HasRet = true;
11360 }
11361
11362 if (!HasRet)
11363 return false;
11364
11365 Chain = TCChain;
11366 return true;
11367}
11368
11369// Return whether the an instruction can potentially be optimized to a tail
11370// call. This will cause the optimizers to attempt to move, or duplicate,
11371// return instructions to help enable tail call optimizations for this
11372// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011373bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011374 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011375}
11376
11377bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11378 SDValue &Offset,
11379 ISD::MemIndexedMode &AM,
11380 bool &IsInc,
11381 SelectionDAG &DAG) const {
11382 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11383 return false;
11384
11385 Base = Op->getOperand(0);
11386 // All of the indexed addressing mode instructions take a signed
11387 // 9 bit immediate offset.
11388 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011389 int64_t RHSC = RHS->getSExtValue();
11390 if (Op->getOpcode() == ISD::SUB)
11391 RHSC = -(uint64_t)RHSC;
11392 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011393 return false;
11394 IsInc = (Op->getOpcode() == ISD::ADD);
11395 Offset = Op->getOperand(1);
11396 return true;
11397 }
11398 return false;
11399}
11400
11401bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11402 SDValue &Offset,
11403 ISD::MemIndexedMode &AM,
11404 SelectionDAG &DAG) const {
11405 EVT VT;
11406 SDValue Ptr;
11407 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11408 VT = LD->getMemoryVT();
11409 Ptr = LD->getBasePtr();
11410 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11411 VT = ST->getMemoryVT();
11412 Ptr = ST->getBasePtr();
11413 } else
11414 return false;
11415
11416 bool IsInc;
11417 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11418 return false;
11419 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11420 return true;
11421}
11422
11423bool AArch64TargetLowering::getPostIndexedAddressParts(
11424 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11425 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11426 EVT VT;
11427 SDValue Ptr;
11428 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11429 VT = LD->getMemoryVT();
11430 Ptr = LD->getBasePtr();
11431 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11432 VT = ST->getMemoryVT();
11433 Ptr = ST->getBasePtr();
11434 } else
11435 return false;
11436
11437 bool IsInc;
11438 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11439 return false;
11440 // Post-indexing updates the base, so it's not a valid transform
11441 // if that's not the same as the load's pointer.
11442 if (Ptr != Base)
11443 return false;
11444 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11445 return true;
11446}
11447
Tim Northoverf8bfe212014-07-18 13:07:05 +000011448static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11449 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011450 SDLoc DL(N);
11451 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011452
11453 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11454 return;
11455
Tim Northoverf8bfe212014-07-18 13:07:05 +000011456 Op = SDValue(
11457 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11458 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011459 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011460 0);
11461 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11462 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11463}
11464
Charlie Turner434d4592015-10-16 15:38:25 +000011465static void ReplaceReductionResults(SDNode *N,
11466 SmallVectorImpl<SDValue> &Results,
11467 SelectionDAG &DAG, unsigned InterOp,
11468 unsigned AcrossOp) {
11469 EVT LoVT, HiVT;
11470 SDValue Lo, Hi;
11471 SDLoc dl(N);
11472 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11473 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11474 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11475 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11476 Results.push_back(SplitVal);
11477}
11478
Tim Northover2f32e7f2016-08-04 19:32:28 +000011479static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11480 SDLoc DL(N);
11481 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11482 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11483 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11484 DAG.getConstant(64, DL, MVT::i64)));
11485 return std::make_pair(Lo, Hi);
11486}
11487
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011488// Create an even/odd pair of X registers holding integer value V.
11489static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11490 SDLoc dl(V.getNode());
11491 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11492 SDValue VHi = DAG.getAnyExtOrTrunc(
11493 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11494 dl, MVT::i64);
11495 if (DAG.getDataLayout().isBigEndian())
11496 std::swap (VLo, VHi);
11497 SDValue RegClass =
11498 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11499 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11500 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11501 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11502 return SDValue(
11503 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11504}
11505
Tim Northovercdf15292016-04-14 17:03:29 +000011506static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011507 SmallVectorImpl<SDValue> &Results,
11508 SelectionDAG &DAG,
11509 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011510 assert(N->getValueType(0) == MVT::i128 &&
11511 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011512
11513 if (Subtarget->hasLSE()) {
11514 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11515 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11516 SDValue Ops[] = {
11517 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11518 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11519 N->getOperand(1), // Ptr
11520 N->getOperand(0), // Chain in
11521 };
11522
Chandler Carruth66654b72018-08-14 23:30:32 +000011523 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011524
11525 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011526 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011527 case AtomicOrdering::Monotonic:
11528 Opcode = AArch64::CASPX;
11529 break;
11530 case AtomicOrdering::Acquire:
11531 Opcode = AArch64::CASPAX;
11532 break;
11533 case AtomicOrdering::Release:
11534 Opcode = AArch64::CASPLX;
11535 break;
11536 case AtomicOrdering::AcquireRelease:
11537 case AtomicOrdering::SequentiallyConsistent:
11538 Opcode = AArch64::CASPALX;
11539 break;
11540 default:
11541 llvm_unreachable("Unexpected ordering!");
11542 }
11543
11544 MachineSDNode *CmpSwap = DAG.getMachineNode(
11545 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011546 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011547
11548 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11549 if (DAG.getDataLayout().isBigEndian())
11550 std::swap(SubReg1, SubReg2);
11551 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11552 SDValue(CmpSwap, 0)));
11553 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11554 SDValue(CmpSwap, 0)));
11555 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11556 return;
11557 }
11558
Tim Northover2f32e7f2016-08-04 19:32:28 +000011559 auto Desired = splitInt128(N->getOperand(2), DAG);
11560 auto New = splitInt128(N->getOperand(3), DAG);
11561 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11562 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011563 SDNode *CmpSwap = DAG.getMachineNode(
11564 AArch64::CMP_SWAP_128, SDLoc(N),
11565 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11566
Chandler Carruth66654b72018-08-14 23:30:32 +000011567 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11568 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011569
11570 Results.push_back(SDValue(CmpSwap, 0));
11571 Results.push_back(SDValue(CmpSwap, 1));
11572 Results.push_back(SDValue(CmpSwap, 3));
11573}
11574
Tim Northover3b0846e2014-05-24 12:50:23 +000011575void AArch64TargetLowering::ReplaceNodeResults(
11576 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11577 switch (N->getOpcode()) {
11578 default:
11579 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011580 case ISD::BITCAST:
11581 ReplaceBITCASTResults(N, Results, DAG);
11582 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011583 case ISD::VECREDUCE_ADD:
11584 case ISD::VECREDUCE_SMAX:
11585 case ISD::VECREDUCE_SMIN:
11586 case ISD::VECREDUCE_UMAX:
11587 case ISD::VECREDUCE_UMIN:
11588 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11589 return;
11590
Charlie Turner434d4592015-10-16 15:38:25 +000011591 case AArch64ISD::SADDV:
11592 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11593 return;
11594 case AArch64ISD::UADDV:
11595 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11596 return;
11597 case AArch64ISD::SMINV:
11598 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11599 return;
11600 case AArch64ISD::UMINV:
11601 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11602 return;
11603 case AArch64ISD::SMAXV:
11604 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11605 return;
11606 case AArch64ISD::UMAXV:
11607 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11608 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011609 case ISD::FP_TO_UINT:
11610 case ISD::FP_TO_SINT:
11611 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11612 // Let normal code take care of it by not adding anything to Results.
11613 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011614 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011615 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011616 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011617 }
11618}
11619
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011620bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011621 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11622 return TargetLowering::useLoadStackGuardNode();
11623 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011624}
11625
Sanjay Patel1dd15592015-07-28 23:05:48 +000011626unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011627 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11628 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011629 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011630}
11631
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011632TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011633AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011634 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11635 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011636 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11637 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011638 return TypeWidenVector;
11639
11640 return TargetLoweringBase::getPreferredVectorAction(VT);
11641}
11642
Robin Morisseted3d48f2014-09-03 21:29:59 +000011643// Loads and stores less than 128-bits are already atomic; ones above that
11644// are doomed anyway, so defer to the default libcall and blame the OS when
11645// things go wrong.
11646bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11647 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11648 return Size == 128;
11649}
11650
11651// Loads and stores less than 128-bits are already atomic; ones above that
11652// are doomed anyway, so defer to the default libcall and blame the OS when
11653// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011654TargetLowering::AtomicExpansionKind
11655AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011656 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011657 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011658}
11659
11660// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011661TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011662AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Matt Arsenault39508332019-01-22 18:18:02 +000011663 if (AI->isFloatingPointOperation())
11664 return AtomicExpansionKind::CmpXChg;
11665
Robin Morisseted3d48f2014-09-03 21:29:59 +000011666 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011667 if (Size > 128) return AtomicExpansionKind::None;
11668 // Nand not supported in LSE.
11669 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011670 // Leave 128 bits to LLSC.
11671 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011672}
11673
Alex Bradbury79518b02018-09-19 14:51:42 +000011674TargetLowering::AtomicExpansionKind
11675AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011676 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011677 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011678 if (Subtarget->hasLSE())
11679 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011680 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11681 // implement cmpxchg without spilling. If the address being exchanged is also
11682 // on the stack and close enough to the spill slot, this can lead to a
11683 // situation where the monitor always gets cleared and the atomic operation
11684 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011685 if (getTargetMachine().getOptLevel() == 0)
11686 return AtomicExpansionKind::None;
11687 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011688}
11689
Tim Northover3b0846e2014-05-24 12:50:23 +000011690Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11691 AtomicOrdering Ord) const {
11692 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11693 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011694 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011695
11696 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11697 // intrinsic must return {i64, i64} and we have to recombine them into a
11698 // single i128 here.
11699 if (ValTy->getPrimitiveSizeInBits() == 128) {
11700 Intrinsic::ID Int =
11701 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011702 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011703
11704 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11705 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11706
11707 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11708 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11709 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11710 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11711 return Builder.CreateOr(
11712 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11713 }
11714
11715 Type *Tys[] = { Addr->getType() };
11716 Intrinsic::ID Int =
11717 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011718 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011719
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011720 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11721
11722 const DataLayout &DL = M->getDataLayout();
11723 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11724 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11725
11726 return Builder.CreateBitCast(Trunc, EltTy);
Tim Northover3b0846e2014-05-24 12:50:23 +000011727}
11728
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011729void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11730 IRBuilder<> &Builder) const {
11731 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011732 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011733}
11734
Tim Northover3b0846e2014-05-24 12:50:23 +000011735Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11736 Value *Val, Value *Addr,
11737 AtomicOrdering Ord) const {
11738 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011739 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011740
11741 // Since the intrinsics must have legal type, the i128 intrinsics take two
11742 // parameters: "i64, i64". We must marshal Val into the appropriate form
11743 // before the call.
11744 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11745 Intrinsic::ID Int =
11746 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11747 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11748 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11749
11750 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11751 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11752 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011753 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011754 }
11755
11756 Intrinsic::ID Int =
11757 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11758 Type *Tys[] = { Addr->getType() };
11759 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11760
Matt Arsenault0cb08e42019-01-17 10:49:01 +000011761 const DataLayout &DL = M->getDataLayout();
11762 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
11763 Val = Builder.CreateBitCast(Val, IntValTy);
11764
David Blaikieff6409d2015-05-18 22:13:54 +000011765 return Builder.CreateCall(Stxr,
11766 {Builder.CreateZExtOrBitCast(
11767 Val, Stxr->getFunctionType()->getParamType(0)),
11768 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011769}
Tim Northover3c55cca2014-11-27 21:02:42 +000011770
11771bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11772 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11773 return Ty->isArrayTy();
11774}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011775
11776bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11777 EVT) const {
11778 return false;
11779}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011780
Petr Hoseka7d59162017-02-24 03:10:10 +000011781static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011782 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11783 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011784 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011785 return IRB.CreatePointerCast(
James Y Knight77160752019-02-01 20:44:47 +000011786 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
11787 Offset),
11788 IRB.getInt8PtrTy()->getPointerTo(0));
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011789}
11790
Petr Hoseka7d59162017-02-24 03:10:10 +000011791Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11792 // Android provides a fixed TLS slot for the stack cookie. See the definition
11793 // of TLS_SLOT_STACK_GUARD in
11794 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11795 if (Subtarget->isTargetAndroid())
11796 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011797
Petr Hoseka7d59162017-02-24 03:10:10 +000011798 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011799 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011800 if (Subtarget->isTargetFuchsia())
11801 return UseTlsOffset(IRB, -0x10);
11802
11803 return TargetLowering::getIRStackGuard(IRB);
11804}
11805
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011806void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11807 // MSVC CRT provides functionalities for stack protection.
11808 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11809 // MSVC CRT has a global variable holding security cookie.
11810 M.getOrInsertGlobal("__security_cookie",
11811 Type::getInt8PtrTy(M.getContext()));
11812
11813 // MSVC CRT has a function to validate security cookie.
James Y Knight13680222019-02-01 02:28:03 +000011814 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
11815 "__security_check_cookie", Type::getVoidTy(M.getContext()),
11816 Type::getInt8PtrTy(M.getContext()));
11817 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
11818 F->setCallingConv(CallingConv::Win64);
11819 F->addAttribute(1, Attribute::AttrKind::InReg);
11820 }
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011821 return;
11822 }
11823 TargetLowering::insertSSPDeclarations(M);
11824}
11825
11826Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
11827 // MSVC CRT has a global variable holding security cookie.
11828 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11829 return M.getGlobalVariable("__security_cookie");
11830 return TargetLowering::getSDagStackGuard(M);
11831}
11832
James Y Knight7976eb52019-02-01 20:43:25 +000011833Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011834 // MSVC CRT has a function to validate security cookie.
11835 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11836 return M.getFunction("__security_check_cookie");
11837 return TargetLowering::getSSPStackGuardCheck(M);
11838}
11839
Petr Hoseka7d59162017-02-24 03:10:10 +000011840Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011841 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11842 // definition of TLS_SLOT_SAFESTACK in
11843 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011844 if (Subtarget->isTargetAndroid())
11845 return UseTlsOffset(IRB, 0x48);
11846
11847 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011848 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011849 if (Subtarget->isTargetFuchsia())
11850 return UseTlsOffset(IRB, -0x8);
11851
11852 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011853}
Manman Rencbe4f942015-12-16 21:04:19 +000011854
Geoff Berry5d534b62017-02-21 18:53:14 +000011855bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11856 const Instruction &AndI) const {
11857 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11858 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11859 // may be beneficial to sink in other cases, but we would have to check that
11860 // the cmp would not get folded into the br to form a cbz for these to be
11861 // beneficial.
11862 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11863 if (!Mask)
11864 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011865 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011866}
11867
Manman Rencbe4f942015-12-16 21:04:19 +000011868void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11869 // Update IsSplitCSR in AArch64unctionInfo.
11870 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11871 AFI->setIsSplitCSR(true);
11872}
11873
11874void AArch64TargetLowering::insertCopiesSplitCSR(
11875 MachineBasicBlock *Entry,
11876 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11877 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11878 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11879 if (!IStart)
11880 return;
11881
11882 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11883 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011884 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011885 for (const MCPhysReg *I = IStart; *I; ++I) {
11886 const TargetRegisterClass *RC = nullptr;
11887 if (AArch64::GPR64RegClass.contains(*I))
11888 RC = &AArch64::GPR64RegClass;
11889 else if (AArch64::FPR64RegClass.contains(*I))
11890 RC = &AArch64::FPR64RegClass;
11891 else
11892 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11893
11894 unsigned NewVR = MRI->createVirtualRegister(RC);
11895 // Create copy from CSR to a virtual register.
11896 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11897 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11898 // nounwind. If we want to generalize this later, we may need to emit
11899 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011900 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011901 Attribute::NoUnwind) &&
11902 "Function should be nounwind in insertCopiesSplitCSR!");
11903 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011904 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011905 .addReg(*I);
11906
Manman Ren4632e8e2016-01-15 20:13:28 +000011907 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011908 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011909 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11910 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011911 .addReg(NewVR);
11912 }
11913}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011914
Reid Klecknerb5180542017-03-21 16:57:19 +000011915bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011916 // Integer division on AArch64 is expensive. However, when aggressively
11917 // optimizing for code size, we prefer to use a div instruction, as it is
11918 // usually smaller than the alternative sequence.
11919 // The exception to this is vector division. Since AArch64 doesn't have vector
11920 // integer division, leaving the division as-is is a loss even in terms of
11921 // size, because it will have to be scalarized, while the alternative code
11922 // sequence can be performed in vector form.
11923 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011924 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011925 return OptSize && !VT.isVector();
11926}
Tim Northoverf19d4672017-02-08 17:57:20 +000011927
Joel Jones07150922018-01-25 21:55:39 +000011928bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11929 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11930}
11931
Tim Northoverf19d4672017-02-08 17:57:20 +000011932unsigned
11933AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011934 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011935 return getPointerTy(DL).getSizeInBits();
11936
11937 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11938}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011939
11940void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11941 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11942 TargetLoweringBase::finalizeLowering(MF);
11943}
Eli Friedmanad1151c2018-11-09 23:33:30 +000011944
11945// Unlike X86, we let frame lowering assign offsets to all catch objects.
11946bool AArch64TargetLowering::needsFixedCatchObjects() const {
11947 return false;
11948}