blob: c7f46a251bfd30de75ad014751b1c72eeddcf05b [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000018#include "AArch64RegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000020#include "MCTargetDesc/AArch64AddressingModes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000021#include "Utils/AArch64BaseInfo.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/ADT/STLExtras.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000026#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000027#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000028#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +000032#include "llvm/Analysis/VectorUtils.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000033#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000034#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000035#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000036#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000038#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000039#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000041#include "llvm/CodeGen/RuntimeLibcalls.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000044#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000045#include "llvm/CodeGen/TargetInstrInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000046#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000047#include "llvm/IR/Attributes.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000052#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000054#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000055#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000056#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Instructions.h"
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"
Tim Northover3b0846e2014-05-24 12:50:23 +000061#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000062#include "llvm/IR/Use.h"
63#include "llvm/IR/Value.h"
64#include "llvm/MC/MCRegisterInfo.h"
65#include "llvm/Support/Casting.h"
66#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000067#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000068#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000069#include "llvm/Support/Debug.h"
70#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000071#include "llvm/Support/KnownBits.h"
David Blaikie13e77db2018-03-23 23:58:25 +000072#include "llvm/Support/MachineValueType.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000073#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000074#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000075#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000076#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000077#include <algorithm>
78#include <bitset>
79#include <cassert>
80#include <cctype>
81#include <cstdint>
82#include <cstdlib>
83#include <iterator>
84#include <limits>
85#include <tuple>
86#include <utility>
87#include <vector>
88
Tim Northover3b0846e2014-05-24 12:50:23 +000089using namespace llvm;
90
91#define DEBUG_TYPE "aarch64-lower"
92
93STATISTIC(NumTailCalls, "Number of tail calls");
94STATISTIC(NumShiftInserts, "Number of vector shift inserts");
Akira Hatanaka22e839f2017-04-21 18:53:12 +000095STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
Tim Northover3b0846e2014-05-24 12:50:23 +000096
Tim Northover3b0846e2014-05-24 12:50:23 +000097static cl::opt<bool>
98EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000099 cl::desc("Allow AArch64 SLI/SRI formation"),
100 cl::init(false));
101
102// FIXME: The necessary dtprel relocations don't seem to be supported
103// well in the GNU bfd and gold linkers at the moment. Therefore, by
104// default, for now, fall back to GeneralDynamic code generation.
105cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106 "aarch64-elf-ldtls-generation", cl::Hidden,
107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000109
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000110static cl::opt<bool>
111EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112 cl::desc("Enable AArch64 logical imm instruction "
113 "optimization"),
114 cl::init(true));
115
Matthias Braunaf7d7702015-07-16 20:02:37 +0000116/// Value type used for condition codes.
117static const MVT MVT_CC = MVT::i32;
118
Eric Christopher905f12d2015-01-29 00:19:42 +0000119AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120 const AArch64Subtarget &STI)
121 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123 // we have to make something up. Arbitrarily, choose ZeroOrOne.
124 setBooleanContents(ZeroOrOneBooleanContent);
125 // When comparing vectors the result sets the different elements in the
126 // vector to all-one or all-zero.
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128
129 // Set up the register classes.
130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132
133 if (Subtarget->hasFPARMv8()) {
134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138 }
139
140 if (Subtarget->hasNEON()) {
141 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143 // Someone set us up the NEON.
144 addDRTypeForNEON(MVT::v2f32);
145 addDRTypeForNEON(MVT::v8i8);
146 addDRTypeForNEON(MVT::v4i16);
147 addDRTypeForNEON(MVT::v2i32);
148 addDRTypeForNEON(MVT::v1i64);
149 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000150 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000151
152 addQRTypeForNEON(MVT::v4f32);
153 addQRTypeForNEON(MVT::v2f64);
154 addQRTypeForNEON(MVT::v16i8);
155 addQRTypeForNEON(MVT::v8i16);
156 addQRTypeForNEON(MVT::v4i32);
157 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000158 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000159 }
160
161 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000162 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000163
164 // Provide all sorts of operation actions
165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167 setOperationAction(ISD::SETCC, MVT::i32, Custom);
168 setOperationAction(ISD::SETCC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000169 setOperationAction(ISD::SETCC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000170 setOperationAction(ISD::SETCC, MVT::f32, Custom);
171 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000172 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
173 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000174 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
175 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
176 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000177 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000178 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
179 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
180 setOperationAction(ISD::SELECT, MVT::i32, Custom);
181 setOperationAction(ISD::SELECT, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000182 setOperationAction(ISD::SELECT, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000183 setOperationAction(ISD::SELECT, MVT::f32, Custom);
184 setOperationAction(ISD::SELECT, MVT::f64, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
186 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000187 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000188 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
189 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
Tim Northover1c353412018-10-24 20:19:09 +0000190 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
192
193 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
194 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
195 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
196
197 setOperationAction(ISD::FREM, MVT::f32, Expand);
198 setOperationAction(ISD::FREM, MVT::f64, Expand);
199 setOperationAction(ISD::FREM, MVT::f80, Expand);
200
Amara Emersone27d5012018-04-10 19:01:58 +0000201 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
202
Tim Northover3b0846e2014-05-24 12:50:23 +0000203 // Custom lowering hooks are needed for XOR
204 // to fold it into CSINC/CSINV.
205 setOperationAction(ISD::XOR, MVT::i32, Custom);
206 setOperationAction(ISD::XOR, MVT::i64, Custom);
207
208 // Virtually no operation on f128 is legal, but LLVM can't expand them when
209 // there's a valid register class, so we need custom operations in most cases.
210 setOperationAction(ISD::FABS, MVT::f128, Expand);
211 setOperationAction(ISD::FADD, MVT::f128, Custom);
212 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
213 setOperationAction(ISD::FCOS, MVT::f128, Expand);
214 setOperationAction(ISD::FDIV, MVT::f128, Custom);
215 setOperationAction(ISD::FMA, MVT::f128, Expand);
216 setOperationAction(ISD::FMUL, MVT::f128, Custom);
217 setOperationAction(ISD::FNEG, MVT::f128, Expand);
218 setOperationAction(ISD::FPOW, MVT::f128, Expand);
219 setOperationAction(ISD::FREM, MVT::f128, Expand);
220 setOperationAction(ISD::FRINT, MVT::f128, Expand);
221 setOperationAction(ISD::FSIN, MVT::f128, Expand);
222 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
223 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
224 setOperationAction(ISD::FSUB, MVT::f128, Custom);
225 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
226 setOperationAction(ISD::SETCC, MVT::f128, Custom);
227 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
228 setOperationAction(ISD::SELECT, MVT::f128, Custom);
229 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
230 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
231
232 // Lowering for many of the conversions is actually specified by the non-f128
233 // type. The LowerXXX function will be trivial when f128 isn't involved.
234 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
235 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
236 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
237 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
238 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
239 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
240 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
241 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
242 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
243 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
244 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
245 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
246 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
247 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
248
249 // Variable arguments.
250 setOperationAction(ISD::VASTART, MVT::Other, Custom);
251 setOperationAction(ISD::VAARG, MVT::Other, Custom);
252 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
253 setOperationAction(ISD::VAEND, MVT::Other, Expand);
254
255 // Variable-sized objects.
256 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
257 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000258
259 if (Subtarget->isTargetWindows())
260 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
261 else
262 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000263
Tim Northover3b0846e2014-05-24 12:50:23 +0000264 // Constant pool entries
265 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
266
267 // BlockAddress
268 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
269
270 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
271 setOperationAction(ISD::ADDC, MVT::i32, Custom);
272 setOperationAction(ISD::ADDE, MVT::i32, Custom);
273 setOperationAction(ISD::SUBC, MVT::i32, Custom);
274 setOperationAction(ISD::SUBE, MVT::i32, Custom);
275 setOperationAction(ISD::ADDC, MVT::i64, Custom);
276 setOperationAction(ISD::ADDE, MVT::i64, Custom);
277 setOperationAction(ISD::SUBC, MVT::i64, Custom);
278 setOperationAction(ISD::SUBE, MVT::i64, Custom);
279
280 // AArch64 lacks both left-rotate and popcount instructions.
281 setOperationAction(ISD::ROTL, MVT::i32, Expand);
282 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000283 for (MVT VT : MVT::vector_valuetypes()) {
284 setOperationAction(ISD::ROTL, VT, Expand);
285 setOperationAction(ISD::ROTR, VT, Expand);
286 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000287
288 // AArch64 doesn't have {U|S}MUL_LOHI.
289 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
290 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
291
Tim Northover3b0846e2014-05-24 12:50:23 +0000292 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
293 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
294
295 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
296 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000297 for (MVT VT : MVT::vector_valuetypes()) {
298 setOperationAction(ISD::SDIVREM, VT, Expand);
299 setOperationAction(ISD::UDIVREM, VT, Expand);
300 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000301 setOperationAction(ISD::SREM, MVT::i32, Expand);
302 setOperationAction(ISD::SREM, MVT::i64, Expand);
303 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
304 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
305 setOperationAction(ISD::UREM, MVT::i32, Expand);
306 setOperationAction(ISD::UREM, MVT::i64, Expand);
307
308 // Custom lower Add/Sub/Mul with overflow.
309 setOperationAction(ISD::SADDO, MVT::i32, Custom);
310 setOperationAction(ISD::SADDO, MVT::i64, Custom);
311 setOperationAction(ISD::UADDO, MVT::i32, Custom);
312 setOperationAction(ISD::UADDO, MVT::i64, Custom);
313 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
314 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
315 setOperationAction(ISD::USUBO, MVT::i32, Custom);
316 setOperationAction(ISD::USUBO, MVT::i64, Custom);
317 setOperationAction(ISD::SMULO, MVT::i32, Custom);
318 setOperationAction(ISD::SMULO, MVT::i64, Custom);
319 setOperationAction(ISD::UMULO, MVT::i32, Custom);
320 setOperationAction(ISD::UMULO, MVT::i64, Custom);
321
322 setOperationAction(ISD::FSIN, MVT::f32, Expand);
323 setOperationAction(ISD::FSIN, MVT::f64, Expand);
324 setOperationAction(ISD::FCOS, MVT::f32, Expand);
325 setOperationAction(ISD::FCOS, MVT::f64, Expand);
326 setOperationAction(ISD::FPOW, MVT::f32, Expand);
327 setOperationAction(ISD::FPOW, MVT::f64, Expand);
328 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
329 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000330 if (Subtarget->hasFullFP16())
331 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
332 else
333 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000334
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000335 setOperationAction(ISD::FREM, MVT::f16, Promote);
336 setOperationAction(ISD::FREM, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000337 setOperationAction(ISD::FREM, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000338 setOperationAction(ISD::FPOW, MVT::f16, Promote);
339 setOperationAction(ISD::FPOW, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000340 setOperationAction(ISD::FPOW, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000341 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
342 setOperationAction(ISD::FCOS, MVT::f16, Promote);
343 setOperationAction(ISD::FCOS, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000344 setOperationAction(ISD::FCOS, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000345 setOperationAction(ISD::FSIN, MVT::f16, Promote);
346 setOperationAction(ISD::FSIN, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000347 setOperationAction(ISD::FSIN, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000348 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
349 setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000350 setOperationAction(ISD::FSINCOS, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000351 setOperationAction(ISD::FEXP, MVT::f16, Promote);
352 setOperationAction(ISD::FEXP, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000353 setOperationAction(ISD::FEXP, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000354 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
355 setOperationAction(ISD::FEXP2, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000356 setOperationAction(ISD::FEXP2, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000357 setOperationAction(ISD::FLOG, MVT::f16, Promote);
358 setOperationAction(ISD::FLOG, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000359 setOperationAction(ISD::FLOG, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000360 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
361 setOperationAction(ISD::FLOG2, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000362 setOperationAction(ISD::FLOG2, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000363 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
364 setOperationAction(ISD::FLOG10, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000365 setOperationAction(ISD::FLOG10, MVT::v8f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000366
367 if (!Subtarget->hasFullFP16()) {
368 setOperationAction(ISD::SELECT, MVT::f16, Promote);
369 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
370 setOperationAction(ISD::SETCC, MVT::f16, Promote);
371 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
372 setOperationAction(ISD::FADD, MVT::f16, Promote);
373 setOperationAction(ISD::FSUB, MVT::f16, Promote);
374 setOperationAction(ISD::FMUL, MVT::f16, Promote);
375 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000376 setOperationAction(ISD::FMA, MVT::f16, Promote);
377 setOperationAction(ISD::FNEG, MVT::f16, Promote);
378 setOperationAction(ISD::FABS, MVT::f16, Promote);
379 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
380 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000381 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
382 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
383 setOperationAction(ISD::FRINT, MVT::f16, Promote);
384 setOperationAction(ISD::FROUND, MVT::f16, Promote);
385 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
386 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
387 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Thomas Lively30f1d692018-10-24 22:49:55 +0000388 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
389 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000390
391 // promote v4f16 to v4f32 when that is known to be safe.
392 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
393 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
394 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
395 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
396 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
397 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
398 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
399 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
400 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
401 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
402 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
403 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
404
405 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
406 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
407 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
408 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
409 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
410 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
411 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
412 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
413 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
414 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
415 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
416 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
417 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
418 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
419 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000420
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000421 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
422 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
423 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
424 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
425 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
426 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
427 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
428 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
429 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
430 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
431 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
432 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
433 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
434 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
435 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
436 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
437 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
438 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
439 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
440 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
441 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000442
Tim Northover3b0846e2014-05-24 12:50:23 +0000443 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000444 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000445 setOperationAction(ISD::FFLOOR, Ty, Legal);
446 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
447 setOperationAction(ISD::FCEIL, Ty, Legal);
448 setOperationAction(ISD::FRINT, Ty, Legal);
449 setOperationAction(ISD::FTRUNC, Ty, Legal);
450 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000451 setOperationAction(ISD::FMINNUM, Ty, Legal);
452 setOperationAction(ISD::FMAXNUM, Ty, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000453 setOperationAction(ISD::FMINIMUM, Ty, Legal);
454 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000455 }
456
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000457 if (Subtarget->hasFullFP16()) {
458 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
459 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
460 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
461 setOperationAction(ISD::FRINT, MVT::f16, Legal);
462 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
463 setOperationAction(ISD::FROUND, MVT::f16, Legal);
464 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
465 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000466 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
467 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000468 }
469
Tim Northover3b0846e2014-05-24 12:50:23 +0000470 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
471
Tim Northover70666e72018-06-20 12:09:01 +0000472 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
473
Tim Northovercdf15292016-04-14 17:03:29 +0000474 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000475 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000477 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000479
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000480 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
481 // This requires the Performance Monitors extension.
482 if (Subtarget->hasPerfMon())
483 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
484
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000485 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
486 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
487 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000488 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
489 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
490 } else {
491 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
492 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
493 }
494
Juergen Ributzka23266502014-12-10 19:43:32 +0000495 // Make floating-point constants legal for the large code model, so they don't
496 // become loads from the constant pool.
497 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
498 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
499 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
500 }
501
Tim Northover3b0846e2014-05-24 12:50:23 +0000502 // AArch64 does not have floating-point extending loads, i1 sign-extending
503 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000504 for (MVT VT : MVT::fp_valuetypes()) {
505 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
506 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
507 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
508 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
509 }
510 for (MVT VT : MVT::integer_valuetypes())
511 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
512
Tim Northover3b0846e2014-05-24 12:50:23 +0000513 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
514 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
515 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
516 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
517 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
518 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
519 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000520
521 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
522 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
523
Tim Northover3b0846e2014-05-24 12:50:23 +0000524 // Indexed loads and stores are supported.
525 for (unsigned im = (unsigned)ISD::PRE_INC;
526 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
527 setIndexedLoadAction(im, MVT::i8, Legal);
528 setIndexedLoadAction(im, MVT::i16, Legal);
529 setIndexedLoadAction(im, MVT::i32, Legal);
530 setIndexedLoadAction(im, MVT::i64, Legal);
531 setIndexedLoadAction(im, MVT::f64, Legal);
532 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000533 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000534 setIndexedStoreAction(im, MVT::i8, Legal);
535 setIndexedStoreAction(im, MVT::i16, Legal);
536 setIndexedStoreAction(im, MVT::i32, Legal);
537 setIndexedStoreAction(im, MVT::i64, Legal);
538 setIndexedStoreAction(im, MVT::f64, Legal);
539 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000540 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000541 }
542
543 // Trap.
544 setOperationAction(ISD::TRAP, MVT::Other, Legal);
545
546 // We combine OR nodes for bitfield operations.
547 setTargetDAGCombine(ISD::OR);
548
549 // Vector add and sub nodes may conceal a high-half opportunity.
550 // Also, try to fold ADD into CSINC/CSINV..
551 setTargetDAGCombine(ISD::ADD);
552 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000553 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000554 setTargetDAGCombine(ISD::XOR);
555 setTargetDAGCombine(ISD::SINT_TO_FP);
556 setTargetDAGCombine(ISD::UINT_TO_FP);
557
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000558 setTargetDAGCombine(ISD::FP_TO_SINT);
559 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000560 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000561
Tim Northover3b0846e2014-05-24 12:50:23 +0000562 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
563
564 setTargetDAGCombine(ISD::ANY_EXTEND);
565 setTargetDAGCombine(ISD::ZERO_EXTEND);
566 setTargetDAGCombine(ISD::SIGN_EXTEND);
567 setTargetDAGCombine(ISD::BITCAST);
568 setTargetDAGCombine(ISD::CONCAT_VECTORS);
569 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000570 if (Subtarget->supportsAddressTopByteIgnored())
571 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000572
573 setTargetDAGCombine(ISD::MUL);
574
575 setTargetDAGCombine(ISD::SELECT);
576 setTargetDAGCombine(ISD::VSELECT);
577
578 setTargetDAGCombine(ISD::INTRINSIC_VOID);
579 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
580 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
581
Peter Collingbourne5ab4a472018-04-23 19:09:34 +0000582 setTargetDAGCombine(ISD::GlobalAddress);
583
Evandro Menezesf8425342018-05-29 15:58:50 +0000584 // In case of strict alignment, avoid an excessive number of byte wide stores.
585 MaxStoresPerMemsetOptSize = 8;
586 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
587 ? MaxStoresPerMemsetOptSize : 32;
Sirish Pandecabe50a32018-05-16 15:36:52 +0000588
Evandro Menezesf8425342018-05-29 15:58:50 +0000589 MaxGluedStoresPerMemcpy = 4;
590 MaxStoresPerMemcpyOptSize = 4;
591 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
592 ? MaxStoresPerMemcpyOptSize : 16;
593
594 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000595
596 setStackPointerRegisterToSaveRestore(AArch64::SP);
597
598 setSchedulingPreference(Sched::Hybrid);
599
Quentin Colombet6843ac42015-03-31 20:52:32 +0000600 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000601
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000602 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000603 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000604 // Set preferred alignments.
605 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
606 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000607
Evandro Menezese45de8a2016-09-26 15:32:33 +0000608 // Only change the limit for entries in a jump table if specified by
609 // the subtarget, but not at the command line.
610 unsigned MaxJT = STI.getMaximumJumpTableSize();
611 if (MaxJT && getMaximumJumpTableSize() == 0)
612 setMaximumJumpTableSize(MaxJT);
613
Tim Northover3b0846e2014-05-24 12:50:23 +0000614 setHasExtractBitsInsn(true);
615
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000616 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
617
Tim Northover3b0846e2014-05-24 12:50:23 +0000618 if (Subtarget->hasNEON()) {
619 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
620 // silliness like this:
621 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
622 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
623 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
624 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
625 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
626 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
627 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
628 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
629 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
630 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
631 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
632 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
633 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
634 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
635 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
636 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
637 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
638 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
639 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
640 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
641 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
642 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
643 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
644 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
645 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
646
647 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
648 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
649 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
650 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
651 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
652
653 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
654
655 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
656 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000657 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
658 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
659 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
660 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000661 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
662 // -> v8f16 conversions.
Craig Toppera4f99972018-01-01 19:21:35 +0000663 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
664 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
665 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
666 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000667 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
668 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
669 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
670 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
671 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000672 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
673 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
674 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
675 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000676
Craig Topperc5551bf2016-04-26 05:26:51 +0000677 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
678 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
679
Craig Topper3b4842b2016-04-28 01:58:21 +0000680 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
681 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
682 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
683 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
684 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
685 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
686 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
687 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
688
Tim Northover3b0846e2014-05-24 12:50:23 +0000689 // AArch64 doesn't have MUL.2d:
690 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000691 // Custom handling for some quad-vector types to detect MULL.
692 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
693 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
694 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
695
Amara Emersonc9916d72017-05-16 21:29:22 +0000696 // Vector reductions
697 for (MVT VT : MVT::integer_valuetypes()) {
698 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
699 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
700 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
701 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
702 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
703 }
704 for (MVT VT : MVT::fp_valuetypes()) {
705 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
706 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
707 }
708
Tim Northover3b0846e2014-05-24 12:50:23 +0000709 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
710 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
711 // Likewise, narrowing and extending vector loads/stores aren't handled
712 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000713 for (MVT VT : MVT::vector_valuetypes()) {
714 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000715
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000716 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
Craig Topper129d5292018-11-29 19:36:17 +0000717 setOperationAction(ISD::MULHS, VT, Legal);
718 setOperationAction(ISD::MULHU, VT, Legal);
Adhemerval Zanellaa57ef172018-05-04 14:33:55 +0000719 } else {
720 setOperationAction(ISD::MULHS, VT, Expand);
721 setOperationAction(ISD::MULHU, VT, Expand);
722 }
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000723 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000724 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000725
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000726 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000727
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000728 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000729 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000730 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
731 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
732 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
733 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000734 }
735
736 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000737 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000738 setOperationAction(ISD::FFLOOR, Ty, Legal);
739 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
740 setOperationAction(ISD::FCEIL, Ty, Legal);
741 setOperationAction(ISD::FRINT, Ty, Legal);
742 setOperationAction(ISD::FTRUNC, Ty, Legal);
743 setOperationAction(ISD::FROUND, Ty, Legal);
744 }
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +0000745
746 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000747 }
James Molloyf089ab72014-08-06 10:42:18 +0000748
Matthias Braun651cff42016-06-02 18:03:53 +0000749 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000750}
751
Craig Topper18e69f42016-04-15 06:20:21 +0000752void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000753 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000754
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000755 if (VT.isFloatingPoint()) {
756 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
757 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
758 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000759 }
760
761 // Mark vector float intrinsics as expand.
762 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000763 setOperationAction(ISD::FSIN, VT, Expand);
764 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000765 setOperationAction(ISD::FPOW, VT, Expand);
766 setOperationAction(ISD::FLOG, VT, Expand);
767 setOperationAction(ISD::FLOG2, VT, Expand);
768 setOperationAction(ISD::FLOG10, VT, Expand);
769 setOperationAction(ISD::FEXP, VT, Expand);
770 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000771
772 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000773 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000774 }
775
Craig Topper18e69f42016-04-15 06:20:21 +0000776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
777 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
778 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
779 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
780 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
781 setOperationAction(ISD::SRA, VT, Custom);
782 setOperationAction(ISD::SRL, VT, Custom);
783 setOperationAction(ISD::SHL, VT, Custom);
784 setOperationAction(ISD::AND, VT, Custom);
785 setOperationAction(ISD::OR, VT, Custom);
786 setOperationAction(ISD::SETCC, VT, Custom);
787 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000788
Craig Topper18e69f42016-04-15 06:20:21 +0000789 setOperationAction(ISD::SELECT, VT, Expand);
790 setOperationAction(ISD::SELECT_CC, VT, Expand);
791 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000792 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000793 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000794
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000795 // CNT supports only B element sizes, then use UADDLP to widen.
Tim Northover3b0846e2014-05-24 12:50:23 +0000796 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Simon Pilgrim095a7fe2018-10-15 21:15:58 +0000797 setOperationAction(ISD::CTPOP, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000798
Craig Topper18e69f42016-04-15 06:20:21 +0000799 setOperationAction(ISD::UDIV, VT, Expand);
800 setOperationAction(ISD::SDIV, VT, Expand);
801 setOperationAction(ISD::UREM, VT, Expand);
802 setOperationAction(ISD::SREM, VT, Expand);
803 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000804
Craig Topper18e69f42016-04-15 06:20:21 +0000805 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
806 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000807
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000808 if (!VT.isFloatingPoint())
809 setOperationAction(ISD::ABS, VT, Legal);
810
Hal Finkelcd8664c2015-12-11 23:11:52 +0000811 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000812 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000813 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000814 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000815
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000816 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
817 if (VT.isFloatingPoint() &&
818 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
Thomas Lively30f1d692018-10-24 22:49:55 +0000819 for (unsigned Opcode :
820 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000821 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000822
Tim Northover3b0846e2014-05-24 12:50:23 +0000823 if (Subtarget->isLittleEndian()) {
824 for (unsigned im = (unsigned)ISD::PRE_INC;
825 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000826 setIndexedLoadAction(im, VT, Legal);
827 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000828 }
829 }
830}
831
832void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
833 addRegisterClass(VT, &AArch64::FPR64RegClass);
834 addTypeForNEON(VT, MVT::v2i32);
835}
836
837void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
838 addRegisterClass(VT, &AArch64::FPR128RegClass);
839 addTypeForNEON(VT, MVT::v4i32);
840}
841
Mehdi Amini44ede332015-07-09 02:09:04 +0000842EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
843 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000844 if (!VT.isVector())
845 return MVT::i32;
846 return VT.changeVectorElementTypeToInteger();
847}
848
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000849static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
850 const APInt &Demanded,
851 TargetLowering::TargetLoweringOpt &TLO,
852 unsigned NewOpc) {
853 uint64_t OldImm = Imm, NewImm, Enc;
854 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
855
856 // Return if the immediate is already all zeros, all ones, a bimm32 or a
857 // bimm64.
858 if (Imm == 0 || Imm == Mask ||
859 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
860 return false;
861
862 unsigned EltSize = Size;
863 uint64_t DemandedBits = Demanded.getZExtValue();
864
865 // Clear bits that are not demanded.
866 Imm &= DemandedBits;
867
868 while (true) {
869 // The goal here is to set the non-demanded bits in a way that minimizes
870 // the number of switching between 0 and 1. In order to achieve this goal,
871 // we set the non-demanded bits to the value of the preceding demanded bits.
872 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
873 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
874 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
875 // The final result is 0b11000011.
876 uint64_t NonDemandedBits = ~DemandedBits;
877 uint64_t InvertedImm = ~Imm & DemandedBits;
878 uint64_t RotatedImm =
879 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
880 NonDemandedBits;
881 uint64_t Sum = RotatedImm + NonDemandedBits;
882 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
883 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
884 NewImm = (Imm | Ones) & Mask;
885
886 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
887 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
888 // we halve the element size and continue the search.
889 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
890 break;
891
892 // We cannot shrink the element size any further if it is 2-bits.
893 if (EltSize == 2)
894 return false;
895
896 EltSize /= 2;
897 Mask >>= EltSize;
898 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
899
900 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
901 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
902 return false;
903
904 // Merge the upper and lower halves of Imm and DemandedBits.
905 Imm |= Hi;
906 DemandedBits |= DemandedBitsHi;
907 }
908
909 ++NumOptimizedImms;
910
911 // Replicate the element across the register width.
912 while (EltSize < Size) {
913 NewImm |= NewImm << EltSize;
914 EltSize *= 2;
915 }
916
917 (void)OldImm;
918 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
919 "demanded bits should never be altered");
920 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
921
922 // Create the new constant immediate node.
923 EVT VT = Op.getValueType();
924 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000925 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000926
927 // If the new constant immediate is all-zeros or all-ones, let the target
928 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000929 if (NewImm == 0 || NewImm == OrigMask) {
930 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
931 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000932 // Otherwise, create a machine node so that target independent DAG combine
933 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000934 } else {
935 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
936 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
937 New = SDValue(
938 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
939 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000940
941 return TLO.CombineTo(Op, New);
942}
943
944bool AArch64TargetLowering::targetShrinkDemandedConstant(
945 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
946 // Delay this optimization to as late as possible.
947 if (!TLO.LegalOps)
948 return false;
949
950 if (!EnableOptimizeLogicalImm)
951 return false;
952
953 EVT VT = Op.getValueType();
954 if (VT.isVector())
955 return false;
956
957 unsigned Size = VT.getSizeInBits();
958 assert((Size == 32 || Size == 64) &&
959 "i32 or i64 is expected after legalization.");
960
961 // Exit early if we demand all bits.
962 if (Demanded.countPopulation() == Size)
963 return false;
964
965 unsigned NewOpc;
966 switch (Op.getOpcode()) {
967 default:
968 return false;
969 case ISD::AND:
970 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
971 break;
972 case ISD::OR:
973 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
974 break;
975 case ISD::XOR:
976 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
977 break;
978 }
979 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
980 if (!C)
981 return false;
982 uint64_t Imm = C->getZExtValue();
983 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
984}
985
Tim Northover3b0846e2014-05-24 12:50:23 +0000986/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000987/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000988void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000989 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000990 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000991 switch (Op.getOpcode()) {
992 default:
993 break;
994 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000995 KnownBits Known2;
Simon Pilgrim148957f2018-12-21 15:05:10 +0000996 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
997 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
Craig Topperd0af7e82017-04-28 05:31:46 +0000998 Known.Zero &= Known2.Zero;
999 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +00001000 break;
1001 }
1002 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +00001003 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001004 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1005 switch (IntID) {
1006 default: return;
1007 case Intrinsic::aarch64_ldaxr:
1008 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +00001009 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001010 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +00001011 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +00001012 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +00001013 return;
1014 }
1015 }
1016 break;
1017 }
1018 case ISD::INTRINSIC_WO_CHAIN:
1019 case ISD::INTRINSIC_VOID: {
1020 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1021 switch (IntNo) {
1022 default:
1023 break;
1024 case Intrinsic::aarch64_neon_umaxv:
1025 case Intrinsic::aarch64_neon_uminv: {
1026 // Figure out the datatype of the vector operand. The UMINV instruction
1027 // will zero extend the result, so we can mark as known zero all the
1028 // bits larger than the element datatype. 32-bit or larget doesn't need
1029 // this as those are legal types and will be handled by isel directly.
1030 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001031 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001032 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1033 assert(BitWidth >= 8 && "Unexpected width!");
1034 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001035 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001036 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1037 assert(BitWidth >= 16 && "Unexpected width!");
1038 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001039 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001040 }
1041 break;
1042 } break;
1043 }
1044 }
1045 }
1046}
1047
Mehdi Aminieaabc512015-07-09 15:12:23 +00001048MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1049 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001050 return MVT::i64;
1051}
1052
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001053bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1054 unsigned AddrSpace,
1055 unsigned Align,
1056 bool *Fast) const {
1057 if (Subtarget->requiresStrictAlign())
1058 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001059
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001060 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001061 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1062 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001063 // See comments in performSTORECombine() for more details about
1064 // these conditions.
1065
1066 // Code that uses clang vector extensions can mark that it
1067 // wants unaligned accesses to be treated as fast by
1068 // underspecifying alignment to be 1 or 2.
1069 Align <= 2 ||
1070
1071 // Disregard v2i64. Memcpy lowering produces those and splitting
1072 // them regresses performance on micro-benchmarks and olden/bh.
1073 VT == MVT::v2i64;
1074 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001075 return true;
1076}
1077
Tim Northover3b0846e2014-05-24 12:50:23 +00001078FastISel *
1079AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1080 const TargetLibraryInfo *libInfo) const {
1081 return AArch64::createFastISel(funcInfo, libInfo);
1082}
1083
1084const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001085 switch ((AArch64ISD::NodeType)Opcode) {
1086 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001087 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1088 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
David Green9dd1d452018-08-22 11:31:39 +00001089 case AArch64ISD::ADR: return "AArch64ISD::ADR";
Tim Northover3b0846e2014-05-24 12:50:23 +00001090 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1091 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1092 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1093 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1094 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1095 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1096 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1097 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1098 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1099 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001100 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001101 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1102 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1103 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1104 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1105 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1106 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1107 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001108 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1109 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1110 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001111 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001112 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1113 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1114 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1115 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1116 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1117 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1118 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1119 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1120 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1121 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1122 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1123 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1124 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1125 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1126 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1127 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1128 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1129 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1130 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1131 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1132 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1133 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1134 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1135 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1136 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1137 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1138 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1139 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1140 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1141 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1142 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1143 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1144 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1145 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1146 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1147 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1148 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1149 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1150 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1151 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1152 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1153 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1154 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1155 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1156 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1157 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1158 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1159 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001160 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1161 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1162 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1163 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1164 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1165 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001166 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1167 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1168 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1169 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1170 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1171 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1172 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001173 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001174 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1175 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001176 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001177 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1178 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1179 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1180 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1181 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1182 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1183 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1184 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1185 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1186 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1187 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1188 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1189 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1190 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1191 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1192 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1193 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1194 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1195 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1196 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1197 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1198 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1199 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1200 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1201 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1202 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1203 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1204 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1205 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001206 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1207 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001208 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001209 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1210 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1211 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001212 }
Matthias Braund04893f2015-05-07 21:33:59 +00001213 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001214}
1215
1216MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001217AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001218 MachineBasicBlock *MBB) const {
1219 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1220 // phi node:
1221
1222 // OrigBB:
1223 // [... previous instrs leading to comparison ...]
1224 // b.ne TrueBB
1225 // b EndBB
1226 // TrueBB:
1227 // ; Fallthrough
1228 // EndBB:
1229 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1230
Tim Northover3b0846e2014-05-24 12:50:23 +00001231 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001232 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001233 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001234 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001235 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001236
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001237 unsigned DestReg = MI.getOperand(0).getReg();
1238 unsigned IfTrueReg = MI.getOperand(1).getReg();
1239 unsigned IfFalseReg = MI.getOperand(2).getReg();
1240 unsigned CondCode = MI.getOperand(3).getImm();
1241 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001242
1243 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1244 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245 MF->insert(It, TrueBB);
1246 MF->insert(It, EndBB);
1247
1248 // Transfer rest of current basic-block to EndBB
1249 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1250 MBB->end());
1251 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1252
1253 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1254 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1255 MBB->addSuccessor(TrueBB);
1256 MBB->addSuccessor(EndBB);
1257
1258 // TrueBB falls through to the end.
1259 TrueBB->addSuccessor(EndBB);
1260
1261 if (!NZCVKilled) {
1262 TrueBB->addLiveIn(AArch64::NZCV);
1263 EndBB->addLiveIn(AArch64::NZCV);
1264 }
1265
1266 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1267 .addReg(IfTrueReg)
1268 .addMBB(TrueBB)
1269 .addReg(IfFalseReg)
1270 .addMBB(MBB);
1271
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001272 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001273 return EndBB;
1274}
1275
Eli Friedmanad1151c2018-11-09 23:33:30 +00001276MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1277 MachineInstr &MI, MachineBasicBlock *BB) const {
1278 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1279 BB->getParent()->getFunction().getPersonalityFn())) &&
1280 "SEH does not use catchret!");
1281 return BB;
1282}
1283
1284MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1285 MachineInstr &MI, MachineBasicBlock *BB) const {
1286 MI.eraseFromParent();
1287 return BB;
1288}
1289
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001290MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1291 MachineInstr &MI, MachineBasicBlock *BB) const {
1292 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001293 default:
1294#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001295 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001296#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001297 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001298
1299 case AArch64::F128CSEL:
1300 return EmitF128CSEL(MI, BB);
1301
1302 case TargetOpcode::STACKMAP:
1303 case TargetOpcode::PATCHPOINT:
1304 return emitPatchPoint(MI, BB);
Eli Friedmanad1151c2018-11-09 23:33:30 +00001305
1306 case AArch64::CATCHRET:
1307 return EmitLoweredCatchRet(MI, BB);
1308 case AArch64::CATCHPAD:
1309 return EmitLoweredCatchPad(MI, BB);
Tim Northover3b0846e2014-05-24 12:50:23 +00001310 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001311}
1312
1313//===----------------------------------------------------------------------===//
1314// AArch64 Lowering private implementation.
1315//===----------------------------------------------------------------------===//
1316
1317//===----------------------------------------------------------------------===//
1318// Lowering Code
1319//===----------------------------------------------------------------------===//
1320
1321/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1322/// CC
1323static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1324 switch (CC) {
1325 default:
1326 llvm_unreachable("Unknown condition code!");
1327 case ISD::SETNE:
1328 return AArch64CC::NE;
1329 case ISD::SETEQ:
1330 return AArch64CC::EQ;
1331 case ISD::SETGT:
1332 return AArch64CC::GT;
1333 case ISD::SETGE:
1334 return AArch64CC::GE;
1335 case ISD::SETLT:
1336 return AArch64CC::LT;
1337 case ISD::SETLE:
1338 return AArch64CC::LE;
1339 case ISD::SETUGT:
1340 return AArch64CC::HI;
1341 case ISD::SETUGE:
1342 return AArch64CC::HS;
1343 case ISD::SETULT:
1344 return AArch64CC::LO;
1345 case ISD::SETULE:
1346 return AArch64CC::LS;
1347 }
1348}
1349
1350/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1351static void changeFPCCToAArch64CC(ISD::CondCode CC,
1352 AArch64CC::CondCode &CondCode,
1353 AArch64CC::CondCode &CondCode2) {
1354 CondCode2 = AArch64CC::AL;
1355 switch (CC) {
1356 default:
1357 llvm_unreachable("Unknown FP condition!");
1358 case ISD::SETEQ:
1359 case ISD::SETOEQ:
1360 CondCode = AArch64CC::EQ;
1361 break;
1362 case ISD::SETGT:
1363 case ISD::SETOGT:
1364 CondCode = AArch64CC::GT;
1365 break;
1366 case ISD::SETGE:
1367 case ISD::SETOGE:
1368 CondCode = AArch64CC::GE;
1369 break;
1370 case ISD::SETOLT:
1371 CondCode = AArch64CC::MI;
1372 break;
1373 case ISD::SETOLE:
1374 CondCode = AArch64CC::LS;
1375 break;
1376 case ISD::SETONE:
1377 CondCode = AArch64CC::MI;
1378 CondCode2 = AArch64CC::GT;
1379 break;
1380 case ISD::SETO:
1381 CondCode = AArch64CC::VC;
1382 break;
1383 case ISD::SETUO:
1384 CondCode = AArch64CC::VS;
1385 break;
1386 case ISD::SETUEQ:
1387 CondCode = AArch64CC::EQ;
1388 CondCode2 = AArch64CC::VS;
1389 break;
1390 case ISD::SETUGT:
1391 CondCode = AArch64CC::HI;
1392 break;
1393 case ISD::SETUGE:
1394 CondCode = AArch64CC::PL;
1395 break;
1396 case ISD::SETLT:
1397 case ISD::SETULT:
1398 CondCode = AArch64CC::LT;
1399 break;
1400 case ISD::SETLE:
1401 case ISD::SETULE:
1402 CondCode = AArch64CC::LE;
1403 break;
1404 case ISD::SETNE:
1405 case ISD::SETUNE:
1406 CondCode = AArch64CC::NE;
1407 break;
1408 }
1409}
1410
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001411/// Convert a DAG fp condition code to an AArch64 CC.
1412/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1413/// should be AND'ed instead of OR'ed.
1414static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1415 AArch64CC::CondCode &CondCode,
1416 AArch64CC::CondCode &CondCode2) {
1417 CondCode2 = AArch64CC::AL;
1418 switch (CC) {
1419 default:
1420 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1421 assert(CondCode2 == AArch64CC::AL);
1422 break;
1423 case ISD::SETONE:
1424 // (a one b)
1425 // == ((a olt b) || (a ogt b))
1426 // == ((a ord b) && (a une b))
1427 CondCode = AArch64CC::VC;
1428 CondCode2 = AArch64CC::NE;
1429 break;
1430 case ISD::SETUEQ:
1431 // (a ueq b)
1432 // == ((a uno b) || (a oeq b))
1433 // == ((a ule b) && (a uge b))
1434 CondCode = AArch64CC::PL;
1435 CondCode2 = AArch64CC::LE;
1436 break;
1437 }
1438}
1439
Tim Northover3b0846e2014-05-24 12:50:23 +00001440/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1441/// CC usable with the vector instructions. Fewer operations are available
1442/// without a real NZCV register, so we have to use less efficient combinations
1443/// to get the same effect.
1444static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1445 AArch64CC::CondCode &CondCode,
1446 AArch64CC::CondCode &CondCode2,
1447 bool &Invert) {
1448 Invert = false;
1449 switch (CC) {
1450 default:
1451 // Mostly the scalar mappings work fine.
1452 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1453 break;
1454 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001455 Invert = true;
1456 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001457 case ISD::SETO:
1458 CondCode = AArch64CC::MI;
1459 CondCode2 = AArch64CC::GE;
1460 break;
1461 case ISD::SETUEQ:
1462 case ISD::SETULT:
1463 case ISD::SETULE:
1464 case ISD::SETUGT:
1465 case ISD::SETUGE:
1466 // All of the compare-mask comparisons are ordered, but we can switch
1467 // between the two by a double inversion. E.g. ULE == !OGT.
1468 Invert = true;
1469 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1470 break;
1471 }
1472}
1473
1474static bool isLegalArithImmed(uint64_t C) {
1475 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001476 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001477 LLVM_DEBUG(dbgs() << "Is imm " << C
1478 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001479 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001480}
1481
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001482// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1483// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1484// can be set differently by this operation. It comes down to whether
1485// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1486// everything is fine. If not then the optimization is wrong. Thus general
1487// comparisons are only valid if op2 != 0.
1488//
1489// So, finally, the only LLVM-native comparisons that don't mention C and V
1490// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1491// the absence of information about op2.
1492static bool isCMN(SDValue Op, ISD::CondCode CC) {
1493 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1494 (CC == ISD::SETEQ || CC == ISD::SETNE);
1495}
1496
Tim Northover3b0846e2014-05-24 12:50:23 +00001497static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001498 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001499 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001500 const bool FullFP16 =
1501 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001502
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001503 if (VT.isFloatingPoint()) {
1504 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001505 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001506 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1507 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001508 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001509 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001510 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001511 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001512
1513 // The CMP instruction is just an alias for SUBS, and representing it as
1514 // SUBS means that it's possible to get CSE with subtract operations.
1515 // A later phase can perform the optimization of setting the destination
1516 // register to WZR/XZR if it ends up being unused.
1517 unsigned Opcode = AArch64ISD::SUBS;
1518
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001519 if (isCMN(RHS, CC)) {
1520 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
Tim Northover3b0846e2014-05-24 12:50:23 +00001521 Opcode = AArch64ISD::ADDS;
1522 RHS = RHS.getOperand(1);
Arnaud A. de Grandmaisondfe86102018-12-13 10:31:32 +00001523 } else if (isCMN(LHS, CC)) {
1524 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1525 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1526 Opcode = AArch64ISD::ADDS;
1527 LHS = LHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001528 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001529 !isUnsignedIntSetCC(CC)) {
1530 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1531 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1532 // of the signed comparisons.
1533 Opcode = AArch64ISD::ANDS;
1534 RHS = LHS.getOperand(1);
1535 LHS = LHS.getOperand(0);
1536 }
1537
Matthias Braunaf7d7702015-07-16 20:02:37 +00001538 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001539 .getValue(1);
1540}
1541
Matthias Braunaf7d7702015-07-16 20:02:37 +00001542/// \defgroup AArch64CCMP CMP;CCMP matching
1543///
1544/// These functions deal with the formation of CMP;CCMP;... sequences.
1545/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1546/// a comparison. They set the NZCV flags to a predefined value if their
1547/// predicate is false. This allows to express arbitrary conjunctions, for
Matthias Braun96d12512018-11-06 03:15:22 +00001548/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
Matthias Braunaf7d7702015-07-16 20:02:37 +00001549/// expressed as:
1550/// cmp A
1551/// ccmp B, inv(CB), CA
1552/// check for CB flags
1553///
Matthias Braund0412122018-12-06 01:40:23 +00001554/// This naturally lets us implement chains of AND operations with SETCC
1555/// operands. And we can even implement some other situations by transforming
1556/// them:
1557/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1558/// negating the flags used in a CCMP/FCCMP operations.
1559/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1560/// by negating the flags we test for afterwards. i.e.
1561/// NEG (CMP CCMP CCCMP ...) can be implemented.
1562/// - Note that we can only ever negate all previously processed results.
1563/// What we can not implement by flipping the flags to test is a negation
1564/// of two sub-trees (because the negation affects all sub-trees emitted so
1565/// far, so the 2nd sub-tree we emit would also affect the first).
1566/// With those tools we can implement some OR operations:
1567/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1568/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1569/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1570/// elimination rules from earlier to implement the whole thing as a
1571/// CCMP/FCCMP chain.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001572///
Matthias Braund0412122018-12-06 01:40:23 +00001573/// As complete example:
1574/// or (or (setCA (cmp A)) (setCB (cmp B)))
1575/// (and (setCC (cmp C)) (setCD (cmp D)))"
1576/// can be reassociated to:
1577/// or (and (setCC (cmp C)) setCD (cmp D))
1578// (or (setCA (cmp A)) (setCB (cmp B)))
1579/// can be transformed to:
1580/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1581/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1582/// which can be implemented as:
Matthias Braunaf7d7702015-07-16 20:02:37 +00001583/// cmp C
1584/// ccmp D, inv(CD), CC
1585/// ccmp A, CA, inv(CD)
1586/// ccmp B, CB, inv(CA)
1587/// check for CB flags
Matthias Braund0412122018-12-06 01:40:23 +00001588///
1589/// A counterexample is "or (and A B) (and C D)" which translates to
1590/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1591/// can only implement 1 of the inner (not) operations, but not both!
Matthias Braunaf7d7702015-07-16 20:02:37 +00001592/// @{
1593
Geoff Berrye41c2df2015-07-20 22:03:52 +00001594/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001595static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1596 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001597 AArch64CC::CondCode Predicate,
1598 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001599 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001600 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001601 const bool FullFP16 =
1602 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1603
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001604 if (LHS.getValueType().isFloatingPoint()) {
1605 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001606 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001607 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1608 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1609 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001610 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001611 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001612 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001613 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001614 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1615 Opcode = AArch64ISD::CCMN;
1616 RHS = RHS.getOperand(1);
1617 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001618 }
1619 if (Opcode == 0)
1620 Opcode = AArch64ISD::CCMP;
1621
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001622 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1623 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1624 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001625 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1626 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1627}
1628
Matthias Braun96d12512018-11-06 03:15:22 +00001629/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1630/// expressed as a conjunction. See \ref AArch64CCMP.
Matthias Braund0412122018-12-06 01:40:23 +00001631/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1632/// changing the conditions on the SETCC tests.
1633/// (this means we can call emitConjunctionRec() with
1634/// Negate==true on this sub-tree)
1635/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1636/// cannot do the negation naturally. We are required to
1637/// emit the subtree first in this case.
1638/// \param WillNegate Is true if are called when the result of this
1639/// subexpression must be negated. This happens when the
1640/// outer expression is an OR. We can use this fact to know
1641/// that we have a double negation (or (or ...) ...) that
1642/// can be implemented for free.
Matthias Braun96d12512018-11-06 03:15:22 +00001643static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
Matthias Braund0412122018-12-06 01:40:23 +00001644 bool &MustBeFirst, bool WillNegate,
Matthias Braun96d12512018-11-06 03:15:22 +00001645 unsigned Depth = 0) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001646 if (!Val.hasOneUse())
1647 return false;
1648 unsigned Opcode = Val->getOpcode();
1649 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001650 if (Val->getOperand(0).getValueType() == MVT::f128)
1651 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001652 CanNegate = true;
Matthias Braund0412122018-12-06 01:40:23 +00001653 MustBeFirst = false;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001654 return true;
1655 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001656 // Protect against exponential runtime and stack overflow.
1657 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001658 return false;
1659 if (Opcode == ISD::AND || Opcode == ISD::OR) {
Matthias Braund0412122018-12-06 01:40:23 +00001660 bool IsOR = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001661 SDValue O0 = Val->getOperand(0);
1662 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001663 bool CanNegateL;
Matthias Braund0412122018-12-06 01:40:23 +00001664 bool MustBeFirstL;
1665 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001666 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001667 bool CanNegateR;
Matthias Braund0412122018-12-06 01:40:23 +00001668 bool MustBeFirstR;
1669 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001670 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001671
Matthias Braund0412122018-12-06 01:40:23 +00001672 if (MustBeFirstL && MustBeFirstR)
1673 return false;
1674
1675 if (IsOR) {
1676 // For an OR expression we need to be able to naturally negate at least
1677 // one side or we cannot do the transformation at all.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001678 if (!CanNegateL && !CanNegateR)
1679 return false;
Matthias Braund0412122018-12-06 01:40:23 +00001680 // If we the result of the OR will be negated and we can naturally negate
1681 // the leafs, then this sub-tree as a whole negates naturally.
1682 CanNegate = WillNegate && CanNegateL && CanNegateR;
1683 // If we cannot naturally negate the whole sub-tree, then this must be
1684 // emitted first.
1685 MustBeFirst = !CanNegate;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001686 } else {
Matthias Braund0412122018-12-06 01:40:23 +00001687 assert(Opcode == ISD::AND && "Must be OR or AND");
1688 // We cannot naturally negate an AND operation.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001689 CanNegate = false;
Matthias Braund0412122018-12-06 01:40:23 +00001690 MustBeFirst = MustBeFirstL || MustBeFirstR;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001691 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001692 return true;
1693 }
1694 return false;
1695}
1696
1697/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1698/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1699/// Tries to transform the given i1 producing node @p Val to a series compare
1700/// and conditional compare operations. @returns an NZCV flags producing node
1701/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1702/// transformation was not possible.
Matthias Braund0412122018-12-06 01:40:23 +00001703/// \p Negate is true if we want this sub-tree being negated just by changing
1704/// SETCC conditions.
Matthias Braun96d12512018-11-06 03:15:22 +00001705static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
Matthias Braunfdef49b2016-01-23 04:05:22 +00001706 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001707 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001708 // We're at a tree leaf, produce a conditional comparison operation.
1709 unsigned Opcode = Val->getOpcode();
1710 if (Opcode == ISD::SETCC) {
1711 SDValue LHS = Val->getOperand(0);
1712 SDValue RHS = Val->getOperand(1);
1713 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1714 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001715 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001716 CC = getSetCCInverse(CC, isInteger);
1717 SDLoc DL(Val);
1718 // Determine OutCC and handle FP special case.
1719 if (isInteger) {
1720 OutCC = changeIntCCToAArch64CC(CC);
1721 } else {
1722 assert(LHS.getValueType().isFloatingPoint());
1723 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001724 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1725 // Some floating point conditions can't be tested with a single condition
1726 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001727 if (ExtraCC != AArch64CC::AL) {
1728 SDValue ExtraCmp;
1729 if (!CCOp.getNode())
1730 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001731 else
1732 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001733 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001734 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001735 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001736 }
1737 }
1738
1739 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001740 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001741 return emitComparison(LHS, RHS, CC, DL, DAG);
1742 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001743 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001744 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001745 }
Matthias Braund0412122018-12-06 01:40:23 +00001746 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001747
Matthias Braund0412122018-12-06 01:40:23 +00001748 bool IsOR = Opcode == ISD::OR;
1749
Matthias Braunaf7d7702015-07-16 20:02:37 +00001750 SDValue LHS = Val->getOperand(0);
Matthias Braund0412122018-12-06 01:40:23 +00001751 bool CanNegateL;
1752 bool MustBeFirstL;
1753 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1754 assert(ValidL && "Valid conjunction/disjunction tree");
1755 (void)ValidL;
1756
Matthias Braunaf7d7702015-07-16 20:02:37 +00001757 SDValue RHS = Val->getOperand(1);
Matthias Braund0412122018-12-06 01:40:23 +00001758 bool CanNegateR;
1759 bool MustBeFirstR;
1760 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1761 assert(ValidR && "Valid conjunction/disjunction tree");
1762 (void)ValidR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001763
Matthias Braund0412122018-12-06 01:40:23 +00001764 // Swap sub-tree that must come first to the right side.
1765 if (MustBeFirstL) {
1766 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1767 std::swap(LHS, RHS);
1768 std::swap(CanNegateL, CanNegateR);
1769 std::swap(MustBeFirstL, MustBeFirstR);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001770 }
1771
Matthias Braund0412122018-12-06 01:40:23 +00001772 bool NegateR;
1773 bool NegateAfterR;
1774 bool NegateL;
1775 bool NegateAfterAll;
1776 if (Opcode == ISD::OR) {
1777 // Swap the sub-tree that we can negate naturally to the left.
1778 if (!CanNegateL) {
1779 assert(CanNegateR && "at least one side must be negatable");
1780 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1781 assert(!Negate);
1782 std::swap(LHS, RHS);
1783 NegateR = false;
1784 NegateAfterR = true;
1785 } else {
1786 // Negate the left sub-tree if possible, otherwise negate the result.
1787 NegateR = CanNegateR;
1788 NegateAfterR = !CanNegateR;
1789 }
1790 NegateL = true;
1791 NegateAfterAll = !Negate;
1792 } else {
1793 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1794 assert(!Negate && "Valid conjunction/disjunction tree");
1795
1796 NegateL = false;
1797 NegateR = false;
1798 NegateAfterR = false;
1799 NegateAfterAll = false;
1800 }
1801
1802 // Emit sub-trees.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001803 AArch64CC::CondCode RHSCC;
Matthias Braund0412122018-12-06 01:40:23 +00001804 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1805 if (NegateAfterR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001806 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braund0412122018-12-06 01:40:23 +00001807 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1808 if (NegateAfterAll)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001809 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1810 return CmpL;
1811}
1812
Matthias Braun96d12512018-11-06 03:15:22 +00001813/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1814/// In some cases this is even possible with OR operations in the expression.
1815/// See \ref AArch64CCMP.
1816/// \see emitConjunctionRec().
1817static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1818 AArch64CC::CondCode &OutCC) {
1819 bool DummyCanNegate;
Matthias Braund0412122018-12-06 01:40:23 +00001820 bool DummyMustBeFirst;
1821 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
Matthias Braunfdef49b2016-01-23 04:05:22 +00001822 return SDValue();
1823
Matthias Braun96d12512018-11-06 03:15:22 +00001824 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001825}
1826
Matthias Braunaf7d7702015-07-16 20:02:37 +00001827/// @}
1828
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001829/// Returns how profitable it is to fold a comparison's operand's shift and/or
1830/// extension operations.
1831static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1832 auto isSupportedExtend = [&](SDValue V) {
1833 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1834 return true;
1835
1836 if (V.getOpcode() == ISD::AND)
1837 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1838 uint64_t Mask = MaskCst->getZExtValue();
1839 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1840 }
1841
1842 return false;
1843 };
1844
1845 if (!Op.hasOneUse())
1846 return 0;
1847
1848 if (isSupportedExtend(Op))
1849 return 1;
1850
1851 unsigned Opc = Op.getOpcode();
1852 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1853 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1854 uint64_t Shift = ShiftCst->getZExtValue();
1855 if (isSupportedExtend(Op.getOperand(0)))
1856 return (Shift <= 4) ? 2 : 1;
1857 EVT VT = Op.getValueType();
1858 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1859 return 1;
1860 }
1861
1862 return 0;
1863}
1864
Tim Northover3b0846e2014-05-24 12:50:23 +00001865static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001866 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001867 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001868 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1869 EVT VT = RHS.getValueType();
1870 uint64_t C = RHSC->getZExtValue();
1871 if (!isLegalArithImmed(C)) {
1872 // Constant does not fit, try adjusting it by one?
1873 switch (CC) {
1874 default:
1875 break;
1876 case ISD::SETLT:
1877 case ISD::SETGE:
1878 if ((VT == MVT::i32 && C != 0x80000000 &&
1879 isLegalArithImmed((uint32_t)(C - 1))) ||
1880 (VT == MVT::i64 && C != 0x80000000ULL &&
1881 isLegalArithImmed(C - 1ULL))) {
1882 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1883 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001884 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001885 }
1886 break;
1887 case ISD::SETULT:
1888 case ISD::SETUGE:
1889 if ((VT == MVT::i32 && C != 0 &&
1890 isLegalArithImmed((uint32_t)(C - 1))) ||
1891 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1892 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1893 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001894 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001895 }
1896 break;
1897 case ISD::SETLE:
1898 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001899 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001900 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001901 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001902 isLegalArithImmed(C + 1ULL))) {
1903 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1904 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001905 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001906 }
1907 break;
1908 case ISD::SETULE:
1909 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001910 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001911 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001912 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001913 isLegalArithImmed(C + 1ULL))) {
1914 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1915 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001916 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001917 }
1918 break;
1919 }
1920 }
1921 }
Arnaud A. de Grandmaison162435e2018-10-13 07:43:56 +00001922
1923 // Comparisons are canonicalized so that the RHS operand is simpler than the
1924 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1925 // can fold some shift+extend operations on the RHS operand, so swap the
1926 // operands if that can be done.
1927 //
1928 // For example:
1929 // lsl w13, w11, #1
1930 // cmp w13, w12
1931 // can be turned into:
1932 // cmp w12, w11, lsl #1
1933 if (!isa<ConstantSDNode>(RHS) ||
1934 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1935 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1936
1937 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1938 std::swap(LHS, RHS);
1939 CC = ISD::getSetCCSwappedOperands(CC);
1940 }
1941 }
1942
Matthias Braunaf7d7702015-07-16 20:02:37 +00001943 SDValue Cmp;
1944 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001945 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001946 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1947
1948 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1949 // For the i8 operand, the largest immediate is 255, so this can be easily
1950 // encoded in the compare instruction. For the i16 operand, however, the
1951 // largest immediate cannot be encoded in the compare.
1952 // Therefore, use a sign extending load and cmn to avoid materializing the
1953 // -1 constant. For example,
1954 // movz w1, #65535
1955 // ldrh w0, [x0, #0]
1956 // cmp w0, w1
1957 // >
1958 // ldrsh w0, [x0, #0]
1959 // cmn w0, #1
1960 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1961 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001962 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001963 // transformation is profitable.
1964 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1965 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1966 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1967 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1968 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1969 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1970 SDValue SExt =
1971 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1972 DAG.getValueType(MVT::i16));
1973 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1974 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001975 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001976 AArch64CC = changeIntCCToAArch64CC(CC);
1977 }
1978 }
1979
1980 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Matthias Braun96d12512018-11-06 03:15:22 +00001981 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001982 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1983 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001984 }
1985 }
1986 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001987
1988 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001989 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001990 AArch64CC = changeIntCCToAArch64CC(CC);
1991 }
1992 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001993 return Cmp;
1994}
1995
1996static std::pair<SDValue, SDValue>
1997getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1998 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1999 "Unsupported value type");
2000 SDValue Value, Overflow;
2001 SDLoc DL(Op);
2002 SDValue LHS = Op.getOperand(0);
2003 SDValue RHS = Op.getOperand(1);
2004 unsigned Opc = 0;
2005 switch (Op.getOpcode()) {
2006 default:
2007 llvm_unreachable("Unknown overflow instruction!");
2008 case ISD::SADDO:
2009 Opc = AArch64ISD::ADDS;
2010 CC = AArch64CC::VS;
2011 break;
2012 case ISD::UADDO:
2013 Opc = AArch64ISD::ADDS;
2014 CC = AArch64CC::HS;
2015 break;
2016 case ISD::SSUBO:
2017 Opc = AArch64ISD::SUBS;
2018 CC = AArch64CC::VS;
2019 break;
2020 case ISD::USUBO:
2021 Opc = AArch64ISD::SUBS;
2022 CC = AArch64CC::LO;
2023 break;
2024 // Multiply needs a little bit extra work.
2025 case ISD::SMULO:
2026 case ISD::UMULO: {
2027 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00002028 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00002029 if (Op.getValueType() == MVT::i32) {
2030 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2031 // For a 32 bit multiply with overflow check we want the instruction
2032 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2033 // need to generate the following pattern:
2034 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2035 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2036 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2037 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2038 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002039 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002040 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2041 // operation. We need to clear out the upper 32 bits, because we used a
2042 // widening multiply that wrote all 64 bits. In the end this should be a
2043 // noop.
2044 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2045 if (IsSigned) {
2046 // The signed overflow check requires more than just a simple check for
2047 // any bit set in the upper 32 bits of the result. These bits could be
2048 // just the sign bits of a negative number. To perform the overflow
2049 // check we have to arithmetic shift right the 32nd bit of the result by
2050 // 31 bits. Then we compare the result to the upper 32 bits.
2051 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002052 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002053 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2054 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002055 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002056 // It is important that LowerBits is last, otherwise the arithmetic
2057 // shift will not be folded into the compare (SUBS).
2058 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2059 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2060 .getValue(1);
2061 } else {
2062 // The overflow check for unsigned multiply is easy. We only need to
2063 // check if any of the upper 32 bits are set. This can be done with a
2064 // CMP (shifted register). For that we need to generate the following
2065 // pattern:
2066 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2067 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002068 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002069 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2070 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002071 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2072 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002073 UpperBits).getValue(1);
2074 }
2075 break;
2076 }
2077 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2078 // For the 64 bit multiply
2079 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2080 if (IsSigned) {
2081 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2082 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002083 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00002084 // It is important that LowerBits is last, otherwise the arithmetic
2085 // shift will not be folded into the compare (SUBS).
2086 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2087 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2088 .getValue(1);
2089 } else {
2090 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2091 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2092 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002093 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2094 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00002095 UpperBits).getValue(1);
2096 }
2097 break;
2098 }
2099 } // switch (...)
2100
2101 if (Opc) {
2102 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2103
2104 // Emit the AArch64 operation with overflow check.
2105 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2106 Overflow = Value.getValue(1);
2107 }
2108 return std::make_pair(Value, Overflow);
2109}
2110
2111SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2112 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002113 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002114 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002115}
2116
Amara Emerson24ca39c2017-10-09 15:15:09 +00002117// Returns true if the given Op is the overflow flag result of an overflow
2118// intrinsic operation.
2119static bool isOverflowIntrOpRes(SDValue Op) {
2120 unsigned Opc = Op.getOpcode();
2121 return (Op.getResNo() == 1 &&
2122 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2123 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2124}
2125
Tim Northover3b0846e2014-05-24 12:50:23 +00002126static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2127 SDValue Sel = Op.getOperand(0);
2128 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00002129 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00002130
Amara Emerson24ca39c2017-10-09 15:15:09 +00002131 // If the operand is an overflow checking operation, invert the condition
2132 // code and kill the Not operation. I.e., transform:
2133 // (xor (overflow_op_bool, 1))
2134 // -->
2135 // (csel 1, 0, invert(cc), overflow_op_bool)
2136 // ... which later gets transformed to just a cset instruction with an
2137 // inverted condition code, rather than a cset + eor sequence.
2138 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2139 // Only lower legal XALUO ops.
2140 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2141 return SDValue();
2142
2143 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2144 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2145 AArch64CC::CondCode CC;
2146 SDValue Value, Overflow;
2147 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2148 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2149 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2150 CCVal, Overflow);
2151 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002152 // If neither operand is a SELECT_CC, give up.
2153 if (Sel.getOpcode() != ISD::SELECT_CC)
2154 std::swap(Sel, Other);
2155 if (Sel.getOpcode() != ISD::SELECT_CC)
2156 return Op;
2157
2158 // The folding we want to perform is:
2159 // (xor x, (select_cc a, b, cc, 0, -1) )
2160 // -->
2161 // (csel x, (xor x, -1), cc ...)
2162 //
2163 // The latter will get matched to a CSINV instruction.
2164
2165 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2166 SDValue LHS = Sel.getOperand(0);
2167 SDValue RHS = Sel.getOperand(1);
2168 SDValue TVal = Sel.getOperand(2);
2169 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002170
2171 // FIXME: This could be generalized to non-integer comparisons.
2172 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2173 return Op;
2174
2175 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2176 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2177
Eric Christopher572e03a2015-06-19 01:53:21 +00002178 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002179 if (!CFVal || !CTVal)
2180 return Op;
2181
2182 // We can commute the SELECT_CC by inverting the condition. This
2183 // might be needed to make this fit into a CSINV pattern.
2184 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2185 std::swap(TVal, FVal);
2186 std::swap(CTVal, CFVal);
2187 CC = ISD::getSetCCInverse(CC, true);
2188 }
2189
2190 // If the constants line up, perform the transform!
2191 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2192 SDValue CCVal;
2193 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2194
2195 FVal = Other;
2196 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002197 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002198
2199 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2200 CCVal, Cmp);
2201 }
2202
2203 return Op;
2204}
2205
2206static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2207 EVT VT = Op.getValueType();
2208
2209 // Let legalize expand this if it isn't a legal type yet.
2210 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2211 return SDValue();
2212
2213 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2214
2215 unsigned Opc;
2216 bool ExtraOp = false;
2217 switch (Op.getOpcode()) {
2218 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002219 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002220 case ISD::ADDC:
2221 Opc = AArch64ISD::ADDS;
2222 break;
2223 case ISD::SUBC:
2224 Opc = AArch64ISD::SUBS;
2225 break;
2226 case ISD::ADDE:
2227 Opc = AArch64ISD::ADCS;
2228 ExtraOp = true;
2229 break;
2230 case ISD::SUBE:
2231 Opc = AArch64ISD::SBCS;
2232 ExtraOp = true;
2233 break;
2234 }
2235
2236 if (!ExtraOp)
2237 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2238 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2239 Op.getOperand(2));
2240}
2241
2242static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2243 // Let legalize expand this if it isn't a legal type yet.
2244 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2245 return SDValue();
2246
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002247 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002248 AArch64CC::CondCode CC;
2249 // The actual operation that sets the overflow or carry flag.
2250 SDValue Value, Overflow;
2251 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2252
2253 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002254 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2255 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002256
2257 // We use an inverted condition, because the conditional select is inverted
2258 // too. This will allow it to be selected to a single instruction:
2259 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002260 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2261 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002262 CCVal, Overflow);
2263
2264 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002265 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002266}
2267
2268// Prefetch operands are:
2269// 1: Address to prefetch
2270// 2: bool isWrite
2271// 3: int locality (0 = no locality ... 3 = extreme locality)
2272// 4: bool isDataCache
2273static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2274 SDLoc DL(Op);
2275 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2276 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002277 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002278
2279 bool IsStream = !Locality;
2280 // When the locality number is set
2281 if (Locality) {
2282 // The front-end should have filtered out the out-of-range values
2283 assert(Locality <= 3 && "Prefetch locality out-of-range");
2284 // The locality degree is the opposite of the cache speed.
2285 // Put the number the other way around.
2286 // The encoding starts at 0 for level 1
2287 Locality = 3 - Locality;
2288 }
2289
2290 // built the mask value encoding the expected behavior.
2291 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002292 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002293 (Locality << 1) | // Cache level bits
2294 (unsigned)IsStream; // Stream bit
2295 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002296 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002297}
2298
2299SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2300 SelectionDAG &DAG) const {
2301 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2302
2303 RTLIB::Libcall LC;
2304 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2305
2306 return LowerF128Call(Op, DAG, LC);
2307}
2308
2309SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2310 SelectionDAG &DAG) const {
2311 if (Op.getOperand(0).getValueType() != MVT::f128) {
2312 // It's legal except when f128 is involved
2313 return Op;
2314 }
2315
2316 RTLIB::Libcall LC;
2317 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2318
2319 // FP_ROUND node has a second operand indicating whether it is known to be
2320 // precise. That doesn't take part in the LibCall so we can't directly use
2321 // LowerF128Call.
2322 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002323 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2324 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002325}
2326
2327static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2328 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2329 // Any additional optimization in this function should be recorded
2330 // in the cost tables.
2331 EVT InVT = Op.getOperand(0).getValueType();
2332 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002333 unsigned NumElts = InVT.getVectorNumElements();
2334
2335 // f16 vectors are promoted to f32 before a conversion.
2336 if (InVT.getVectorElementType() == MVT::f16) {
2337 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2338 SDLoc dl(Op);
2339 return DAG.getNode(
2340 Op.getOpcode(), dl, Op.getValueType(),
2341 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2342 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002343
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002344 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002345 SDLoc dl(Op);
2346 SDValue Cv =
2347 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2348 Op.getOperand(0));
2349 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002350 }
2351
2352 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002353 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002354 MVT ExtVT =
2355 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2356 VT.getVectorNumElements());
2357 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002358 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2359 }
2360
2361 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002362 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002363}
2364
2365SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2366 SelectionDAG &DAG) const {
2367 if (Op.getOperand(0).getValueType().isVector())
2368 return LowerVectorFP_TO_INT(Op, DAG);
2369
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002370 // f16 conversions are promoted to f32 when full fp16 is not supported.
2371 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2372 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002373 SDLoc dl(Op);
2374 return DAG.getNode(
2375 Op.getOpcode(), dl, Op.getValueType(),
2376 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2377 }
2378
Tim Northover3b0846e2014-05-24 12:50:23 +00002379 if (Op.getOperand(0).getValueType() != MVT::f128) {
2380 // It's legal except when f128 is involved
2381 return Op;
2382 }
2383
2384 RTLIB::Libcall LC;
2385 if (Op.getOpcode() == ISD::FP_TO_SINT)
2386 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2387 else
2388 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2389
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002390 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002391 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002392}
2393
2394static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2395 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2396 // Any additional optimization in this function should be recorded
2397 // in the cost tables.
2398 EVT VT = Op.getValueType();
2399 SDLoc dl(Op);
2400 SDValue In = Op.getOperand(0);
2401 EVT InVT = In.getValueType();
2402
Tim Northoveref0d7602014-06-15 09:27:06 +00002403 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2404 MVT CastVT =
2405 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2406 InVT.getVectorNumElements());
2407 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002408 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002409 }
2410
Tim Northoveref0d7602014-06-15 09:27:06 +00002411 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2412 unsigned CastOpc =
2413 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2414 EVT CastVT = VT.changeVectorElementTypeToInteger();
2415 In = DAG.getNode(CastOpc, dl, CastVT, In);
2416 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002417 }
2418
Tim Northoveref0d7602014-06-15 09:27:06 +00002419 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002420}
2421
2422SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2423 SelectionDAG &DAG) const {
2424 if (Op.getValueType().isVector())
2425 return LowerVectorINT_TO_FP(Op, DAG);
2426
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002427 // f16 conversions are promoted to f32 when full fp16 is not supported.
2428 if (Op.getValueType() == MVT::f16 &&
2429 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002430 SDLoc dl(Op);
2431 return DAG.getNode(
2432 ISD::FP_ROUND, dl, MVT::f16,
2433 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002434 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002435 }
2436
Tim Northover3b0846e2014-05-24 12:50:23 +00002437 // i128 conversions are libcalls.
2438 if (Op.getOperand(0).getValueType() == MVT::i128)
2439 return SDValue();
2440
2441 // Other conversions are legal, unless it's to the completely software-based
2442 // fp128.
2443 if (Op.getValueType() != MVT::f128)
2444 return Op;
2445
2446 RTLIB::Libcall LC;
2447 if (Op.getOpcode() == ISD::SINT_TO_FP)
2448 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2449 else
2450 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2451
2452 return LowerF128Call(Op, DAG, LC);
2453}
2454
2455SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2456 SelectionDAG &DAG) const {
2457 // For iOS, we want to call an alternative entry point: __sincos_stret,
2458 // which returns the values in two S / D registers.
2459 SDLoc dl(Op);
2460 SDValue Arg = Op.getOperand(0);
2461 EVT ArgVT = Arg.getValueType();
2462 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2463
2464 ArgListTy Args;
2465 ArgListEntry Entry;
2466
2467 Entry.Node = Arg;
2468 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002469 Entry.IsSExt = false;
2470 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002471 Args.push_back(Entry);
2472
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002473 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2474 : RTLIB::SINCOS_STRET_F32;
2475 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002476 SDValue Callee =
2477 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002478
Serge Gueltone38003f2017-05-09 19:31:13 +00002479 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002480 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002481 CLI.setDebugLoc(dl)
2482 .setChain(DAG.getEntryNode())
2483 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002484
2485 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2486 return CallResult.first;
2487}
2488
Tim Northoverf8bfe212014-07-18 13:07:05 +00002489static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2490 if (Op.getValueType() != MVT::f16)
2491 return SDValue();
2492
2493 assert(Op.getOperand(0).getValueType() == MVT::i16);
2494 SDLoc DL(Op);
2495
2496 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2497 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2498 return SDValue(
2499 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002500 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002501 0);
2502}
2503
Chad Rosierd9d0f862014-10-08 02:31:24 +00002504static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2505 if (OrigVT.getSizeInBits() >= 64)
2506 return OrigVT;
2507
2508 assert(OrigVT.isSimple() && "Expecting a simple value type");
2509
2510 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2511 switch (OrigSimpleTy) {
2512 default: llvm_unreachable("Unexpected Vector Type");
2513 case MVT::v2i8:
2514 case MVT::v2i16:
2515 return MVT::v2i32;
2516 case MVT::v4i8:
2517 return MVT::v4i16;
2518 }
2519}
2520
2521static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2522 const EVT &OrigTy,
2523 const EVT &ExtTy,
2524 unsigned ExtOpcode) {
2525 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2526 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2527 // 64-bits we need to insert a new extension so that it will be 64-bits.
2528 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2529 if (OrigTy.getSizeInBits() >= 64)
2530 return N;
2531
2532 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2533 EVT NewVT = getExtensionTo64Bits(OrigTy);
2534
2535 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2536}
2537
2538static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2539 bool isSigned) {
2540 EVT VT = N->getValueType(0);
2541
2542 if (N->getOpcode() != ISD::BUILD_VECTOR)
2543 return false;
2544
Pete Cooper3af9a252015-06-26 18:17:36 +00002545 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002547 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002548 unsigned HalfSize = EltSize / 2;
2549 if (isSigned) {
2550 if (!isIntN(HalfSize, C->getSExtValue()))
2551 return false;
2552 } else {
2553 if (!isUIntN(HalfSize, C->getZExtValue()))
2554 return false;
2555 }
2556 continue;
2557 }
2558 return false;
2559 }
2560
2561 return true;
2562}
2563
2564static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2565 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2566 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2567 N->getOperand(0)->getValueType(0),
2568 N->getValueType(0),
2569 N->getOpcode());
2570
2571 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2572 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002573 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002574 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002575 unsigned NumElts = VT.getVectorNumElements();
2576 MVT TruncVT = MVT::getIntegerVT(EltSize);
2577 SmallVector<SDValue, 8> Ops;
2578 for (unsigned i = 0; i != NumElts; ++i) {
2579 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2580 const APInt &CInt = C->getAPIntValue();
2581 // Element types smaller than 32 bits are not legal, so use i32 elements.
2582 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002583 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002584 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002585 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002586}
2587
2588static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002589 return N->getOpcode() == ISD::SIGN_EXTEND ||
2590 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002591}
2592
2593static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002594 return N->getOpcode() == ISD::ZERO_EXTEND ||
2595 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002596}
2597
2598static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2599 unsigned Opcode = N->getOpcode();
2600 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2601 SDNode *N0 = N->getOperand(0).getNode();
2602 SDNode *N1 = N->getOperand(1).getNode();
2603 return N0->hasOneUse() && N1->hasOneUse() &&
2604 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2605 }
2606 return false;
2607}
2608
2609static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2610 unsigned Opcode = N->getOpcode();
2611 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2612 SDNode *N0 = N->getOperand(0).getNode();
2613 SDNode *N1 = N->getOperand(1).getNode();
2614 return N0->hasOneUse() && N1->hasOneUse() &&
2615 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2616 }
2617 return false;
2618}
2619
Tim Northover70666e72018-06-20 12:09:01 +00002620SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2621 SelectionDAG &DAG) const {
2622 // The rounding mode is in bits 23:22 of the FPSCR.
2623 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2624 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2625 // so that the shift + and get folded into a bitfield extract.
2626 SDLoc dl(Op);
2627
2628 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2629 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2630 MVT::i64));
2631 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2632 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2633 DAG.getConstant(1U << 22, dl, MVT::i32));
2634 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2635 DAG.getConstant(22, dl, MVT::i32));
2636 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2637 DAG.getConstant(3, dl, MVT::i32));
2638}
2639
Chad Rosierd9d0f862014-10-08 02:31:24 +00002640static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2641 // Multiplications are only custom-lowered for 128-bit vectors so that
2642 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2643 EVT VT = Op.getValueType();
2644 assert(VT.is128BitVector() && VT.isInteger() &&
2645 "unexpected type for custom-lowering ISD::MUL");
2646 SDNode *N0 = Op.getOperand(0).getNode();
2647 SDNode *N1 = Op.getOperand(1).getNode();
2648 unsigned NewOpc = 0;
2649 bool isMLA = false;
2650 bool isN0SExt = isSignExtended(N0, DAG);
2651 bool isN1SExt = isSignExtended(N1, DAG);
2652 if (isN0SExt && isN1SExt)
2653 NewOpc = AArch64ISD::SMULL;
2654 else {
2655 bool isN0ZExt = isZeroExtended(N0, DAG);
2656 bool isN1ZExt = isZeroExtended(N1, DAG);
2657 if (isN0ZExt && isN1ZExt)
2658 NewOpc = AArch64ISD::UMULL;
2659 else if (isN1SExt || isN1ZExt) {
2660 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2661 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2662 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2663 NewOpc = AArch64ISD::SMULL;
2664 isMLA = true;
2665 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2666 NewOpc = AArch64ISD::UMULL;
2667 isMLA = true;
2668 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2669 std::swap(N0, N1);
2670 NewOpc = AArch64ISD::UMULL;
2671 isMLA = true;
2672 }
2673 }
2674
2675 if (!NewOpc) {
2676 if (VT == MVT::v2i64)
2677 // Fall through to expand this. It is not legal.
2678 return SDValue();
2679 else
2680 // Other vector multiplications are legal.
2681 return Op;
2682 }
2683 }
2684
2685 // Legalize to a S/UMULL instruction
2686 SDLoc DL(Op);
2687 SDValue Op0;
2688 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2689 if (!isMLA) {
2690 Op0 = skipExtensionForVectorMULL(N0, DAG);
2691 assert(Op0.getValueType().is64BitVector() &&
2692 Op1.getValueType().is64BitVector() &&
2693 "unexpected types for extended operands to VMULL");
2694 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2695 }
2696 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2697 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2698 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2699 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2700 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2701 EVT Op1VT = Op1.getValueType();
2702 return DAG.getNode(N0->getOpcode(), DL, VT,
2703 DAG.getNode(NewOpc, DL, VT,
2704 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2705 DAG.getNode(NewOpc, DL, VT,
2706 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2707}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002708
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002709SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2710 SelectionDAG &DAG) const {
2711 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2712 SDLoc dl(Op);
2713 switch (IntNo) {
2714 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002715 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002716 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2717 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2718 }
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +00002719 case Intrinsic::aarch64_neon_abs:
2720 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2721 Op.getOperand(1));
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002722 case Intrinsic::aarch64_neon_smax:
2723 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2724 Op.getOperand(1), Op.getOperand(2));
2725 case Intrinsic::aarch64_neon_umax:
2726 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2727 Op.getOperand(1), Op.getOperand(2));
2728 case Intrinsic::aarch64_neon_smin:
2729 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2730 Op.getOperand(1), Op.getOperand(2));
2731 case Intrinsic::aarch64_neon_umin:
2732 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2733 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002734 }
2735}
2736
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002737// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2738static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2739 EVT VT, EVT MemVT,
2740 SelectionDAG &DAG) {
2741 assert(VT.isVector() && "VT should be a vector type");
2742 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2743
2744 SDValue Value = ST->getValue();
2745
2746 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2747 // the word lane which represent the v4i8 subvector. It optimizes the store
2748 // to:
2749 //
2750 // xtn v0.8b, v0.8h
2751 // str s0, [x0]
2752
2753 SDValue Undef = DAG.getUNDEF(MVT::i16);
2754 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2755 {Undef, Undef, Undef, Undef});
2756
2757 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2758 Value, UndefVec);
2759 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2760
2761 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2762 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2763 Trunc, DAG.getConstant(0, DL, MVT::i64));
2764
2765 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2766 ST->getBasePtr(), ST->getMemOperand());
2767}
2768
2769// Custom lowering for any store, vector or scalar and/or default or with
2770// a truncate operations. Currently only custom lower truncate operation
2771// from vector v4i16 to v4i8.
2772SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2773 SelectionDAG &DAG) const {
2774 SDLoc Dl(Op);
2775 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2776 assert (StoreNode && "Can only custom lower store nodes");
2777
2778 SDValue Value = StoreNode->getValue();
2779
2780 EVT VT = Value.getValueType();
2781 EVT MemVT = StoreNode->getMemoryVT();
2782
2783 assert (VT.isVector() && "Can only custom lower vector store types");
2784
2785 unsigned AS = StoreNode->getAddressSpace();
2786 unsigned Align = StoreNode->getAlignment();
2787 if (Align < MemVT.getStoreSize() &&
2788 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2789 return scalarizeVectorStore(StoreNode, DAG);
2790 }
2791
2792 if (StoreNode->isTruncatingStore()) {
2793 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2794 }
2795
2796 return SDValue();
2797}
2798
Tim Northover3b0846e2014-05-24 12:50:23 +00002799SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2800 SelectionDAG &DAG) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002801 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2802 LLVM_DEBUG(Op.dump());
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002803
Tim Northover3b0846e2014-05-24 12:50:23 +00002804 switch (Op.getOpcode()) {
2805 default:
2806 llvm_unreachable("unimplemented operand");
2807 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002808 case ISD::BITCAST:
2809 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002810 case ISD::GlobalAddress:
2811 return LowerGlobalAddress(Op, DAG);
2812 case ISD::GlobalTLSAddress:
2813 return LowerGlobalTLSAddress(Op, DAG);
2814 case ISD::SETCC:
2815 return LowerSETCC(Op, DAG);
2816 case ISD::BR_CC:
2817 return LowerBR_CC(Op, DAG);
2818 case ISD::SELECT:
2819 return LowerSELECT(Op, DAG);
2820 case ISD::SELECT_CC:
2821 return LowerSELECT_CC(Op, DAG);
2822 case ISD::JumpTable:
2823 return LowerJumpTable(Op, DAG);
Tim Northover1c353412018-10-24 20:19:09 +00002824 case ISD::BR_JT:
2825 return LowerBR_JT(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002826 case ISD::ConstantPool:
2827 return LowerConstantPool(Op, DAG);
2828 case ISD::BlockAddress:
2829 return LowerBlockAddress(Op, DAG);
2830 case ISD::VASTART:
2831 return LowerVASTART(Op, DAG);
2832 case ISD::VACOPY:
2833 return LowerVACOPY(Op, DAG);
2834 case ISD::VAARG:
2835 return LowerVAARG(Op, DAG);
2836 case ISD::ADDC:
2837 case ISD::ADDE:
2838 case ISD::SUBC:
2839 case ISD::SUBE:
2840 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2841 case ISD::SADDO:
2842 case ISD::UADDO:
2843 case ISD::SSUBO:
2844 case ISD::USUBO:
2845 case ISD::SMULO:
2846 case ISD::UMULO:
2847 return LowerXALUO(Op, DAG);
2848 case ISD::FADD:
2849 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2850 case ISD::FSUB:
2851 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2852 case ISD::FMUL:
2853 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2854 case ISD::FDIV:
2855 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2856 case ISD::FP_ROUND:
2857 return LowerFP_ROUND(Op, DAG);
2858 case ISD::FP_EXTEND:
2859 return LowerFP_EXTEND(Op, DAG);
2860 case ISD::FRAMEADDR:
2861 return LowerFRAMEADDR(Op, DAG);
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00002862 case ISD::SPONENTRY:
2863 return LowerSPONENTRY(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002864 case ISD::RETURNADDR:
2865 return LowerRETURNADDR(Op, DAG);
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00002866 case ISD::ADDROFRETURNADDR:
2867 return LowerADDROFRETURNADDR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002868 case ISD::INSERT_VECTOR_ELT:
2869 return LowerINSERT_VECTOR_ELT(Op, DAG);
2870 case ISD::EXTRACT_VECTOR_ELT:
2871 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2872 case ISD::BUILD_VECTOR:
2873 return LowerBUILD_VECTOR(Op, DAG);
2874 case ISD::VECTOR_SHUFFLE:
2875 return LowerVECTOR_SHUFFLE(Op, DAG);
2876 case ISD::EXTRACT_SUBVECTOR:
2877 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2878 case ISD::SRA:
2879 case ISD::SRL:
2880 case ISD::SHL:
2881 return LowerVectorSRA_SRL_SHL(Op, DAG);
2882 case ISD::SHL_PARTS:
2883 return LowerShiftLeftParts(Op, DAG);
2884 case ISD::SRL_PARTS:
2885 case ISD::SRA_PARTS:
2886 return LowerShiftRightParts(Op, DAG);
2887 case ISD::CTPOP:
2888 return LowerCTPOP(Op, DAG);
2889 case ISD::FCOPYSIGN:
2890 return LowerFCOPYSIGN(Op, DAG);
2891 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002892 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002893 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002894 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002895 case ISD::XOR:
2896 return LowerXOR(Op, DAG);
2897 case ISD::PREFETCH:
2898 return LowerPREFETCH(Op, DAG);
2899 case ISD::SINT_TO_FP:
2900 case ISD::UINT_TO_FP:
2901 return LowerINT_TO_FP(Op, DAG);
2902 case ISD::FP_TO_SINT:
2903 case ISD::FP_TO_UINT:
2904 return LowerFP_TO_INT(Op, DAG);
2905 case ISD::FSINCOS:
2906 return LowerFSINCOS(Op, DAG);
Tim Northover70666e72018-06-20 12:09:01 +00002907 case ISD::FLT_ROUNDS_:
2908 return LowerFLT_ROUNDS_(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002909 case ISD::MUL:
2910 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002911 case ISD::INTRINSIC_WO_CHAIN:
2912 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Adhemerval Zanellacadcfed2018-06-27 13:58:46 +00002913 case ISD::STORE:
2914 return LowerSTORE(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002915 case ISD::VECREDUCE_ADD:
2916 case ISD::VECREDUCE_SMAX:
2917 case ISD::VECREDUCE_SMIN:
2918 case ISD::VECREDUCE_UMAX:
2919 case ISD::VECREDUCE_UMIN:
2920 case ISD::VECREDUCE_FMAX:
2921 case ISD::VECREDUCE_FMIN:
2922 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002923 case ISD::ATOMIC_LOAD_SUB:
2924 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002925 case ISD::ATOMIC_LOAD_AND:
2926 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002927 case ISD::DYNAMIC_STACKALLOC:
2928 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002929 }
2930}
2931
Tim Northover3b0846e2014-05-24 12:50:23 +00002932//===----------------------------------------------------------------------===//
2933// Calling Convention Implementation
2934//===----------------------------------------------------------------------===//
2935
2936#include "AArch64GenCallingConv.inc"
2937
Robin Morisset039781e2014-08-29 21:53:01 +00002938/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002939CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2940 bool IsVarArg) const {
2941 switch (CC) {
2942 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002943 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002944 case CallingConv::WebKit_JS:
2945 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002946 case CallingConv::GHC:
2947 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002948 case CallingConv::C:
2949 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002950 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002951 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002952 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002953 if (Subtarget->isTargetWindows() && IsVarArg)
2954 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002955 if (!Subtarget->isTargetDarwin())
2956 return CC_AArch64_AAPCS;
2957 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002958 case CallingConv::Win64:
2959 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Sander de Smalen4dbc5122018-09-12 08:54:06 +00002960 case CallingConv::AArch64_VectorCall:
2961 return CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002962 }
2963}
2964
Tim Northover406024a2016-08-10 21:44:01 +00002965CCAssignFn *
2966AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2967 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2968 : RetCC_AArch64_AAPCS;
2969}
2970
Tim Northover3b0846e2014-05-24 12:50:23 +00002971SDValue AArch64TargetLowering::LowerFormalArguments(
2972 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002973 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2974 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002975 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002976 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00002977 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00002978
2979 // Assign locations to all of the incoming arguments.
2980 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002981 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2982 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002983
2984 // At this point, Ins[].VT may already be promoted to i32. To correctly
2985 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2986 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2987 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2988 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2989 // LocVT.
2990 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00002991 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00002992 unsigned CurArgIdx = 0;
2993 for (unsigned i = 0; i != NumArgs; ++i) {
2994 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002995 if (Ins[i].isOrigArg()) {
2996 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2997 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002998
Andrew Trick05938a52015-02-16 18:10:47 +00002999 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003000 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3001 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00003002 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3003 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3004 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3005 ValVT = MVT::i8;
3006 else if (ActualMVT == MVT::i16)
3007 ValVT = MVT::i16;
3008 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003009 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3010 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00003011 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003012 assert(!Res && "Call operand has unhandled type");
3013 (void)Res;
3014 }
3015 assert(ArgLocs.size() == Ins.size());
3016 SmallVector<SDValue, 16> ArgValues;
3017 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3018 CCValAssign &VA = ArgLocs[i];
3019
3020 if (Ins[i].Flags.isByVal()) {
3021 // Byval is used for HFAs in the PCS, but the system should work in a
3022 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00003023 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003024 int Size = Ins[i].Flags.getByValSize();
3025 unsigned NumRegs = (Size + 7) / 8;
3026
3027 // FIXME: This works on big-endian for composite byvals, which are the common
3028 // case. It should also work for fundamental types too.
3029 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00003030 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00003031 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003032 InVals.push_back(FrameIdxN);
3033
3034 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003035 }
Junmo Park3b8c7152016-01-05 09:36:47 +00003036
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003037 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003038 // Arguments stored in registers.
3039 EVT RegVT = VA.getLocVT();
3040
3041 SDValue ArgValue;
3042 const TargetRegisterClass *RC;
3043
3044 if (RegVT == MVT::i32)
3045 RC = &AArch64::GPR32RegClass;
3046 else if (RegVT == MVT::i64)
3047 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00003048 else if (RegVT == MVT::f16)
3049 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00003050 else if (RegVT == MVT::f32)
3051 RC = &AArch64::FPR32RegClass;
3052 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3053 RC = &AArch64::FPR64RegClass;
3054 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3055 RC = &AArch64::FPR128RegClass;
3056 else
3057 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3058
3059 // Transform the arguments in physical registers into virtual ones.
3060 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3061 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3062
3063 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3064 // to 64 bits. Insert an assert[sz]ext to capture this, then
3065 // truncate to the right size.
3066 switch (VA.getLocInfo()) {
3067 default:
3068 llvm_unreachable("Unknown loc info!");
3069 case CCValAssign::Full:
3070 break;
3071 case CCValAssign::BCvt:
3072 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3073 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003074 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003075 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00003076 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00003077 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3078 // nodes after our lowering.
3079 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00003080 break;
3081 }
3082
3083 InVals.push_back(ArgValue);
3084
3085 } else { // VA.isRegLoc()
3086 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3087 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00003088 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003089
3090 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00003091 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3092 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00003093 BEAlign = 8 - ArgSize;
3094
Matthias Braun941a7052016-07-28 18:40:00 +00003095 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003096
3097 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00003098 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003099 SDValue ArgValue;
3100
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003101 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00003102 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00003103 MVT MemVT = VA.getValVT();
3104
Tim Northover47e003c2014-05-26 17:21:53 +00003105 switch (VA.getLocInfo()) {
3106 default:
3107 break;
Tim Northover6890add2014-06-03 13:54:53 +00003108 case CCValAssign::BCvt:
3109 MemVT = VA.getLocVT();
3110 break;
Tim Northover47e003c2014-05-26 17:21:53 +00003111 case CCValAssign::SExt:
3112 ExtType = ISD::SEXTLOAD;
3113 break;
3114 case CCValAssign::ZExt:
3115 ExtType = ISD::ZEXTLOAD;
3116 break;
3117 case CCValAssign::AExt:
3118 ExtType = ISD::EXTLOAD;
3119 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00003120 }
3121
Alex Lorenze40c8a22015-08-11 23:09:45 +00003122 ArgValue = DAG.getExtLoad(
3123 ExtType, DL, VA.getLocVT(), Chain, FIN,
3124 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00003125 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00003126
Tim Northover3b0846e2014-05-24 12:50:23 +00003127 InVals.push_back(ArgValue);
3128 }
3129 }
3130
3131 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00003132 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00003133 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00003134 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003135 // The AAPCS variadic function ABI is identical to the non-variadic
3136 // one. As a result there may be more arguments in registers and we should
3137 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00003138 // Win64 variadic functions also pass arguments in registers, but all float
3139 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003140 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3141 }
3142
Tim Northover3b0846e2014-05-24 12:50:23 +00003143 // This will point to the next argument passed via stack.
3144 unsigned StackOffset = CCInfo.getNextStackOffset();
3145 // We currently pass all varargs at 8-byte alignment.
3146 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00003147 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003148
3149 if (MFI.hasMustTailInVarArgFunc()) {
3150 SmallVector<MVT, 2> RegParmTypes;
3151 RegParmTypes.push_back(MVT::i64);
3152 RegParmTypes.push_back(MVT::f128);
3153 // Compute the set of forwarded registers. The rest are scratch.
3154 SmallVectorImpl<ForwardedRegister> &Forwards =
3155 FuncInfo->getForwardedMustTailRegParms();
3156 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3157 CC_AArch64_AAPCS);
3158 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003159 }
3160
Tim Northover3b0846e2014-05-24 12:50:23 +00003161 unsigned StackArgSize = CCInfo.getNextStackOffset();
3162 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3163 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3164 // This is a non-standard ABI so by fiat I say we're allowed to make full
3165 // use of the stack area to be popped, which must be aligned to 16 bytes in
3166 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003167 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003168
3169 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3170 // a multiple of 16.
3171 FuncInfo->setArgumentStackToRestore(StackArgSize);
3172
3173 // This realignment carries over to the available bytes below. Our own
3174 // callers will guarantee the space is free by giving an aligned value to
3175 // CALLSEQ_START.
3176 }
3177 // Even if we're not expected to free up the space, it's useful to know how
3178 // much is there while considering tail calls (because we can reuse it).
3179 FuncInfo->setBytesInStackArgArea(StackArgSize);
3180
Tri Vo6c47c622018-09-22 22:17:50 +00003181 if (Subtarget->hasCustomCallingConv())
3182 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3183
Tim Northover3b0846e2014-05-24 12:50:23 +00003184 return Chain;
3185}
3186
3187void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003188 SelectionDAG &DAG,
3189 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00003190 SDValue &Chain) const {
3191 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00003192 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003193 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00003194 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00003195 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00003196
3197 SmallVector<SDValue, 8> MemOps;
3198
3199 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3200 AArch64::X3, AArch64::X4, AArch64::X5,
3201 AArch64::X6, AArch64::X7 };
3202 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003203 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003204
3205 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3206 int GPRIdx = 0;
3207 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00003208 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00003209 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00003210 if (GPRSaveSize & 15)
3211 // The extra size here, if triggered, will always be 8.
3212 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3213 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00003214 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003215
Mehdi Amini44ede332015-07-09 02:09:04 +00003216 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003217
3218 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3219 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3220 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003221 SDValue Store = DAG.getStore(
3222 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00003223 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00003224 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3225 GPRIdx,
3226 (i - FirstVariadicGPR) * 8)
3227 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00003228 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003229 FIN =
3230 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003231 }
3232 }
3233 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3234 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3235
Martin Storsjo2f24e932017-07-17 20:05:19 +00003236 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003237 static const MCPhysReg FPRArgRegs[] = {
3238 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3239 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3240 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003241 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00003242
3243 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3244 int FPRIdx = 0;
3245 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003246 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00003247
Mehdi Amini44ede332015-07-09 02:09:04 +00003248 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003249
3250 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3251 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3252 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3253
Alex Lorenze40c8a22015-08-11 23:09:45 +00003254 SDValue Store = DAG.getStore(
3255 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003256 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003257 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003258 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3259 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003260 }
3261 }
3262 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3263 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3264 }
3265
3266 if (!MemOps.empty()) {
3267 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3268 }
3269}
3270
3271/// LowerCallResult - Lower the result values of a call into the
3272/// appropriate copies out of appropriate physical registers.
3273SDValue AArch64TargetLowering::LowerCallResult(
3274 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003275 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3276 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003277 SDValue ThisVal) const {
3278 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3279 ? RetCC_AArch64_WebKit_JS
3280 : RetCC_AArch64_AAPCS;
3281 // Assign locations to each value returned by this call.
3282 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003283 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3284 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003285 CCInfo.AnalyzeCallResult(Ins, RetCC);
3286
3287 // Copy all of the result registers out of their specified physreg.
3288 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3289 CCValAssign VA = RVLocs[i];
3290
3291 // Pass 'this' value directly from the argument to return value, to avoid
3292 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003293 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003294 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3295 "unexpected return calling convention register assignment");
3296 InVals.push_back(ThisVal);
3297 continue;
3298 }
3299
3300 SDValue Val =
3301 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3302 Chain = Val.getValue(1);
3303 InFlag = Val.getValue(2);
3304
3305 switch (VA.getLocInfo()) {
3306 default:
3307 llvm_unreachable("Unknown loc info!");
3308 case CCValAssign::Full:
3309 break;
3310 case CCValAssign::BCvt:
3311 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3312 break;
3313 }
3314
3315 InVals.push_back(Val);
3316 }
3317
3318 return Chain;
3319}
3320
Matthias Braun1af14142016-09-13 19:27:38 +00003321/// Return true if the calling convention is one that we can guarantee TCO for.
3322static bool canGuaranteeTCO(CallingConv::ID CC) {
3323 return CC == CallingConv::Fast;
3324}
3325
3326/// Return true if we might ever do TCO for calls with this calling convention.
3327static bool mayTailCallThisCC(CallingConv::ID CC) {
3328 switch (CC) {
3329 case CallingConv::C:
3330 case CallingConv::PreserveMost:
3331 case CallingConv::Swift:
3332 return true;
3333 default:
3334 return canGuaranteeTCO(CC);
3335 }
3336}
3337
Tim Northover3b0846e2014-05-24 12:50:23 +00003338bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3339 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003340 const SmallVectorImpl<ISD::OutputArg> &Outs,
3341 const SmallVectorImpl<SDValue> &OutVals,
3342 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003343 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003344 return false;
3345
Matthias Braun8d414362016-03-30 22:46:04 +00003346 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003347 const Function &CallerF = MF.getFunction();
3348 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003349 bool CCMatch = CallerCC == CalleeCC;
3350
3351 // Byval parameters hand the function a pointer directly into the stack area
3352 // we want to reuse during a tail call. Working around this *is* possible (see
3353 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003354 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3355 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003356 i != e; ++i)
3357 if (i->hasByValAttr())
3358 return false;
3359
Matthias Braun1af14142016-09-13 19:27:38 +00003360 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3361 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003362
Oliver Stannard12993dd2014-08-18 12:42:15 +00003363 // Externally-defined functions with weak linkage should not be
3364 // tail-called on AArch64 when the OS does not support dynamic
3365 // pre-emption of symbols, as the AAELF spec requires normal calls
3366 // to undefined weak functions to be replaced with a NOP or jump to the
3367 // next instruction. The behaviour of branch instructions in this
3368 // situation (as used for tail calls) is implementation-defined, so we
3369 // cannot rely on the linker replacing the tail call with a return.
3370 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3371 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003372 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003373 if (GV->hasExternalWeakLinkage() &&
3374 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003375 return false;
3376 }
3377
Tim Northover3b0846e2014-05-24 12:50:23 +00003378 // Now we search for cases where we can use a tail call without changing the
3379 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3380 // concept.
3381
3382 // I want anyone implementing a new calling convention to think long and hard
3383 // about this assert.
3384 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3385 "Unexpected variadic calling convention");
3386
Matthias Braun8d414362016-03-30 22:46:04 +00003387 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003388 if (isVarArg && !Outs.empty()) {
3389 // At least two cases here: if caller is fastcc then we can't have any
3390 // memory arguments (we'd be expected to clean up the stack afterwards). If
3391 // caller is C then we could potentially use its argument area.
3392
3393 // FIXME: for now we take the most conservative of these in both cases:
3394 // disallow all variadic memory operands.
3395 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003396 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003397
3398 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003399 for (const CCValAssign &ArgLoc : ArgLocs)
3400 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003401 return false;
3402 }
3403
Matthias Braun8d414362016-03-30 22:46:04 +00003404 // Check that the call results are passed in the same way.
3405 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3406 CCAssignFnForCall(CalleeCC, isVarArg),
3407 CCAssignFnForCall(CallerCC, isVarArg)))
3408 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003409 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003410 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3411 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003412 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003413 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
Tri Vo6c47c622018-09-22 22:17:50 +00003414 if (Subtarget->hasCustomCallingConv()) {
3415 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3416 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3417 }
Matthias Braun74a0bd32016-04-13 21:43:16 +00003418 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003419 return false;
3420 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003421
3422 // Nothing more to check if the callee is taking no arguments
3423 if (Outs.empty())
3424 return true;
3425
3426 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003427 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003428
3429 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3430
3431 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3432
Matthias Braun74a0bd32016-04-13 21:43:16 +00003433 // If the stack arguments for this call do not fit into our own save area then
3434 // the call cannot be made tail.
3435 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3436 return false;
3437
Matthias Braun46b0f032016-04-14 01:10:42 +00003438 const MachineRegisterInfo &MRI = MF.getRegInfo();
3439 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3440 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003441
3442 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003443}
3444
3445SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3446 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003447 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003448 int ClobberedFI) const {
3449 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003450 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3451 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003452
3453 // Include the original chain at the beginning of the list. When this is
3454 // used by target LowerCall hooks, this helps legalize find the
3455 // CALLSEQ_BEGIN node.
3456 ArgChains.push_back(Chain);
3457
3458 // Add a chain value for each stack argument corresponding
3459 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3460 UE = DAG.getEntryNode().getNode()->use_end();
3461 U != UE; ++U)
3462 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3463 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3464 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003465 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003466 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003467 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003468
3469 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3470 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3471 ArgChains.push_back(SDValue(L, 1));
3472 }
3473
3474 // Build a tokenfactor for all the chains.
3475 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3476}
3477
3478bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3479 bool TailCallOpt) const {
3480 return CallCC == CallingConv::Fast && TailCallOpt;
3481}
3482
Tim Northover3b0846e2014-05-24 12:50:23 +00003483/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3484/// and add input and output parameter nodes.
3485SDValue
3486AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3487 SmallVectorImpl<SDValue> &InVals) const {
3488 SelectionDAG &DAG = CLI.DAG;
3489 SDLoc &DL = CLI.DL;
3490 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3491 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3492 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3493 SDValue Chain = CLI.Chain;
3494 SDValue Callee = CLI.Callee;
3495 bool &IsTailCall = CLI.IsTailCall;
3496 CallingConv::ID CallConv = CLI.CallConv;
3497 bool IsVarArg = CLI.IsVarArg;
3498
3499 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003500 bool IsThisReturn = false;
3501
3502 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3503 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3504 bool IsSibCall = false;
3505
3506 if (IsTailCall) {
3507 // Check if it's really possible to do a tail call.
3508 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003509 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003510 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003511 report_fatal_error("failed to perform tail call elimination on a call "
3512 "site marked musttail");
3513
3514 // A sibling call is one where we're under the usual C ABI and not planning
3515 // to change that but can still do a tail call:
3516 if (!TailCallOpt && IsTailCall)
3517 IsSibCall = true;
3518
3519 if (IsTailCall)
3520 ++NumTailCalls;
3521 }
3522
3523 // Analyze operands of the call, assigning locations to each operand.
3524 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003525 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3526 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003527
3528 if (IsVarArg) {
3529 // Handle fixed and variable vector arguments differently.
3530 // Variable vector arguments always go into memory.
3531 unsigned NumArgs = Outs.size();
3532
3533 for (unsigned i = 0; i != NumArgs; ++i) {
3534 MVT ArgVT = Outs[i].VT;
3535 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3536 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3537 /*IsVarArg=*/ !Outs[i].IsFixed);
3538 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3539 assert(!Res && "Call operand has unhandled type");
3540 (void)Res;
3541 }
3542 } else {
3543 // At this point, Outs[].VT may already be promoted to i32. To correctly
3544 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3545 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3546 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3547 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3548 // LocVT.
3549 unsigned NumArgs = Outs.size();
3550 for (unsigned i = 0; i != NumArgs; ++i) {
3551 MVT ValVT = Outs[i].VT;
3552 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003553 EVT ActualVT = getValueType(DAG.getDataLayout(),
3554 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003555 /*AllowUnknown*/ true);
3556 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3557 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3558 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003559 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003560 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003561 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003562 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003563
3564 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003565 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003566 assert(!Res && "Call operand has unhandled type");
3567 (void)Res;
3568 }
3569 }
3570
3571 // Get a count of how many bytes are to be pushed on the stack.
3572 unsigned NumBytes = CCInfo.getNextStackOffset();
3573
3574 if (IsSibCall) {
3575 // Since we're not changing the ABI to make this a tail call, the memory
3576 // operands are already available in the caller's incoming argument space.
3577 NumBytes = 0;
3578 }
3579
3580 // FPDiff is the byte offset of the call's argument area from the callee's.
3581 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3582 // by this amount for a tail call. In a sibling call it must be 0 because the
3583 // caller will deallocate the entire stack and the callee still expects its
3584 // arguments to begin at SP+0. Completely unused for non-tail calls.
3585 int FPDiff = 0;
3586
3587 if (IsTailCall && !IsSibCall) {
3588 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3589
3590 // Since callee will pop argument stack as a tail call, we must keep the
3591 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003592 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003593
3594 // FPDiff will be negative if this tail call requires more space than we
3595 // would automatically have in our incoming argument space. Positive if we
3596 // can actually shrink the stack.
3597 FPDiff = NumReusableBytes - NumBytes;
3598
3599 // The stack pointer must be 16-byte aligned at all times it's used for a
3600 // memory operation, which in practice means at *all* times and in
3601 // particular across call boundaries. Therefore our own arguments started at
3602 // a 16-byte aligned SP and the delta applied for the tail call should
3603 // satisfy the same constraint.
3604 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3605 }
3606
3607 // Adjust the stack pointer for the new arguments...
3608 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003609 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003610 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003611
Mehdi Amini44ede332015-07-09 02:09:04 +00003612 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3613 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003614
3615 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3616 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003617 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003618
Mandeep Singh Grang71e0cc22018-10-30 20:46:10 +00003619 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3620 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3621 for (const auto &F : Forwards) {
3622 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3623 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3624 }
3625 }
3626
Tim Northover3b0846e2014-05-24 12:50:23 +00003627 // Walk the register/memloc assignments, inserting copies/loads.
3628 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3629 ++i, ++realArgIdx) {
3630 CCValAssign &VA = ArgLocs[i];
3631 SDValue Arg = OutVals[realArgIdx];
3632 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3633
3634 // Promote the value if needed.
3635 switch (VA.getLocInfo()) {
3636 default:
3637 llvm_unreachable("Unknown loc info!");
3638 case CCValAssign::Full:
3639 break;
3640 case CCValAssign::SExt:
3641 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3642 break;
3643 case CCValAssign::ZExt:
3644 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3645 break;
3646 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003647 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3648 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3649 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3650 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3651 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003652 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3653 break;
3654 case CCValAssign::BCvt:
3655 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3656 break;
3657 case CCValAssign::FPExt:
3658 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3659 break;
3660 }
3661
3662 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003663 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3664 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003665 assert(VA.getLocVT() == MVT::i64 &&
3666 "unexpected calling convention register assignment");
3667 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3668 "unexpected use of 'returned'");
3669 IsThisReturn = true;
3670 }
3671 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3672 } else {
3673 assert(VA.isMemLoc());
3674
3675 SDValue DstAddr;
3676 MachinePointerInfo DstInfo;
3677
3678 // FIXME: This works on big-endian for composite byvals, which are the
3679 // common case. It should also work for fundamental types too.
3680 uint32_t BEAlign = 0;
3681 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003682 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003683 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003684 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3685 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003686 if (OpSize < 8)
3687 BEAlign = 8 - OpSize;
3688 }
3689 unsigned LocMemOffset = VA.getLocMemOffset();
3690 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003691 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003692 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003693
3694 if (IsTailCall) {
3695 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003696 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003697
Mehdi Amini44ede332015-07-09 02:09:04 +00003698 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003699 DstInfo =
3700 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003701
3702 // Make sure any stack arguments overlapping with where we're storing
3703 // are loaded before this eventual operation. Otherwise they'll be
3704 // clobbered.
3705 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3706 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003707 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003708
Mehdi Amini44ede332015-07-09 02:09:04 +00003709 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003710 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3711 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003712 }
3713
3714 if (Outs[i].Flags.isByVal()) {
3715 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003716 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003717 SDValue Cpy = DAG.getMemcpy(
3718 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003719 /*isVol = */ false, /*AlwaysInline = */ false,
3720 /*isTailCall = */ false,
3721 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003722
3723 MemOpChains.push_back(Cpy);
3724 } else {
3725 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3726 // promoted to a legal register type i32, we should truncate Arg back to
3727 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003728 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3729 VA.getValVT() == MVT::i16)
3730 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003731
Justin Lebar9c375812016-07-15 18:27:10 +00003732 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003733 MemOpChains.push_back(Store);
3734 }
3735 }
3736 }
3737
3738 if (!MemOpChains.empty())
3739 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3740
3741 // Build a sequence of copy-to-reg nodes chained together with token chain
3742 // and flag operands which copy the outgoing args into the appropriate regs.
3743 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003744 for (auto &RegToPass : RegsToPass) {
3745 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3746 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003747 InFlag = Chain.getValue(1);
3748 }
3749
3750 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3751 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3752 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003753 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3754 auto GV = G->getGlobal();
3755 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3756 AArch64II::MO_GOT) {
3757 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3758 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003759 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3760 assert(Subtarget->isTargetWindows() &&
3761 "Windows is the only supported COFF target");
3762 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003763 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003764 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003765 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3766 }
3767 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3768 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3769 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003770 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003771 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3772 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003773 } else {
3774 const char *Sym = S->getSymbol();
3775 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003776 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003777 }
3778
3779 // We don't usually want to end the call-sequence here because we would tidy
3780 // the frame up *after* the call, however in the ABI-changing tail-call case
3781 // we've carefully laid out the parameters so that when sp is reset they'll be
3782 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003783 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003784 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3785 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003786 InFlag = Chain.getValue(1);
3787 }
3788
3789 std::vector<SDValue> Ops;
3790 Ops.push_back(Chain);
3791 Ops.push_back(Callee);
3792
3793 if (IsTailCall) {
3794 // Each tail call may have to adjust the stack by a different amount, so
3795 // this information must travel along with the operation for eventual
3796 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003797 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003798 }
3799
3800 // Add argument registers to the end of the list so that they are known live
3801 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003802 for (auto &RegToPass : RegsToPass)
3803 Ops.push_back(DAG.getRegister(RegToPass.first,
3804 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003805
3806 // Add a register mask operand representing the call-preserved registers.
3807 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003808 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003809 if (IsThisReturn) {
3810 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003811 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003812 if (!Mask) {
3813 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003814 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003815 }
3816 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003817 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003818
Tri Vo6c47c622018-09-22 22:17:50 +00003819 if (Subtarget->hasCustomCallingConv())
3820 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3821
Nick Desaulniers287a3be2018-09-07 20:58:57 +00003822 if (TRI->isAnyArgRegReserved(MF))
3823 TRI->emitReservedArgRegCallError(MF);
3824
Tim Northover3b0846e2014-05-24 12:50:23 +00003825 assert(Mask && "Missing call preserved mask for calling convention");
3826 Ops.push_back(DAG.getRegisterMask(Mask));
3827
3828 if (InFlag.getNode())
3829 Ops.push_back(InFlag);
3830
3831 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3832
3833 // If we're doing a tall call, use a TC_RETURN here rather than an
3834 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003835 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003836 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003837 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003838 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003839
3840 // Returns a chain and a flag for retval copy to use.
3841 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3842 InFlag = Chain.getValue(1);
3843
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003844 uint64_t CalleePopBytes =
3845 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003846
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003847 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3848 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3849 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003850 if (!Ins.empty())
3851 InFlag = Chain.getValue(1);
3852
3853 // Handle result values, copying them out of physregs into vregs that we
3854 // return.
3855 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3856 InVals, IsThisReturn,
3857 IsThisReturn ? OutVals[0] : SDValue());
3858}
3859
3860bool AArch64TargetLowering::CanLowerReturn(
3861 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3862 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3863 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3864 ? RetCC_AArch64_WebKit_JS
3865 : RetCC_AArch64_AAPCS;
3866 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003867 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003868 return CCInfo.CheckReturn(Outs, RetCC);
3869}
3870
3871SDValue
3872AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3873 bool isVarArg,
3874 const SmallVectorImpl<ISD::OutputArg> &Outs,
3875 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003876 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003877 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3878 ? RetCC_AArch64_WebKit_JS
3879 : RetCC_AArch64_AAPCS;
3880 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003881 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3882 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003883 CCInfo.AnalyzeReturn(Outs, RetCC);
3884
3885 // Copy the result values into the output registers.
3886 SDValue Flag;
3887 SmallVector<SDValue, 4> RetOps(1, Chain);
3888 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3889 ++i, ++realRVLocIdx) {
3890 CCValAssign &VA = RVLocs[i];
3891 assert(VA.isRegLoc() && "Can only return in registers!");
3892 SDValue Arg = OutVals[realRVLocIdx];
3893
3894 switch (VA.getLocInfo()) {
3895 default:
3896 llvm_unreachable("Unknown loc info!");
3897 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003898 if (Outs[i].ArgVT == MVT::i1) {
3899 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3900 // value. This is strictly redundant on Darwin (which uses "zeroext
3901 // i1"), but will be optimised out before ISel.
3902 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3903 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3904 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003905 break;
3906 case CCValAssign::BCvt:
3907 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3908 break;
3909 }
3910
3911 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3912 Flag = Chain.getValue(1);
3913 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3914 }
Manman Rencbe4f942015-12-16 21:04:19 +00003915 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3916 const MCPhysReg *I =
3917 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3918 if (I) {
3919 for (; *I; ++I) {
3920 if (AArch64::GPR64RegClass.contains(*I))
3921 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3922 else if (AArch64::FPR64RegClass.contains(*I))
3923 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3924 else
3925 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3926 }
3927 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003928
3929 RetOps[0] = Chain; // Update chain.
3930
3931 // Add the flag if we have it.
3932 if (Flag.getNode())
3933 RetOps.push_back(Flag);
3934
3935 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3936}
3937
3938//===----------------------------------------------------------------------===//
3939// Other Lowering Code
3940//===----------------------------------------------------------------------===//
3941
Joel Jonesa7c4a522017-04-21 17:31:03 +00003942SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3943 SelectionDAG &DAG,
3944 unsigned Flag) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00003945 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3946 N->getOffset(), Flag);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003947}
3948
3949SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3950 SelectionDAG &DAG,
3951 unsigned Flag) const {
3952 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3953}
3954
3955SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3956 SelectionDAG &DAG,
3957 unsigned Flag) const {
3958 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3959 N->getOffset(), Flag);
3960}
3961
3962SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3963 SelectionDAG &DAG,
3964 unsigned Flag) const {
3965 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3966}
3967
3968// (loadGOT sym)
3969template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003970SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3971 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003972 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00003973 SDLoc DL(N);
3974 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003975 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003976 // FIXME: Once remat is capable of dealing with instructions with register
3977 // operands, expand this into two nodes instead of using a wrapper node.
3978 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3979}
3980
3981// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3982template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003983SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3984 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003985 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00003986 SDLoc DL(N);
3987 EVT Ty = getPointerTy(DAG.getDataLayout());
3988 const unsigned char MO_NC = AArch64II::MO_NC;
3989 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003990 AArch64ISD::WrapperLarge, DL, Ty,
3991 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3992 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3993 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3994 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00003995}
3996
3997// (addlow (adrp %hi(sym)) %lo(sym))
3998template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003999SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4000 unsigned Flags) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004001 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
Joel Jonesa7c4a522017-04-21 17:31:03 +00004002 SDLoc DL(N);
4003 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004004 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004005 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004006 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00004007 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4008 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4009}
4010
David Green9dd1d452018-08-22 11:31:39 +00004011// (adr sym)
4012template <class NodeTy>
4013SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4014 unsigned Flags) const {
4015 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4016 SDLoc DL(N);
4017 EVT Ty = getPointerTy(DAG.getDataLayout());
4018 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4019 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4020}
4021
Tim Northover3b0846e2014-05-24 12:50:23 +00004022SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4023 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004024 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00004025 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00004026 unsigned char OpFlags =
4027 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
Peter Collingbournea7d936f2018-04-10 16:19:30 +00004028
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00004029 if (OpFlags != AArch64II::MO_NO_FLAG)
4030 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4031 "unexpected offset in global node");
Tim Northover3b0846e2014-05-24 12:50:23 +00004032
David Green9dd1d452018-08-22 11:31:39 +00004033 // This also catches the large code model case for Darwin, and tiny code
4034 // model with got relocations.
Tim Northover3b0846e2014-05-24 12:50:23 +00004035 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004036 return getGOT(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004037 }
4038
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004039 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004040 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004041 Result = getAddrLarge(GN, DAG, OpFlags);
David Green9dd1d452018-08-22 11:31:39 +00004042 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004043 Result = getAddrTiny(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004044 } else {
Martin Storsjo5c984fb2018-09-03 11:59:23 +00004045 Result = getAddr(GN, DAG, OpFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00004046 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004047 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4048 SDLoc DL(GN);
Martin Storsjofed420d2018-09-04 20:56:21 +00004049 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
Martin Storsjo373c8ef2017-10-25 07:25:18 +00004050 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4051 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4052 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00004053}
4054
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004055/// Convert a TLS address reference into the correct sequence of loads
Tim Northover3b0846e2014-05-24 12:50:23 +00004056/// and calls to compute the variable's address (for Darwin, currently) and
4057/// return an SDValue containing the final node.
4058
4059/// Darwin only has one TLS scheme which must be capable of dealing with the
4060/// fully general situation, in the worst case. This means:
4061/// + "extern __thread" declaration.
4062/// + Defined in a possibly unknown dynamic library.
4063///
4064/// The general system is that each __thread variable has a [3 x i64] descriptor
4065/// which contains information used by the runtime to calculate the address. The
4066/// only part of this the compiler needs to know about is the first xword, which
4067/// contains a function pointer that must be called with the address of the
4068/// entire descriptor in "x0".
4069///
4070/// Since this descriptor may be in a different unit, in general even the
4071/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4072/// is:
4073/// adrp x0, _var@TLVPPAGE
4074/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4075/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4076/// ; the function pointer
4077/// blr x1 ; Uses descriptor address in x0
4078/// ; Address of _var is now in x0.
4079///
4080/// If the address of _var's descriptor *is* known to the linker, then it can
4081/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4082/// a slight efficiency gain.
4083SDValue
4084AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4085 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00004086 assert(Subtarget->isTargetDarwin() &&
4087 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00004088
4089 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004090 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004091 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4092
4093 SDValue TLVPAddr =
4094 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4095 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4096
4097 // The first entry in the descriptor is a function pointer that we must call
4098 // to obtain the address of the variable.
4099 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00004100 SDValue FuncTLVGet = DAG.getLoad(
4101 MVT::i64, DL, Chain, DescAddr,
4102 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4103 /* Alignment = */ 8,
4104 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4105 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00004106 Chain = FuncTLVGet.getValue(1);
4107
Matthias Braun941a7052016-07-28 18:40:00 +00004108 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4109 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004110
4111 // TLS calls preserve all registers except those that absolutely must be
4112 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4113 // silly).
Tri Vo6c47c622018-09-22 22:17:50 +00004114 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4115 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4116 if (Subtarget->hasCustomCallingConv())
4117 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00004118
4119 // Finally, we can make the call. This is just a degenerate version of a
4120 // normal AArch64 call node: x0 takes the address of the descriptor, and
4121 // returns the address of the variable in this thread.
4122 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4123 Chain =
4124 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4125 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4126 DAG.getRegisterMask(Mask), Chain.getValue(1));
4127 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4128}
4129
4130/// When accessing thread-local variables under either the general-dynamic or
4131/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4132/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00004133/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00004134///
Kristof Beylsaea84612015-03-04 09:12:08 +00004135/// The sequence is:
4136/// adrp x0, :tlsdesc:var
4137/// ldr x1, [x0, #:tlsdesc_lo12:var]
4138/// add x0, x0, #:tlsdesc_lo12:var
4139/// .tlsdesccall var
4140/// blr x1
4141/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00004142///
Kristof Beylsaea84612015-03-04 09:12:08 +00004143/// The above sequence must be produced unscheduled, to enable the linker to
4144/// optimize/relax this sequence.
4145/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4146/// above sequence, and expanded really late in the compilation flow, to ensure
4147/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004148SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4149 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00004150 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00004151 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004152
Kristof Beylsaea84612015-03-04 09:12:08 +00004153 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00004154 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00004155
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00004156 Chain =
4157 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00004158 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004159
4160 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4161}
4162
4163SDValue
4164AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4165 SelectionDAG &DAG) const {
4166 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
David Green9dd1d452018-08-22 11:31:39 +00004167 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4168 report_fatal_error("ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00004169 // Different choices can be made for the maximum size of the TLS area for a
4170 // module. For the small address model, the default TLS size is 16MiB and the
4171 // maximum TLS size is 4GiB.
4172 // FIXME: add -mtls-size command line option and make it control the 16MiB
4173 // vs. 4GiB code sequence generation.
David Green9dd1d452018-08-22 11:31:39 +00004174 // FIXME: add tiny codemodel support. We currently generate the same code as
4175 // small, which may be larger than needed.
Tim Northover3b0846e2014-05-24 12:50:23 +00004176 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4177
4178 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00004179
Kristof Beylsaea84612015-03-04 09:12:08 +00004180 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4181 if (Model == TLSModel::LocalDynamic)
4182 Model = TLSModel::GeneralDynamic;
4183 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004184
4185 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00004186 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004187 SDLoc DL(Op);
4188 const GlobalValue *GV = GA->getGlobal();
4189
4190 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4191
4192 if (Model == TLSModel::LocalExec) {
4193 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004194 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004195 SDValue LoVar = DAG.getTargetGlobalAddress(
4196 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00004197 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00004198
Kristof Beylsaea84612015-03-04 09:12:08 +00004199 SDValue TPWithOff_lo =
4200 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004201 HiVar,
4202 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004203 0);
4204 SDValue TPWithOff =
Martin Storsjobde67722018-03-14 13:09:10 +00004205 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4206 LoVar,
4207 DAG.getTargetConstant(0, DL, MVT::i32)),
4208 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004209 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00004210 } else if (Model == TLSModel::InitialExec) {
4211 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4212 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4213 } else if (Model == TLSModel::LocalDynamic) {
4214 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4215 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4216 // the beginning of the module's TLS region, followed by a DTPREL offset
4217 // calculation.
4218
4219 // These accesses will need deduplicating if there's more than one.
4220 AArch64FunctionInfo *MFI =
4221 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4222 MFI->incNumLocalDynamicTLSAccesses();
4223
Tim Northover3b0846e2014-05-24 12:50:23 +00004224 // The call needs a relocation too for linker relaxation. It doesn't make
4225 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4226 // the address.
4227 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4228 AArch64II::MO_TLS);
4229
4230 // Now we can calculate the offset from TPIDR_EL0 to this module's
4231 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00004232 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004233
4234 // Now use :dtprel_whatever: operations to calculate this variable's offset
4235 // in its thread-storage area.
4236 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00004237 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00004238 SDValue LoVar = DAG.getTargetGlobalAddress(
4239 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00004240 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4241
Kristof Beylsaea84612015-03-04 09:12:08 +00004242 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004243 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00004244 0);
Martin Storsjobde67722018-03-14 13:09:10 +00004245 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4246 DAG.getTargetConstant(0, DL, MVT::i32)),
4247 0);
Kristof Beylsaea84612015-03-04 09:12:08 +00004248 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004249 // The call needs a relocation too for linker relaxation. It doesn't make
4250 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4251 // the address.
4252 SDValue SymAddr =
4253 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4254
4255 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00004256 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004257 } else
4258 llvm_unreachable("Unsupported ELF TLS access model");
4259
4260 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4261}
4262
Martin Storsjocc240962018-03-10 19:05:21 +00004263SDValue
4264AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4265 SelectionDAG &DAG) const {
4266 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4267
4268 SDValue Chain = DAG.getEntryNode();
4269 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4270 SDLoc DL(Op);
4271
4272 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4273
4274 // Load the ThreadLocalStoragePointer from the TEB
4275 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4276 SDValue TLSArray =
4277 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4278 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4279 Chain = TLSArray.getValue(1);
4280
4281 // Load the TLS index from the C runtime;
4282 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4283 // This also does the same as LOADgot, but using a generic i32 load,
4284 // while LOADgot only loads i64.
4285 SDValue TLSIndexHi =
4286 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4287 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4288 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4289 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4290 SDValue TLSIndex =
4291 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4292 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4293 Chain = TLSIndex.getValue(1);
4294
4295 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4296 // offset into the TLSArray.
4297 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4298 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4299 DAG.getConstant(3, DL, PtrVT));
4300 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4301 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4302 MachinePointerInfo());
4303 Chain = TLS.getValue(1);
4304
4305 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4306 const GlobalValue *GV = GA->getGlobal();
4307 SDValue TGAHi = DAG.getTargetGlobalAddress(
4308 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4309 SDValue TGALo = DAG.getTargetGlobalAddress(
4310 GV, DL, PtrVT, 0,
4311 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4312
4313 // Add the offset from the start of the .tls section (section base).
4314 SDValue Addr =
4315 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4316 DAG.getTargetConstant(0, DL, MVT::i32)),
4317 0);
Martin Storsjo7bc64bd2018-03-12 18:47:43 +00004318 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
Martin Storsjocc240962018-03-10 19:05:21 +00004319 return Addr;
4320}
4321
Tim Northover3b0846e2014-05-24 12:50:23 +00004322SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4323 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00004324 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00004325 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00004326 return LowerToTLSEmulatedModel(GA, DAG);
4327
Tim Northover3b0846e2014-05-24 12:50:23 +00004328 if (Subtarget->isTargetDarwin())
4329 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00004330 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00004331 return LowerELFGlobalTLSAddress(Op, DAG);
Martin Storsjocc240962018-03-10 19:05:21 +00004332 if (Subtarget->isTargetWindows())
4333 return LowerWindowsGlobalTLSAddress(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004334
4335 llvm_unreachable("Unexpected platform trying to use TLS");
4336}
Eugene Zelenko049b0172017-01-06 00:30:53 +00004337
Tim Northover3b0846e2014-05-24 12:50:23 +00004338SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4339 SDValue Chain = Op.getOperand(0);
4340 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4341 SDValue LHS = Op.getOperand(2);
4342 SDValue RHS = Op.getOperand(3);
4343 SDValue Dest = Op.getOperand(4);
4344 SDLoc dl(Op);
4345
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004346 MachineFunction &MF = DAG.getMachineFunction();
4347 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4348 // will not be produced, as they are conditional branch instructions that do
4349 // not set flags.
4350 bool ProduceNonFlagSettingCondBr =
4351 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4352
Tim Northover3b0846e2014-05-24 12:50:23 +00004353 // Handle f128 first, since lowering it will result in comparing the return
4354 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4355 // is expecting to deal with.
4356 if (LHS.getValueType() == MVT::f128) {
4357 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4358
4359 // If softenSetCCOperands returned a scalar, we need to compare the result
4360 // against zero to select between true and false values.
4361 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004362 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004363 CC = ISD::SETNE;
4364 }
4365 }
4366
4367 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4368 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004369 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4370 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004371 // Only lower legal XALUO ops.
4372 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4373 return SDValue();
4374
4375 // The actual operation with overflow check.
4376 AArch64CC::CondCode OFCC;
4377 SDValue Value, Overflow;
4378 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4379
4380 if (CC == ISD::SETNE)
4381 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004382 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004383
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004384 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4385 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004386 }
4387
4388 if (LHS.getValueType().isInteger()) {
4389 assert((LHS.getValueType() == RHS.getValueType()) &&
4390 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4391
4392 // If the RHS of the comparison is zero, we can potentially fold this
4393 // to a specialized branch.
4394 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004395 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004396 if (CC == ISD::SETEQ) {
4397 // See if we can use a TBZ to fold in an AND as well.
4398 // TBZ has a smaller branch displacement than CBZ. If the offset is
4399 // out of bounds, a late MI-layer pass rewrites branches.
4400 // 403.gcc is an example that hits this case.
4401 if (LHS.getOpcode() == ISD::AND &&
4402 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4403 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4404 SDValue Test = LHS.getOperand(0);
4405 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004406 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004407 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4408 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004409 }
4410
4411 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4412 } else if (CC == ISD::SETNE) {
4413 // See if we can use a TBZ to fold in an AND as well.
4414 // TBZ has a smaller branch displacement than CBZ. If the offset is
4415 // out of bounds, a late MI-layer pass rewrites branches.
4416 // 403.gcc is an example that hits this case.
4417 if (LHS.getOpcode() == ISD::AND &&
4418 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4419 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4420 SDValue Test = LHS.getOperand(0);
4421 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004422 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004423 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4424 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004425 }
4426
4427 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004428 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4429 // Don't combine AND since emitComparison converts the AND to an ANDS
4430 // (a.k.a. TST) and the test in the test bit and branch instruction
4431 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004432 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004433 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004434 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004435 }
4436 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004437 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
Kristof Beylse66bc1f2018-12-18 08:50:02 +00004438 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
Chad Rosier579c02c2014-08-01 14:48:56 +00004439 // Don't combine AND since emitComparison converts the AND to an ANDS
4440 // (a.k.a. TST) and the test in the test bit and branch instruction
4441 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004442 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004443 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004444 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004445 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004446
4447 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004448 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004449 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4450 Cmp);
4451 }
4452
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004453 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4454 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004455
4456 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4457 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004458 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004459 AArch64CC::CondCode CC1, CC2;
4460 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004461 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004462 SDValue BR1 =
4463 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4464 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004465 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004466 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4467 Cmp);
4468 }
4469
4470 return BR1;
4471}
4472
4473SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4474 SelectionDAG &DAG) const {
4475 EVT VT = Op.getValueType();
4476 SDLoc DL(Op);
4477
4478 SDValue In1 = Op.getOperand(0);
4479 SDValue In2 = Op.getOperand(1);
4480 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004481
4482 if (SrcVT.bitsLT(VT))
4483 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4484 else if (SrcVT.bitsGT(VT))
4485 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004486
4487 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004488 uint64_t EltMask;
4489 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004490
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004491 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004492 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004493 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004494 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004495 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004496 DAG.getUNDEF(VecVT), In2);
4497 } else {
4498 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4499 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4500 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004501 };
4502
4503 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4504 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4505 EltMask = 0x80000000ULL;
4506 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004507 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004508 VecVT = MVT::v2i64;
4509
Eric Christopher572e03a2015-06-19 01:53:21 +00004510 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004511 // immediate moves cannot materialize that in a single instruction for
4512 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004513 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004514
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004515 setVecVal(AArch64::dsub);
4516 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4517 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4518 EltMask = 0x8000ULL;
4519 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004520 } else {
4521 llvm_unreachable("Invalid type for copysign!");
4522 }
4523
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004524 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004525
4526 // If we couldn't materialize the mask above, then the mask vector will be
4527 // the zero vector, and we need to negate it here.
4528 if (VT == MVT::f64 || VT == MVT::v2f64) {
4529 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4530 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4531 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4532 }
4533
4534 SDValue Sel =
4535 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4536
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004537 if (VT == MVT::f16)
4538 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004539 if (VT == MVT::f32)
4540 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4541 else if (VT == MVT::f64)
4542 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4543 else
4544 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4545}
4546
4547SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004548 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004549 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004550 return SDValue();
4551
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004552 if (!Subtarget->hasNEON())
4553 return SDValue();
4554
Tim Northover3b0846e2014-05-24 12:50:23 +00004555 // While there is no integer popcount instruction, it can
4556 // be more efficiently lowered to the following sequence that uses
4557 // AdvSIMD registers/instructions as long as the copies to/from
4558 // the AdvSIMD registers are cheap.
4559 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4560 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4561 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4562 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4563 SDValue Val = Op.getOperand(0);
4564 SDLoc DL(Op);
4565 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004566
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004567 if (VT == MVT::i32 || VT == MVT::i64) {
4568 if (VT == MVT::i32)
4569 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4570 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004571
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004572 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4573 SDValue UaddLV = DAG.getNode(
4574 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4575 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004576
Simon Pilgrim095a7fe2018-10-15 21:15:58 +00004577 if (VT == MVT::i64)
4578 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4579 return UaddLV;
4580 }
4581
4582 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4583 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4584 "Unexpected type for custom ctpop lowering");
4585
4586 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4587 Val = DAG.getBitcast(VT8Bit, Val);
4588 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4589
4590 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4591 unsigned EltSize = 8;
4592 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4593 while (EltSize != VT.getScalarSizeInBits()) {
4594 EltSize *= 2;
4595 NumElts /= 2;
4596 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4597 Val = DAG.getNode(
4598 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4599 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4600 }
4601
4602 return Val;
Tim Northover3b0846e2014-05-24 12:50:23 +00004603}
4604
4605SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4606
4607 if (Op.getValueType().isVector())
4608 return LowerVSETCC(Op, DAG);
4609
4610 SDValue LHS = Op.getOperand(0);
4611 SDValue RHS = Op.getOperand(1);
4612 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4613 SDLoc dl(Op);
4614
4615 // We chose ZeroOrOneBooleanContents, so use zero and one.
4616 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004617 SDValue TVal = DAG.getConstant(1, dl, VT);
4618 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004619
4620 // Handle f128 first, since one possible outcome is a normal integer
4621 // comparison which gets picked up by the next if statement.
4622 if (LHS.getValueType() == MVT::f128) {
4623 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4624
4625 // If softenSetCCOperands returned a scalar, use it.
4626 if (!RHS.getNode()) {
4627 assert(LHS.getValueType() == Op.getValueType() &&
4628 "Unexpected setcc expansion!");
4629 return LHS;
4630 }
4631 }
4632
4633 if (LHS.getValueType().isInteger()) {
4634 SDValue CCVal;
4635 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004636 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004637
4638 // Note that we inverted the condition above, so we reverse the order of
4639 // the true and false operands here. This will allow the setcc to be
4640 // matched to a single CSINC instruction.
4641 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4642 }
4643
4644 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004645 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4646 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004647
4648 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4649 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004650 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004651
4652 AArch64CC::CondCode CC1, CC2;
4653 changeFPCCToAArch64CC(CC, CC1, CC2);
4654 if (CC2 == AArch64CC::AL) {
4655 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004656 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004657
4658 // Note that we inverted the condition above, so we reverse the order of
4659 // the true and false operands here. This will allow the setcc to be
4660 // matched to a single CSINC instruction.
4661 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4662 } else {
4663 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4664 // totally clean. Some of them require two CSELs to implement. As is in
4665 // this case, we emit the first CSEL and then emit a second using the output
4666 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4667
4668 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004669 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004670 SDValue CS1 =
4671 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4672
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004673 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004674 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4675 }
4676}
4677
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004678SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4679 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004680 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004681 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004682 // Handle f128 first, because it will result in a comparison of some RTLIB
4683 // call result against zero.
4684 if (LHS.getValueType() == MVT::f128) {
4685 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4686
4687 // If softenSetCCOperands returned a scalar, we need to compare the result
4688 // against zero to select between true and false values.
4689 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004690 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004691 CC = ISD::SETNE;
4692 }
4693 }
4694
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004695 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004696 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004697 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4698 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4699 }
4700
4701 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004702 if (LHS.getValueType().isInteger()) {
4703 assert((LHS.getValueType() == RHS.getValueType()) &&
4704 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4705
4706 unsigned Opcode = AArch64ISD::CSEL;
4707
4708 // If both the TVal and the FVal are constants, see if we can swap them in
4709 // order to for a CSINV or CSINC out of them.
4710 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4711 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4712
4713 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4714 std::swap(TVal, FVal);
4715 std::swap(CTVal, CFVal);
4716 CC = ISD::getSetCCInverse(CC, true);
4717 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4718 std::swap(TVal, FVal);
4719 std::swap(CTVal, CFVal);
4720 CC = ISD::getSetCCInverse(CC, true);
4721 } else if (TVal.getOpcode() == ISD::XOR) {
4722 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4723 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004724 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004725 std::swap(TVal, FVal);
4726 std::swap(CTVal, CFVal);
4727 CC = ISD::getSetCCInverse(CC, true);
4728 }
4729 } else if (TVal.getOpcode() == ISD::SUB) {
4730 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4731 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004732 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004733 std::swap(TVal, FVal);
4734 std::swap(CTVal, CFVal);
4735 CC = ISD::getSetCCInverse(CC, true);
4736 }
4737 } else if (CTVal && CFVal) {
4738 const int64_t TrueVal = CTVal->getSExtValue();
4739 const int64_t FalseVal = CFVal->getSExtValue();
4740 bool Swap = false;
4741
4742 // If both TVal and FVal are constants, see if FVal is the
4743 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4744 // instead of a CSEL in that case.
4745 if (TrueVal == ~FalseVal) {
4746 Opcode = AArch64ISD::CSINV;
4747 } else if (TrueVal == -FalseVal) {
4748 Opcode = AArch64ISD::CSNEG;
4749 } else if (TVal.getValueType() == MVT::i32) {
4750 // If our operands are only 32-bit wide, make sure we use 32-bit
4751 // arithmetic for the check whether we can use CSINC. This ensures that
4752 // the addition in the check will wrap around properly in case there is
4753 // an overflow (which would not be the case if we do the check with
4754 // 64-bit arithmetic).
4755 const uint32_t TrueVal32 = CTVal->getZExtValue();
4756 const uint32_t FalseVal32 = CFVal->getZExtValue();
4757
4758 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4759 Opcode = AArch64ISD::CSINC;
4760
4761 if (TrueVal32 > FalseVal32) {
4762 Swap = true;
4763 }
4764 }
4765 // 64-bit check whether we can use CSINC.
4766 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4767 Opcode = AArch64ISD::CSINC;
4768
4769 if (TrueVal > FalseVal) {
4770 Swap = true;
4771 }
4772 }
4773
4774 // Swap TVal and FVal if necessary.
4775 if (Swap) {
4776 std::swap(TVal, FVal);
4777 std::swap(CTVal, CFVal);
4778 CC = ISD::getSetCCInverse(CC, true);
4779 }
4780
4781 if (Opcode != AArch64ISD::CSEL) {
4782 // Drop FVal since we can get its value by simply inverting/negating
4783 // TVal.
4784 FVal = TVal;
4785 }
4786 }
4787
Chad Rosier58f505b2016-08-26 18:05:50 +00004788 // Avoid materializing a constant when possible by reusing a known value in
4789 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004790 // is one, zero or negative one in the case of a CSEL. We can always
4791 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4792 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004793 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4794 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4795 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4796 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4797 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4798 // "a != C ? x : a" to avoid materializing C.
4799 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4800 TVal = LHS;
4801 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4802 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004803 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4804 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4805 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4806 // avoid materializing C.
4807 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4808 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4809 Opcode = AArch64ISD::CSINV;
4810 TVal = LHS;
4811 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4812 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004813 }
4814
Tim Northover3b0846e2014-05-24 12:50:23 +00004815 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004816 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004817 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004818 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4819 }
4820
4821 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004822 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4823 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004824 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004825 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004826 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004827
4828 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4829 // clean. Some of them require two CSELs to implement.
4830 AArch64CC::CondCode CC1, CC2;
4831 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004832
4833 if (DAG.getTarget().Options.UnsafeFPMath) {
4834 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4835 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4836 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4837 if (RHSVal && RHSVal->isZero()) {
4838 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4839 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4840
4841 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004842 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004843 TVal = LHS;
4844 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004845 CFVal && CFVal->isZero() &&
4846 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004847 FVal = LHS;
4848 }
4849 }
4850
4851 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004852 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004853 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4854
4855 // If we need a second CSEL, emit it, using the output of the first as the
4856 // RHS. We're effectively OR'ing the two CC's together.
4857 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004858 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004859 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4860 }
4861
4862 // Otherwise, return the output of the first CSEL.
4863 return CS1;
4864}
4865
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004866SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4867 SelectionDAG &DAG) const {
4868 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4869 SDValue LHS = Op.getOperand(0);
4870 SDValue RHS = Op.getOperand(1);
4871 SDValue TVal = Op.getOperand(2);
4872 SDValue FVal = Op.getOperand(3);
4873 SDLoc DL(Op);
4874 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4875}
4876
4877SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4878 SelectionDAG &DAG) const {
4879 SDValue CCVal = Op->getOperand(0);
4880 SDValue TVal = Op->getOperand(1);
4881 SDValue FVal = Op->getOperand(2);
4882 SDLoc DL(Op);
4883
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004884 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4885 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004886 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004887 // Only lower legal XALUO ops.
4888 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4889 return SDValue();
4890
4891 AArch64CC::CondCode OFCC;
4892 SDValue Value, Overflow;
4893 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004894 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004895
4896 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4897 CCVal, Overflow);
4898 }
4899
4900 // Lower it the same way as we would lower a SELECT_CC node.
4901 ISD::CondCode CC;
4902 SDValue LHS, RHS;
4903 if (CCVal.getOpcode() == ISD::SETCC) {
4904 LHS = CCVal.getOperand(0);
4905 RHS = CCVal.getOperand(1);
4906 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4907 } else {
4908 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004909 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004910 CC = ISD::SETNE;
4911 }
4912 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4913}
4914
Tim Northover3b0846e2014-05-24 12:50:23 +00004915SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4916 SelectionDAG &DAG) const {
4917 // Jump table entries as PC relative offsets. No additional tweaking
4918 // is necessary here. Just get the address of the jump table.
4919 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004920
4921 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4922 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004923 return getAddrLarge(JT, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004924 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4925 return getAddrTiny(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004926 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004927 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004928}
4929
Tim Northover1c353412018-10-24 20:19:09 +00004930SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
4931 SelectionDAG &DAG) const {
4932 // Jump table entries as PC relative offsets. No additional tweaking
4933 // is necessary here. Just get the address of the jump table.
4934 SDLoc DL(Op);
4935 SDValue JT = Op.getOperand(1);
4936 SDValue Entry = Op.getOperand(2);
4937 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
4938
4939 SDNode *Dest =
4940 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
4941 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
4942 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
4943 SDValue(Dest, 0));
4944}
4945
Tim Northover3b0846e2014-05-24 12:50:23 +00004946SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4947 SelectionDAG &DAG) const {
4948 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004949
4950 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4951 // Use the GOT for the large code model on iOS.
4952 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004953 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004954 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004955 return getAddrLarge(CP, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004956 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4957 return getAddrTiny(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004958 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004959 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004960 }
4961}
4962
4963SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4964 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004965 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004966 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4967 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004968 return getAddrLarge(BA, DAG);
David Green9dd1d452018-08-22 11:31:39 +00004969 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4970 return getAddrTiny(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004971 }
David Green9dd1d452018-08-22 11:31:39 +00004972 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004973}
4974
4975SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4976 SelectionDAG &DAG) const {
4977 AArch64FunctionInfo *FuncInfo =
4978 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4979
4980 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004981 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4982 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004983 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4984 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004985 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004986}
4987
Martin Storsjo68266fa2017-07-13 17:03:12 +00004988SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4989 SelectionDAG &DAG) const {
4990 AArch64FunctionInfo *FuncInfo =
4991 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4992
4993 SDLoc DL(Op);
4994 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4995 ? FuncInfo->getVarArgsGPRIndex()
4996 : FuncInfo->getVarArgsStackIndex(),
4997 getPointerTy(DAG.getDataLayout()));
4998 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4999 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5000 MachinePointerInfo(SV));
5001}
5002
Tim Northover3b0846e2014-05-24 12:50:23 +00005003SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5004 SelectionDAG &DAG) const {
5005 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5006 // Standard, section B.3.
5007 MachineFunction &MF = DAG.getMachineFunction();
5008 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00005009 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005010 SDLoc DL(Op);
5011
5012 SDValue Chain = Op.getOperand(0);
5013 SDValue VAList = Op.getOperand(1);
5014 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5015 SmallVector<SDValue, 4> MemOps;
5016
5017 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00005018 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005019 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00005020 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005021
5022 // void *__gr_top at offset 8
5023 int GPRSize = FuncInfo->getVarArgsGPRSize();
5024 if (GPRSize > 0) {
5025 SDValue GRTop, GRTopAddr;
5026
Mehdi Amini44ede332015-07-09 02:09:04 +00005027 GRTopAddr =
5028 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005029
Mehdi Amini44ede332015-07-09 02:09:04 +00005030 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5031 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5032 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005033
5034 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005035 MachinePointerInfo(SV, 8),
5036 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005037 }
5038
5039 // void *__vr_top at offset 16
5040 int FPRSize = FuncInfo->getVarArgsFPRSize();
5041 if (FPRSize > 0) {
5042 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00005043 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5044 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005045
Mehdi Amini44ede332015-07-09 02:09:04 +00005046 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5047 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5048 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005049
5050 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005051 MachinePointerInfo(SV, 16),
5052 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00005053 }
5054
5055 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00005056 SDValue GROffsAddr =
5057 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005058 MemOps.push_back(DAG.getStore(
5059 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5060 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005061
5062 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00005063 SDValue VROffsAddr =
5064 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00005065 MemOps.push_back(DAG.getStore(
5066 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5067 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00005068
5069 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5070}
5071
5072SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5073 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00005074 MachineFunction &MF = DAG.getMachineFunction();
5075
Matthias Braunf1caa282017-12-15 22:22:58 +00005076 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00005077 return LowerWin64_VASTART(Op, DAG);
5078 else if (Subtarget->isTargetDarwin())
5079 return LowerDarwin_VASTART(Op, DAG);
5080 else
5081 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00005082}
5083
5084SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5085 SelectionDAG &DAG) const {
5086 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5087 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005088 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00005089 unsigned VaListSize =
5090 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00005091 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5092 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5093
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005094 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5095 Op.getOperand(2),
5096 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00005097 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00005098 MachinePointerInfo(SrcSV));
5099}
5100
5101SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5102 assert(Subtarget->isTargetDarwin() &&
5103 "automatic va_arg instruction only works on Darwin");
5104
5105 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5106 EVT VT = Op.getValueType();
5107 SDLoc DL(Op);
5108 SDValue Chain = Op.getOperand(0);
5109 SDValue Addr = Op.getOperand(1);
5110 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00005111 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00005112
Justin Lebar9c375812016-07-15 18:27:10 +00005113 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005114 Chain = VAList.getValue(1);
5115
5116 if (Align > 8) {
5117 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00005118 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5119 DAG.getConstant(Align - 1, DL, PtrVT));
5120 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5121 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005122 }
5123
5124 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00005125 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00005126
5127 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5128 // up to 64 bits. At the very least, we have to increase the striding of the
5129 // vaargs list to match this, and for FP values we need to introduce
5130 // FP_ROUND nodes as well.
5131 if (VT.isInteger() && !VT.isVector())
5132 ArgSize = 8;
5133 bool NeedFPTrunc = false;
5134 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5135 ArgSize = 8;
5136 NeedFPTrunc = true;
5137 }
5138
5139 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00005140 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5141 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00005142 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00005143 SDValue APStore =
5144 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00005145
5146 // Load the actual argument out of the pointer VAList
5147 if (NeedFPTrunc) {
5148 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00005149 SDValue WideFP =
5150 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005151 // Round the value down to an f32.
5152 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005153 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00005154 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5155 // Merge the rounded value with the chain output of the load.
5156 return DAG.getMergeValues(Ops, DL);
5157 }
5158
Justin Lebar9c375812016-07-15 18:27:10 +00005159 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005160}
5161
5162SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5163 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00005164 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5165 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005166
5167 EVT VT = Op.getValueType();
5168 SDLoc DL(Op);
5169 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5170 SDValue FrameAddr =
5171 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5172 while (Depth--)
5173 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00005174 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005175 return FrameAddr;
5176}
5177
Mandeep Singh Grang547a0d72018-11-01 23:22:25 +00005178SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5179 SelectionDAG &DAG) const {
5180 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5181
5182 EVT VT = getPointerTy(DAG.getDataLayout());
5183 SDLoc DL(Op);
5184 int FI = MFI.CreateFixedObject(4, 0, false);
5185 return DAG.getFrameIndex(FI, VT);
5186}
5187
Tim Northover3b0846e2014-05-24 12:50:23 +00005188// FIXME? Maybe this could be a TableGen attribute on some registers and
5189// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00005190unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5191 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005192 unsigned Reg = StringSwitch<unsigned>(RegName)
5193 .Case("sp", AArch64::SP)
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005194 .Case("x1", AArch64::X1)
5195 .Case("w1", AArch64::W1)
5196 .Case("x2", AArch64::X2)
5197 .Case("w2", AArch64::W2)
5198 .Case("x3", AArch64::X3)
5199 .Case("w3", AArch64::W3)
5200 .Case("x4", AArch64::X4)
5201 .Case("w4", AArch64::W4)
5202 .Case("x5", AArch64::X5)
5203 .Case("w5", AArch64::W5)
5204 .Case("x6", AArch64::X6)
5205 .Case("w6", AArch64::W6)
5206 .Case("x7", AArch64::X7)
5207 .Case("w7", AArch64::W7)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005208 .Case("x18", AArch64::X18)
5209 .Case("w18", AArch64::W18)
Petr Hosek72509082018-06-12 20:00:50 +00005210 .Case("x20", AArch64::X20)
5211 .Case("w20", AArch64::W20)
Tim Northover3b0846e2014-05-24 12:50:23 +00005212 .Default(0);
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005213 if (((Reg == AArch64::X1 || Reg == AArch64::W1) &&
5214 !Subtarget->isXRegisterReserved(1)) ||
5215 ((Reg == AArch64::X2 || Reg == AArch64::W2) &&
5216 !Subtarget->isXRegisterReserved(2)) ||
5217 ((Reg == AArch64::X3 || Reg == AArch64::W3) &&
5218 !Subtarget->isXRegisterReserved(3)) ||
5219 ((Reg == AArch64::X4 || Reg == AArch64::W4) &&
5220 !Subtarget->isXRegisterReserved(4)) ||
5221 ((Reg == AArch64::X5 || Reg == AArch64::W5) &&
5222 !Subtarget->isXRegisterReserved(5)) ||
5223 ((Reg == AArch64::X6 || Reg == AArch64::W6) &&
5224 !Subtarget->isXRegisterReserved(6)) ||
5225 ((Reg == AArch64::X7 || Reg == AArch64::W7) &&
5226 !Subtarget->isXRegisterReserved(7)) ||
5227 ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
5228 !Subtarget->isXRegisterReserved(18)) ||
Petr Hosek72509082018-06-12 20:00:50 +00005229 ((Reg == AArch64::X20 || Reg == AArch64::W20) &&
Nick Desaulniers287a3be2018-09-07 20:58:57 +00005230 !Subtarget->isXRegisterReserved(20)))
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00005231 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00005232 if (Reg)
5233 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00005234 report_fatal_error(Twine("Invalid register name \""
5235 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00005236}
5237
Mandeep Singh Grangdf19e572018-11-01 21:23:47 +00005238SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5239 SelectionDAG &DAG) const {
5240 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5241
5242 EVT VT = Op.getValueType();
5243 SDLoc DL(Op);
5244
5245 SDValue FrameAddr =
5246 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5247 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5248
5249 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5250}
5251
Tim Northover3b0846e2014-05-24 12:50:23 +00005252SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5253 SelectionDAG &DAG) const {
5254 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00005255 MachineFrameInfo &MFI = MF.getFrameInfo();
5256 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00005257
5258 EVT VT = Op.getValueType();
5259 SDLoc DL(Op);
5260 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5261 if (Depth) {
5262 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00005263 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005264 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5265 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00005266 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00005267 }
5268
5269 // Return LR, which contains the return address. Mark it an implicit live-in.
5270 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5271 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5272}
5273
5274/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5275/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5276SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5277 SelectionDAG &DAG) const {
5278 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5279 EVT VT = Op.getValueType();
5280 unsigned VTBits = VT.getSizeInBits();
5281 SDLoc dl(Op);
5282 SDValue ShOpLo = Op.getOperand(0);
5283 SDValue ShOpHi = Op.getOperand(1);
5284 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005285 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5286
5287 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5288
5289 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005290 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005291 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5292
5293 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5294 // is "undef". We wanted 0, so CSEL it directly.
5295 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5296 ISD::SETEQ, dl, DAG);
5297 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5298 HiBitsForLo =
5299 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5300 HiBitsForLo, CCVal, Cmp);
5301
Tim Northover3b0846e2014-05-24 12:50:23 +00005302 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005303 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005304
Tim Northoverf3be9d52015-12-02 00:33:54 +00005305 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5306 SDValue LoForNormalShift =
5307 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005308
Tim Northoverf3be9d52015-12-02 00:33:54 +00005309 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5310 dl, DAG);
5311 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5312 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5313 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5314 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005315
5316 // AArch64 shifts larger than the register width are wrapped rather than
5317 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00005318 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5319 SDValue HiForBigShift =
5320 Opc == ISD::SRA
5321 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5322 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5323 : DAG.getConstant(0, dl, VT);
5324 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5325 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005326
5327 SDValue Ops[2] = { Lo, Hi };
5328 return DAG.getMergeValues(Ops, dl);
5329}
5330
5331/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5332/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5333SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00005334 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005335 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5336 EVT VT = Op.getValueType();
5337 unsigned VTBits = VT.getSizeInBits();
5338 SDLoc dl(Op);
5339 SDValue ShOpLo = Op.getOperand(0);
5340 SDValue ShOpHi = Op.getOperand(1);
5341 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00005342
5343 assert(Op.getOpcode() == ISD::SHL_PARTS);
5344 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005345 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00005346 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5347
5348 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5349 // is "undef". We wanted 0, so CSEL it directly.
5350 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5351 ISD::SETEQ, dl, DAG);
5352 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5353 LoBitsForHi =
5354 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5355 LoBitsForHi, CCVal, Cmp);
5356
Tim Northover3b0846e2014-05-24 12:50:23 +00005357 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005358 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00005359 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5360 SDValue HiForNormalShift =
5361 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00005362
Tim Northoverf3be9d52015-12-02 00:33:54 +00005363 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00005364
Tim Northoverf3be9d52015-12-02 00:33:54 +00005365 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5366 dl, DAG);
5367 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5368 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5369 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005370
5371 // AArch64 shifts of larger than register sizes are wrapped rather than
5372 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00005373 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5374 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5375 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5376 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00005377
5378 SDValue Ops[2] = { Lo, Hi };
5379 return DAG.getMergeValues(Ops, dl);
5380}
5381
5382bool AArch64TargetLowering::isOffsetFoldingLegal(
5383 const GlobalAddressSDNode *GA) const {
Peter Collingbourne5ab4a472018-04-23 19:09:34 +00005384 // Offsets are folded in the DAG combine rather than here so that we can
5385 // intelligently choose an offset based on the uses.
Peter Collingbournea7d936f2018-04-10 16:19:30 +00005386 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00005387}
5388
5389bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
5390 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
5391 // FIXME: We should be able to handle f128 as well with a clever lowering.
Sjoerd Meijer5ea465d2018-02-08 08:39:05 +00005392 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
5393 (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
JF Bastienda339002018-09-05 23:38:11 +00005394 LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString() << " imm value: 0\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005395 return true;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005396 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005397
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005398 bool IsLegal = false;
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00005399 SmallString<128> ImmStrVal;
5400 Imm.toString(ImmStrVal);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005401
JF Bastienda339002018-09-05 23:38:11 +00005402 if (VT == MVT::f64)
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005403 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
JF Bastienda339002018-09-05 23:38:11 +00005404 else if (VT == MVT::f32)
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005405 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
JF Bastienda339002018-09-05 23:38:11 +00005406 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005407 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005408
5409 if (IsLegal) {
JF Bastienda339002018-09-05 23:38:11 +00005410 LLVM_DEBUG(dbgs() << "Legal " << VT.getEVTString()
5411 << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00005412 return true;
5413 }
5414
JF Bastienda339002018-09-05 23:38:11 +00005415 LLVM_DEBUG(dbgs() << "Illegal " << VT.getEVTString()
5416 << " imm value: " << ImmStrVal << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005417 return false;
5418}
5419
5420//===----------------------------------------------------------------------===//
5421// AArch64 Optimization Hooks
5422//===----------------------------------------------------------------------===//
5423
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005424static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5425 SDValue Operand, SelectionDAG &DAG,
5426 int &ExtraSteps) {
5427 EVT VT = Operand.getValueType();
5428 if (ST->hasNEON() &&
5429 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5430 VT == MVT::f32 || VT == MVT::v1f32 ||
5431 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5432 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5433 // For the reciprocal estimates, convergence is quadratic, so the number
5434 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5435 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5436 // the result for float (23 mantissa bits) is 2 and for double (52
5437 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00005438 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005439
5440 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5441 }
5442
5443 return SDValue();
5444}
5445
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005446SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5447 SelectionDAG &DAG, int Enabled,
5448 int &ExtraSteps,
5449 bool &UseOneConst,
5450 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005451 if (Enabled == ReciprocalEstimate::Enabled ||
5452 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5453 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5454 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005455 SDLoc DL(Operand);
5456 EVT VT = Operand.getValueType();
5457
5458 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005459 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005460
5461 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5462 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5463 for (int i = ExtraSteps; i > 0; --i) {
5464 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005465 Flags);
5466 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5467 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005468 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005469 if (!Reciprocal) {
5470 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5471 VT);
5472 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5473 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5474
Amara Emersond28f0cd42017-05-01 15:17:51 +00005475 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005476 // Correct the result if the operand is 0.0.
5477 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5478 VT, Eq, Operand, Estimate);
5479 }
5480
5481 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005482 return Estimate;
5483 }
5484
5485 return SDValue();
5486}
5487
5488SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5489 SelectionDAG &DAG, int Enabled,
5490 int &ExtraSteps) const {
5491 if (Enabled == ReciprocalEstimate::Enabled)
5492 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005493 DAG, ExtraSteps)) {
5494 SDLoc DL(Operand);
5495 EVT VT = Operand.getValueType();
5496
5497 SDNodeFlags Flags;
Michael Berg7acc81b2018-05-04 18:48:20 +00005498 Flags.setAllowReassociation(true);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005499
5500 // Newton reciprocal iteration: E * (2 - X * E)
5501 // AArch64 reciprocal iteration instruction: (2 - M * N)
5502 for (int i = ExtraSteps; i > 0; --i) {
5503 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005504 Estimate, Flags);
5505 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005506 }
5507
5508 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005509 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005510 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005511
5512 return SDValue();
5513}
5514
Tim Northover3b0846e2014-05-24 12:50:23 +00005515//===----------------------------------------------------------------------===//
5516// AArch64 Inline Assembly Support
5517//===----------------------------------------------------------------------===//
5518
5519// Table of Constraints
5520// TODO: This is the current set of constraints supported by ARM for the
Peter Smithc8117582018-05-16 09:33:25 +00005521// compiler, not all of them may make sense.
Tim Northover3b0846e2014-05-24 12:50:23 +00005522//
5523// r - A general register
5524// w - An FP/SIMD register of some size in the range v0-v31
5525// x - An FP/SIMD register of some size in the range v0-v15
5526// I - Constant that can be used with an ADD instruction
5527// J - Constant that can be used with a SUB instruction
5528// K - Constant that can be used with a 32-bit logical instruction
5529// L - Constant that can be used with a 64-bit logical instruction
5530// M - Constant that can be used as a 32-bit MOV immediate
5531// N - Constant that can be used as a 64-bit MOV immediate
5532// Q - A memory reference with base register and no offset
5533// S - A symbolic address
5534// Y - Floating point constant zero
5535// Z - Integer constant zero
5536//
5537// Note that general register operands will be output using their 64-bit x
5538// register name, whatever the size of the variable, unless the asm operand
5539// is prefixed by the %w modifier. Floating-point and SIMD register operands
5540// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5541// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005542const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5543 // At this point, we have to lower this constraint to something else, so we
5544 // lower it to an "r" or "w". However, by doing this we will force the result
5545 // to be in register, while the X constraint is much more permissive.
5546 //
5547 // Although we are correct (we are free to emit anything, without
5548 // constraints), we might break use cases that would expect us to be more
5549 // efficient and emit something else.
5550 if (!Subtarget->hasFPARMv8())
5551 return "r";
5552
5553 if (ConstraintVT.isFloatingPoint())
5554 return "w";
5555
5556 if (ConstraintVT.isVector() &&
5557 (ConstraintVT.getSizeInBits() == 64 ||
5558 ConstraintVT.getSizeInBits() == 128))
5559 return "w";
5560
5561 return "r";
5562}
Tim Northover3b0846e2014-05-24 12:50:23 +00005563
5564/// getConstraintType - Given a constraint letter, return the type of
5565/// constraint it is for this target.
5566AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005567AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005568 if (Constraint.size() == 1) {
5569 switch (Constraint[0]) {
5570 default:
5571 break;
5572 case 'z':
5573 return C_Other;
5574 case 'x':
5575 case 'w':
5576 return C_RegisterClass;
5577 // An address with a single base register. Due to the way we
5578 // currently handle addresses it is the same as 'r'.
5579 case 'Q':
5580 return C_Memory;
Peter Smithc8117582018-05-16 09:33:25 +00005581 case 'S': // A symbolic address
5582 return C_Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00005583 }
5584 }
5585 return TargetLowering::getConstraintType(Constraint);
5586}
5587
5588/// Examine constraint type and operand type and determine a weight value.
5589/// This object must already have been set up with the operand type
5590/// and the current alternative constraint selected.
5591TargetLowering::ConstraintWeight
5592AArch64TargetLowering::getSingleConstraintMatchWeight(
5593 AsmOperandInfo &info, const char *constraint) const {
5594 ConstraintWeight weight = CW_Invalid;
5595 Value *CallOperandVal = info.CallOperandVal;
5596 // If we don't have a value, we can't do a match,
5597 // but allow it at the lowest weight.
5598 if (!CallOperandVal)
5599 return CW_Default;
5600 Type *type = CallOperandVal->getType();
5601 // Look at the constraint type.
5602 switch (*constraint) {
5603 default:
5604 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5605 break;
5606 case 'x':
5607 case 'w':
5608 if (type->isFloatingPointTy() || type->isVectorTy())
5609 weight = CW_Register;
5610 break;
5611 case 'z':
5612 weight = CW_Constant;
5613 break;
5614 }
5615 return weight;
5616}
5617
5618std::pair<unsigned, const TargetRegisterClass *>
5619AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005620 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005621 if (Constraint.size() == 1) {
5622 switch (Constraint[0]) {
5623 case 'r':
5624 if (VT.getSizeInBits() == 64)
5625 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5626 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5627 case 'w':
Eli Friedman071203b2018-08-24 19:12:13 +00005628 if (!Subtarget->hasFPARMv8())
5629 break;
Amara Emerson614b44b2016-11-07 15:42:12 +00005630 if (VT.getSizeInBits() == 16)
5631 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005632 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005633 return std::make_pair(0U, &AArch64::FPR32RegClass);
5634 if (VT.getSizeInBits() == 64)
5635 return std::make_pair(0U, &AArch64::FPR64RegClass);
5636 if (VT.getSizeInBits() == 128)
5637 return std::make_pair(0U, &AArch64::FPR128RegClass);
5638 break;
5639 // The instructions that this constraint is designed for can
5640 // only take 128-bit registers so just use that regclass.
5641 case 'x':
Eli Friedman071203b2018-08-24 19:12:13 +00005642 if (!Subtarget->hasFPARMv8())
5643 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00005644 if (VT.getSizeInBits() == 128)
5645 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5646 break;
5647 }
5648 }
5649 if (StringRef("{cc}").equals_lower(Constraint))
5650 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5651
5652 // Use the default implementation in TargetLowering to convert the register
5653 // constraint into a member of a register class.
5654 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005655 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005656
5657 // Not found as a standard register?
5658 if (!Res.second) {
5659 unsigned Size = Constraint.size();
5660 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5661 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005662 int RegNo;
5663 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5664 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005665 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005666 // By default we'll emit v0-v31 for this unless there's a modifier where
5667 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005668 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5669 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5670 Res.second = &AArch64::FPR64RegClass;
5671 } else {
5672 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5673 Res.second = &AArch64::FPR128RegClass;
5674 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005675 }
5676 }
5677 }
5678
Eli Friedman071203b2018-08-24 19:12:13 +00005679 if (Res.second && !Subtarget->hasFPARMv8() &&
5680 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5681 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5682 return std::make_pair(0U, nullptr);
5683
Tim Northover3b0846e2014-05-24 12:50:23 +00005684 return Res;
5685}
5686
5687/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5688/// vector. If it is invalid, don't add anything to Ops.
5689void AArch64TargetLowering::LowerAsmOperandForConstraint(
5690 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5691 SelectionDAG &DAG) const {
5692 SDValue Result;
5693
5694 // Currently only support length 1 constraints.
5695 if (Constraint.length() != 1)
5696 return;
5697
5698 char ConstraintLetter = Constraint[0];
5699 switch (ConstraintLetter) {
5700 default:
5701 break;
5702
5703 // This set of constraints deal with valid constants for various instructions.
5704 // Validate and return a target constant for them if we can.
5705 case 'z': {
5706 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005707 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005708 return;
5709
5710 if (Op.getValueType() == MVT::i64)
5711 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5712 else
5713 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5714 break;
5715 }
Peter Smithc8117582018-05-16 09:33:25 +00005716 case 'S': {
5717 // An absolute symbolic address or label reference.
5718 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5719 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5720 GA->getValueType(0));
5721 } else if (const BlockAddressSDNode *BA =
5722 dyn_cast<BlockAddressSDNode>(Op)) {
5723 Result =
5724 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5725 } else if (const ExternalSymbolSDNode *ES =
5726 dyn_cast<ExternalSymbolSDNode>(Op)) {
5727 Result =
5728 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5729 } else
5730 return;
5731 break;
5732 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005733
5734 case 'I':
5735 case 'J':
5736 case 'K':
5737 case 'L':
5738 case 'M':
5739 case 'N':
5740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5741 if (!C)
5742 return;
5743
5744 // Grab the value and do some validation.
5745 uint64_t CVal = C->getZExtValue();
5746 switch (ConstraintLetter) {
5747 // The I constraint applies only to simple ADD or SUB immediate operands:
5748 // i.e. 0 to 4095 with optional shift by 12
5749 // The J constraint applies only to ADD or SUB immediates that would be
5750 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5751 // instruction [or vice versa], in other words -1 to -4095 with optional
5752 // left shift by 12.
5753 case 'I':
5754 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5755 break;
5756 return;
5757 case 'J': {
5758 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005759 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5760 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005761 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005762 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005763 return;
5764 }
5765 // The K and L constraints apply *only* to logical immediates, including
5766 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5767 // been removed and MOV should be used). So these constraints have to
5768 // distinguish between bit patterns that are valid 32-bit or 64-bit
5769 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5770 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5771 // versa.
5772 case 'K':
5773 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5774 break;
5775 return;
5776 case 'L':
5777 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5778 break;
5779 return;
5780 // The M and N constraints are a superset of K and L respectively, for use
5781 // with the MOV (immediate) alias. As well as the logical immediates they
5782 // also match 32 or 64-bit immediates that can be loaded either using a
5783 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5784 // (M) or 64-bit 0x1234000000000000 (N) etc.
5785 // As a note some of this code is liberally stolen from the asm parser.
5786 case 'M': {
5787 if (!isUInt<32>(CVal))
5788 return;
5789 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5790 break;
5791 if ((CVal & 0xFFFF) == CVal)
5792 break;
5793 if ((CVal & 0xFFFF0000ULL) == CVal)
5794 break;
5795 uint64_t NCVal = ~(uint32_t)CVal;
5796 if ((NCVal & 0xFFFFULL) == NCVal)
5797 break;
5798 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5799 break;
5800 return;
5801 }
5802 case 'N': {
5803 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5804 break;
5805 if ((CVal & 0xFFFFULL) == CVal)
5806 break;
5807 if ((CVal & 0xFFFF0000ULL) == CVal)
5808 break;
5809 if ((CVal & 0xFFFF00000000ULL) == CVal)
5810 break;
5811 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5812 break;
5813 uint64_t NCVal = ~CVal;
5814 if ((NCVal & 0xFFFFULL) == NCVal)
5815 break;
5816 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5817 break;
5818 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5819 break;
5820 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5821 break;
5822 return;
5823 }
5824 default:
5825 return;
5826 }
5827
5828 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005829 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005830 break;
5831 }
5832
5833 if (Result.getNode()) {
5834 Ops.push_back(Result);
5835 return;
5836 }
5837
5838 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5839}
5840
5841//===----------------------------------------------------------------------===//
5842// AArch64 Advanced SIMD Support
5843//===----------------------------------------------------------------------===//
5844
5845/// WidenVector - Given a value in the V64 register class, produce the
5846/// equivalent value in the V128 register class.
5847static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5848 EVT VT = V64Reg.getValueType();
5849 unsigned NarrowSize = VT.getVectorNumElements();
5850 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5851 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5852 SDLoc DL(V64Reg);
5853
5854 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005855 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005856}
5857
5858/// getExtFactor - Determine the adjustment factor for the position when
5859/// generating an "extract from vector registers" instruction.
5860static unsigned getExtFactor(SDValue &V) {
5861 EVT EltType = V.getValueType().getVectorElementType();
5862 return EltType.getSizeInBits() / 8;
5863}
5864
5865/// NarrowVector - Given a value in the V128 register class, produce the
5866/// equivalent value in the V64 register class.
5867static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5868 EVT VT = V128Reg.getValueType();
5869 unsigned WideSize = VT.getVectorNumElements();
5870 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5871 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5872 SDLoc DL(V128Reg);
5873
5874 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5875}
5876
5877// Gather data to see if the operation can be modelled as a
5878// shuffle in combination with VEXTs.
5879SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5880 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005881 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005882 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005883 SDLoc dl(Op);
5884 EVT VT = Op.getValueType();
5885 unsigned NumElts = VT.getVectorNumElements();
5886
Tim Northover7324e842014-07-24 15:39:55 +00005887 struct ShuffleSourceInfo {
5888 SDValue Vec;
5889 unsigned MinElt;
5890 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005891
Tim Northover7324e842014-07-24 15:39:55 +00005892 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5893 // be compatible with the shuffle we intend to construct. As a result
5894 // ShuffleVec will be some sliding window into the original Vec.
5895 SDValue ShuffleVec;
5896
5897 // Code should guarantee that element i in Vec starts at element "WindowBase
5898 // + i * WindowScale in ShuffleVec".
5899 int WindowBase;
5900 int WindowScale;
5901
Tim Northover7324e842014-07-24 15:39:55 +00005902 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005903 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5904 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5905
5906 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005907 };
5908
5909 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5910 // node.
5911 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005912 for (unsigned i = 0; i < NumElts; ++i) {
5913 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005914 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005915 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005916 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5917 !isa<ConstantSDNode>(V.getOperand(1))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005918 LLVM_DEBUG(
5919 dbgs() << "Reshuffle failed: "
5920 "a shuffle can only come from building a vector from "
5921 "various elements of other vectors, provided their "
5922 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005923 return SDValue();
5924 }
5925
Tim Northover7324e842014-07-24 15:39:55 +00005926 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005927 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005928 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005929 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005930 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005931
Tim Northover7324e842014-07-24 15:39:55 +00005932 // Update the minimum and maximum lane number seen.
5933 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5934 Source->MinElt = std::min(Source->MinElt, EltNo);
5935 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005936 }
5937
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005938 if (Sources.size() > 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005939 LLVM_DEBUG(
5940 dbgs() << "Reshuffle failed: currently only do something sane when at "
5941 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005942 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005943 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005944
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005945 // Find out the smallest element size among result and two sources, and use
5946 // it as element size to build the shuffle_vector.
5947 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005948 for (auto &Source : Sources) {
5949 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005950 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5951 SmallestEltTy = SrcEltTy;
5952 }
5953 }
5954 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005955 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005956 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5957 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005958
Tim Northover7324e842014-07-24 15:39:55 +00005959 // If the source vector is too wide or too narrow, we may nevertheless be able
5960 // to construct a compatible shuffle either by concatenating it with UNDEF or
5961 // extracting a suitable range of elements.
5962 for (auto &Src : Sources) {
5963 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005964
Tim Northover7324e842014-07-24 15:39:55 +00005965 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005966 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005967
5968 // This stage of the search produces a source with the same element type as
5969 // the original, but with a total width matching the BUILD_VECTOR output.
5970 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005971 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5972 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005973
5974 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5975 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005976 // We can pad out the smaller vector for free, so if it's part of a
5977 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005978 Src.ShuffleVec =
5979 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5980 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005981 continue;
5982 }
5983
Tim Northover7324e842014-07-24 15:39:55 +00005984 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005985
James Molloyf497d552014-10-17 17:06:31 +00005986 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00005987 LLVM_DEBUG(
5988 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005989 return SDValue();
5990 }
5991
James Molloyf497d552014-10-17 17:06:31 +00005992 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005993 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005994 Src.ShuffleVec =
5995 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005996 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005997 Src.WindowBase = -NumSrcElts;
5998 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005999 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00006000 Src.ShuffleVec =
6001 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006002 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006003 } else {
6004 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00006005 SDValue VEXTSrc1 =
6006 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006007 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006008 SDValue VEXTSrc2 =
6009 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006010 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00006011 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6012
6013 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006014 VEXTSrc2,
6015 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00006016 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00006017 }
6018 }
6019
Tim Northover7324e842014-07-24 15:39:55 +00006020 // Another possible incompatibility occurs from the vector element types. We
6021 // can fix this by bitcasting the source vectors to the same type we intend
6022 // for the shuffle.
6023 for (auto &Src : Sources) {
6024 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6025 if (SrcEltTy == SmallestEltTy)
6026 continue;
6027 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6028 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6029 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6030 Src.WindowBase *= Src.WindowScale;
6031 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006032
Tim Northover7324e842014-07-24 15:39:55 +00006033 // Final sanity check before we try to actually produce a shuffle.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006034 LLVM_DEBUG(for (auto Src
6035 : Sources)
6036 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
Tim Northover7324e842014-07-24 15:39:55 +00006037
6038 // The stars all align, our next step is to produce the mask for the shuffle.
6039 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006040 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00006041 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006042 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006043 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00006044 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00006045
David Majnemer0d955d02016-08-11 22:21:41 +00006046 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00006047 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6048
6049 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6050 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6051 // segment.
6052 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006053 int BitsDefined =
6054 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00006055 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6056
6057 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6058 // starting at the appropriate offset.
6059 int *LaneMask = &Mask[i * ResMultiplier];
6060
6061 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6062 ExtractBase += NumElts * (Src - Sources.begin());
6063 for (int j = 0; j < LanesDefined; ++j)
6064 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00006065 }
6066
6067 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006068 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006069 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00006070 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006071 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006072
Tim Northover7324e842014-07-24 15:39:55 +00006073 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6074 for (unsigned i = 0; i < Sources.size(); ++i)
6075 ShuffleOps[i] = Sources[i].ShuffleVec;
6076
6077 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00006078 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006079 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6080
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006081 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6082 dbgs() << "Reshuffle, creating node: "; V.dump(););
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006083
6084 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00006085}
6086
6087// check if an EXT instruction can handle the shuffle mask when the
6088// vector sources of the shuffle are the same.
6089static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6090 unsigned NumElts = VT.getVectorNumElements();
6091
6092 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6093 if (M[0] < 0)
6094 return false;
6095
6096 Imm = M[0];
6097
6098 // If this is a VEXT shuffle, the immediate value is the index of the first
6099 // element. The other shuffle indices must be the successive elements after
6100 // the first one.
6101 unsigned ExpectedElt = Imm;
6102 for (unsigned i = 1; i < NumElts; ++i) {
6103 // Increment the expected index. If it wraps around, just follow it
6104 // back to index zero and keep going.
6105 ++ExpectedElt;
6106 if (ExpectedElt == NumElts)
6107 ExpectedElt = 0;
6108
6109 if (M[i] < 0)
6110 continue; // ignore UNDEF indices
6111 if (ExpectedElt != static_cast<unsigned>(M[i]))
6112 return false;
6113 }
6114
6115 return true;
6116}
6117
6118// check if an EXT instruction can handle the shuffle mask when the
6119// vector sources of the shuffle are different.
6120static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6121 unsigned &Imm) {
6122 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00006123 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00006124
6125 // Benefit form APInt to handle overflow when calculating expected element.
6126 unsigned NumElts = VT.getVectorNumElements();
6127 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6128 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6129 // The following shuffle indices must be the successive elements after the
6130 // first real element.
6131 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6132 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6133 if (FirstWrongElt != M.end())
6134 return false;
6135
6136 // The index of an EXT is the first element if it is not UNDEF.
6137 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00006138 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00006139 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6140 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6141 // ExpectedElt is the last mask index plus 1.
6142 Imm = ExpectedElt.getZExtValue();
6143
6144 // There are two difference cases requiring to reverse input vectors.
6145 // For example, for vector <4 x i32> we have the following cases,
6146 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6147 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6148 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6149 // to reverse two input vectors.
6150 if (Imm < NumElts)
6151 ReverseEXT = true;
6152 else
6153 Imm -= NumElts;
6154
6155 return true;
6156}
6157
6158/// isREVMask - Check if a vector shuffle corresponds to a REV
6159/// instruction with the specified blocksize. (The order of the elements
6160/// within each block of the vector is reversed.)
6161static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6162 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6163 "Only possible block sizes for REV are: 16, 32, 64");
6164
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006165 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006166 if (EltSz == 64)
6167 return false;
6168
6169 unsigned NumElts = VT.getVectorNumElements();
6170 unsigned BlockElts = M[0] + 1;
6171 // If the first shuffle index is UNDEF, be optimistic.
6172 if (M[0] < 0)
6173 BlockElts = BlockSize / EltSz;
6174
6175 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6176 return false;
6177
6178 for (unsigned i = 0; i < NumElts; ++i) {
6179 if (M[i] < 0)
6180 continue; // ignore UNDEF indices
6181 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6182 return false;
6183 }
6184
6185 return true;
6186}
6187
6188static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6189 unsigned NumElts = VT.getVectorNumElements();
6190 WhichResult = (M[0] == 0 ? 0 : 1);
6191 unsigned Idx = WhichResult * NumElts / 2;
6192 for (unsigned i = 0; i != NumElts; i += 2) {
6193 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6194 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6195 return false;
6196 Idx += 1;
6197 }
6198
6199 return true;
6200}
6201
6202static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6203 unsigned NumElts = VT.getVectorNumElements();
6204 WhichResult = (M[0] == 0 ? 0 : 1);
6205 for (unsigned i = 0; i != NumElts; ++i) {
6206 if (M[i] < 0)
6207 continue; // ignore UNDEF indices
6208 if ((unsigned)M[i] != 2 * i + WhichResult)
6209 return false;
6210 }
6211
6212 return true;
6213}
6214
6215static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6216 unsigned NumElts = VT.getVectorNumElements();
6217 WhichResult = (M[0] == 0 ? 0 : 1);
6218 for (unsigned i = 0; i < NumElts; i += 2) {
6219 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6220 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6221 return false;
6222 }
6223 return true;
6224}
6225
6226/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6227/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6228/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6229static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6230 unsigned NumElts = VT.getVectorNumElements();
6231 WhichResult = (M[0] == 0 ? 0 : 1);
6232 unsigned Idx = WhichResult * NumElts / 2;
6233 for (unsigned i = 0; i != NumElts; i += 2) {
6234 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6235 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6236 return false;
6237 Idx += 1;
6238 }
6239
6240 return true;
6241}
6242
6243/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6244/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6245/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6246static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6247 unsigned Half = VT.getVectorNumElements() / 2;
6248 WhichResult = (M[0] == 0 ? 0 : 1);
6249 for (unsigned j = 0; j != 2; ++j) {
6250 unsigned Idx = WhichResult;
6251 for (unsigned i = 0; i != Half; ++i) {
6252 int MIdx = M[i + j * Half];
6253 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6254 return false;
6255 Idx += 2;
6256 }
6257 }
6258
6259 return true;
6260}
6261
6262/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6263/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6264/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6265static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6266 unsigned NumElts = VT.getVectorNumElements();
6267 WhichResult = (M[0] == 0 ? 0 : 1);
6268 for (unsigned i = 0; i < NumElts; i += 2) {
6269 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6270 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6271 return false;
6272 }
6273 return true;
6274}
6275
6276static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6277 bool &DstIsLeft, int &Anomaly) {
6278 if (M.size() != static_cast<size_t>(NumInputElements))
6279 return false;
6280
6281 int NumLHSMatch = 0, NumRHSMatch = 0;
6282 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6283
6284 for (int i = 0; i < NumInputElements; ++i) {
6285 if (M[i] == -1) {
6286 ++NumLHSMatch;
6287 ++NumRHSMatch;
6288 continue;
6289 }
6290
6291 if (M[i] == i)
6292 ++NumLHSMatch;
6293 else
6294 LastLHSMismatch = i;
6295
6296 if (M[i] == i + NumInputElements)
6297 ++NumRHSMatch;
6298 else
6299 LastRHSMismatch = i;
6300 }
6301
6302 if (NumLHSMatch == NumInputElements - 1) {
6303 DstIsLeft = true;
6304 Anomaly = LastLHSMismatch;
6305 return true;
6306 } else if (NumRHSMatch == NumInputElements - 1) {
6307 DstIsLeft = false;
6308 Anomaly = LastRHSMismatch;
6309 return true;
6310 }
6311
6312 return false;
6313}
6314
6315static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6316 if (VT.getSizeInBits() != 128)
6317 return false;
6318
6319 unsigned NumElts = VT.getVectorNumElements();
6320
6321 for (int I = 0, E = NumElts / 2; I != E; I++) {
6322 if (Mask[I] != I)
6323 return false;
6324 }
6325
6326 int Offset = NumElts / 2;
6327 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6328 if (Mask[I] != I + SplitLHS * Offset)
6329 return false;
6330 }
6331
6332 return true;
6333}
6334
6335static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6336 SDLoc DL(Op);
6337 EVT VT = Op.getValueType();
6338 SDValue V0 = Op.getOperand(0);
6339 SDValue V1 = Op.getOperand(1);
6340 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6341
6342 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6343 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6344 return SDValue();
6345
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006346 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00006347
6348 if (!isConcatMask(Mask, VT, SplitV0))
6349 return SDValue();
6350
6351 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6352 VT.getVectorNumElements() / 2);
6353 if (SplitV0) {
6354 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006355 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006356 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006357 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006358 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006359 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006360 }
6361 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6362}
6363
6364/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6365/// the specified operations to build the shuffle.
6366static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6367 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006368 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006369 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6370 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6371 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6372
6373 enum {
6374 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6375 OP_VREV,
6376 OP_VDUP0,
6377 OP_VDUP1,
6378 OP_VDUP2,
6379 OP_VDUP3,
6380 OP_VEXT1,
6381 OP_VEXT2,
6382 OP_VEXT3,
6383 OP_VUZPL, // VUZP, left result
6384 OP_VUZPR, // VUZP, right result
6385 OP_VZIPL, // VZIP, left result
6386 OP_VZIPR, // VZIP, right result
6387 OP_VTRNL, // VTRN, left result
6388 OP_VTRNR // VTRN, right result
6389 };
6390
6391 if (OpNum == OP_COPY) {
6392 if (LHSID == (1 * 9 + 2) * 9 + 3)
6393 return LHS;
6394 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6395 return RHS;
6396 }
6397
6398 SDValue OpLHS, OpRHS;
6399 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6400 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6401 EVT VT = OpLHS.getValueType();
6402
6403 switch (OpNum) {
6404 default:
6405 llvm_unreachable("Unknown shuffle opcode!");
6406 case OP_VREV:
6407 // VREV divides the vector in half and swaps within the half.
6408 if (VT.getVectorElementType() == MVT::i32 ||
6409 VT.getVectorElementType() == MVT::f32)
6410 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6411 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00006412 if (VT.getVectorElementType() == MVT::i16 ||
6413 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006414 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6415 // vrev <4 x i8> -> REV16
6416 assert(VT.getVectorElementType() == MVT::i8);
6417 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6418 case OP_VDUP0:
6419 case OP_VDUP1:
6420 case OP_VDUP2:
6421 case OP_VDUP3: {
6422 EVT EltTy = VT.getVectorElementType();
6423 unsigned Opcode;
6424 if (EltTy == MVT::i8)
6425 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00006426 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006427 Opcode = AArch64ISD::DUPLANE16;
6428 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6429 Opcode = AArch64ISD::DUPLANE32;
6430 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6431 Opcode = AArch64ISD::DUPLANE64;
6432 else
6433 llvm_unreachable("Invalid vector element type?");
6434
6435 if (VT.getSizeInBits() == 64)
6436 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006437 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006438 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6439 }
6440 case OP_VEXT1:
6441 case OP_VEXT2:
6442 case OP_VEXT3: {
6443 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6444 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006445 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006446 }
6447 case OP_VUZPL:
6448 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6449 OpRHS);
6450 case OP_VUZPR:
6451 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6452 OpRHS);
6453 case OP_VZIPL:
6454 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6455 OpRHS);
6456 case OP_VZIPR:
6457 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6458 OpRHS);
6459 case OP_VTRNL:
6460 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6461 OpRHS);
6462 case OP_VTRNR:
6463 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6464 OpRHS);
6465 }
6466}
6467
6468static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6469 SelectionDAG &DAG) {
6470 // Check to see if we can use the TBL instruction.
6471 SDValue V1 = Op.getOperand(0);
6472 SDValue V2 = Op.getOperand(1);
6473 SDLoc DL(Op);
6474
6475 EVT EltVT = Op.getValueType().getVectorElementType();
6476 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6477
6478 SmallVector<SDValue, 8> TBLMask;
6479 for (int Val : ShuffleMask) {
6480 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6481 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006482 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006483 }
6484 }
6485
6486 MVT IndexVT = MVT::v8i8;
6487 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006488 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006489 IndexVT = MVT::v16i8;
6490 IndexLen = 16;
6491 }
6492
6493 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6494 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6495
6496 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006497 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006498 if (IndexLen == 8)
6499 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
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 if (IndexLen == 8) {
6507 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6508 Shuffle = DAG.getNode(
6509 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006510 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006511 DAG.getBuildVector(IndexVT, DL,
6512 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006513 } else {
6514 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6515 // cannot currently represent the register constraints on the input
6516 // table registers.
6517 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006518 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6519 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006520 Shuffle = DAG.getNode(
6521 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006522 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6523 V2Cst, DAG.getBuildVector(IndexVT, DL,
6524 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006525 }
6526 }
6527 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6528}
6529
6530static unsigned getDUPLANEOp(EVT EltType) {
6531 if (EltType == MVT::i8)
6532 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006533 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006534 return AArch64ISD::DUPLANE16;
6535 if (EltType == MVT::i32 || EltType == MVT::f32)
6536 return AArch64ISD::DUPLANE32;
6537 if (EltType == MVT::i64 || EltType == MVT::f64)
6538 return AArch64ISD::DUPLANE64;
6539
6540 llvm_unreachable("Invalid vector element type?");
6541}
6542
6543SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6544 SelectionDAG &DAG) const {
6545 SDLoc dl(Op);
6546 EVT VT = Op.getValueType();
6547
6548 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6549
6550 // Convert shuffles that are directly supported on NEON to target-specific
6551 // DAG nodes, instead of keeping them as shuffles and matching them again
6552 // during code selection. This is more efficient and avoids the possibility
6553 // of inconsistencies between legalization and selection.
6554 ArrayRef<int> ShuffleMask = SVN->getMask();
6555
6556 SDValue V1 = Op.getOperand(0);
6557 SDValue V2 = Op.getOperand(1);
6558
Craig Topperbc56e3b2016-06-30 04:38:51 +00006559 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006560 int Lane = SVN->getSplatIndex();
6561 // If this is undef splat, generate it via "just" vdup, if possible.
6562 if (Lane == -1)
6563 Lane = 0;
6564
6565 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6566 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6567 V1.getOperand(0));
6568 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6569 // constant. If so, we can just reference the lane's definition directly.
6570 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6571 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6572 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6573
6574 // Otherwise, duplicate from the lane of the input vector.
6575 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6576
6577 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6578 // to make a vector of the same size as this SHUFFLE. We can ignore the
6579 // extract entirely, and canonicalise the concat using WidenVector.
6580 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6581 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6582 V1 = V1.getOperand(0);
6583 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6584 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6585 Lane -= Idx * VT.getVectorNumElements() / 2;
6586 V1 = WidenVector(V1.getOperand(Idx), DAG);
6587 } else if (VT.getSizeInBits() == 64)
6588 V1 = WidenVector(V1, DAG);
6589
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006590 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006591 }
6592
6593 if (isREVMask(ShuffleMask, VT, 64))
6594 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6595 if (isREVMask(ShuffleMask, VT, 32))
6596 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6597 if (isREVMask(ShuffleMask, VT, 16))
6598 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6599
6600 bool ReverseEXT = false;
6601 unsigned Imm;
6602 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6603 if (ReverseEXT)
6604 std::swap(V1, V2);
6605 Imm *= getExtFactor(V1);
6606 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006607 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006608 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006609 Imm *= getExtFactor(V1);
6610 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006611 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006612 }
6613
6614 unsigned WhichResult;
6615 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6616 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6617 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6618 }
6619 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6620 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6621 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6622 }
6623 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6624 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6625 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6626 }
6627
6628 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6629 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6630 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6631 }
6632 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6633 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6634 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6635 }
6636 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6637 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6638 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6639 }
6640
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006641 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006642 return Concat;
6643
6644 bool DstIsLeft;
6645 int Anomaly;
6646 int NumInputElements = V1.getValueType().getVectorNumElements();
6647 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6648 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006649 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006650
6651 SDValue SrcVec = V1;
6652 int SrcLane = ShuffleMask[Anomaly];
6653 if (SrcLane >= NumInputElements) {
6654 SrcVec = V2;
6655 SrcLane -= VT.getVectorNumElements();
6656 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006657 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006658
6659 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006660
6661 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006662 ScalarVT = MVT::i32;
6663
6664 return DAG.getNode(
6665 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6666 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6667 DstLaneV);
6668 }
6669
6670 // If the shuffle is not directly supported and it has 4 elements, use
6671 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6672 unsigned NumElts = VT.getVectorNumElements();
6673 if (NumElts == 4) {
6674 unsigned PFIndexes[4];
6675 for (unsigned i = 0; i != 4; ++i) {
6676 if (ShuffleMask[i] < 0)
6677 PFIndexes[i] = 8;
6678 else
6679 PFIndexes[i] = ShuffleMask[i];
6680 }
6681
6682 // Compute the index in the perfect shuffle table.
6683 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6684 PFIndexes[2] * 9 + PFIndexes[3];
6685 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6686 unsigned Cost = (PFEntry >> 30);
6687
6688 if (Cost <= 4)
6689 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6690 }
6691
6692 return GenerateTBL(Op, ShuffleMask, DAG);
6693}
6694
6695static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6696 APInt &UndefBits) {
6697 EVT VT = BVN->getValueType(0);
6698 APInt SplatBits, SplatUndef;
6699 unsigned SplatBitSize;
6700 bool HasAnyUndefs;
6701 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6702 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6703
6704 for (unsigned i = 0; i < NumSplats; ++i) {
6705 CnstBits <<= SplatBitSize;
6706 UndefBits <<= SplatBitSize;
6707 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6708 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6709 }
6710
6711 return true;
6712 }
6713
6714 return false;
6715}
6716
Evandro Menezes72f39832018-02-20 20:31:45 +00006717// Try 64-bit splatted SIMD immediate.
6718static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6719 const APInt &Bits) {
6720 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6721 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6722 EVT VT = Op.getValueType();
6723 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6724
6725 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6726 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6727
6728 SDLoc dl(Op);
6729 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6730 DAG.getConstant(Value, dl, MVT::i32));
6731 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6732 }
6733 }
6734
6735 return SDValue();
6736}
6737
6738// Try 32-bit splatted SIMD immediate.
6739static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6740 const APInt &Bits,
6741 const SDValue *LHS = nullptr) {
6742 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6743 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6744 EVT VT = Op.getValueType();
6745 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6746 bool isAdvSIMDModImm = false;
6747 uint64_t Shift;
6748
6749 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6750 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6751 Shift = 0;
6752 }
6753 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6754 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6755 Shift = 8;
6756 }
6757 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6758 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6759 Shift = 16;
6760 }
6761 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6762 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6763 Shift = 24;
6764 }
6765
6766 if (isAdvSIMDModImm) {
6767 SDLoc dl(Op);
6768 SDValue Mov;
6769
6770 if (LHS)
6771 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6772 DAG.getConstant(Value, dl, MVT::i32),
6773 DAG.getConstant(Shift, dl, MVT::i32));
6774 else
6775 Mov = DAG.getNode(NewOp, dl, MovTy,
6776 DAG.getConstant(Value, dl, MVT::i32),
6777 DAG.getConstant(Shift, dl, MVT::i32));
6778
6779 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6780 }
6781 }
6782
6783 return SDValue();
6784}
6785
6786// Try 16-bit splatted SIMD immediate.
6787static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6788 const APInt &Bits,
6789 const SDValue *LHS = nullptr) {
6790 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6791 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6792 EVT VT = Op.getValueType();
6793 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6794 bool isAdvSIMDModImm = false;
6795 uint64_t Shift;
6796
6797 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6798 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6799 Shift = 0;
6800 }
6801 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6802 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6803 Shift = 8;
6804 }
6805
6806 if (isAdvSIMDModImm) {
6807 SDLoc dl(Op);
6808 SDValue Mov;
6809
6810 if (LHS)
6811 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
Evandro Menezescd855f72018-03-05 17:02:47 +00006812 DAG.getConstant(Value, dl, MVT::i32),
6813 DAG.getConstant(Shift, dl, MVT::i32));
Evandro Menezes72f39832018-02-20 20:31:45 +00006814 else
6815 Mov = DAG.getNode(NewOp, dl, MovTy,
6816 DAG.getConstant(Value, dl, MVT::i32),
6817 DAG.getConstant(Shift, dl, MVT::i32));
6818
6819 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6820 }
6821 }
6822
6823 return SDValue();
6824}
6825
6826// Try 32-bit splatted SIMD immediate with shifted ones.
6827static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6828 SelectionDAG &DAG, const APInt &Bits) {
6829 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6830 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6831 EVT VT = Op.getValueType();
6832 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6833 bool isAdvSIMDModImm = false;
6834 uint64_t Shift;
6835
6836 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6837 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6838 Shift = 264;
6839 }
6840 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6841 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6842 Shift = 272;
6843 }
6844
6845 if (isAdvSIMDModImm) {
6846 SDLoc dl(Op);
6847 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6848 DAG.getConstant(Value, dl, MVT::i32),
6849 DAG.getConstant(Shift, dl, MVT::i32));
6850 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6851 }
6852 }
6853
6854 return SDValue();
6855}
6856
6857// Try 8-bit splatted SIMD immediate.
6858static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6859 const APInt &Bits) {
6860 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6861 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6862 EVT VT = Op.getValueType();
6863 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6864
6865 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6866 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6867
6868 SDLoc dl(Op);
6869 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6870 DAG.getConstant(Value, dl, MVT::i32));
6871 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6872 }
6873 }
6874
6875 return SDValue();
6876}
6877
6878// Try FP splatted SIMD immediate.
6879static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6880 const APInt &Bits) {
6881 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6882 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6883 EVT VT = Op.getValueType();
6884 bool isWide = (VT.getSizeInBits() == 128);
6885 MVT MovTy;
6886 bool isAdvSIMDModImm = false;
6887
6888 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6889 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6890 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6891 }
6892 else if (isWide &&
6893 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6894 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6895 MovTy = MVT::v2f64;
6896 }
6897
6898 if (isAdvSIMDModImm) {
6899 SDLoc dl(Op);
6900 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6901 DAG.getConstant(Value, dl, MVT::i32));
6902 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6903 }
6904 }
6905
6906 return SDValue();
6907}
6908
Tim Northover3b0846e2014-05-24 12:50:23 +00006909SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6910 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006911 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006912 EVT VT = Op.getValueType();
6913
Evandro Menezes72f39832018-02-20 20:31:45 +00006914 BuildVectorSDNode *BVN =
6915 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6916 if (!BVN) {
6917 // AND commutes, so try swapping the operands.
6918 LHS = Op.getOperand(1);
6919 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6920 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006921 if (!BVN)
6922 return Op;
6923
Evandro Menezes72f39832018-02-20 20:31:45 +00006924 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006925 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006926 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6927 SDValue NewOp;
6928
Tim Northover3b0846e2014-05-24 12:50:23 +00006929 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006930 DefBits = ~DefBits;
6931 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6932 DefBits, &LHS)) ||
6933 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6934 DefBits, &LHS)))
6935 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00006936
6937 UndefBits = ~UndefBits;
6938 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6939 UndefBits, &LHS)) ||
6940 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6941 UndefBits, &LHS)))
6942 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006943 }
6944
Evandro Menezes72f39832018-02-20 20:31:45 +00006945 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006946 return Op;
6947}
6948
6949// Specialized code to quickly find if PotentialBVec is a BuildVector that
6950// consists of only the same constant int value, returned in reference arg
6951// ConstVal
6952static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6953 uint64_t &ConstVal) {
6954 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6955 if (!Bvec)
6956 return false;
6957 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6958 if (!FirstElt)
6959 return false;
6960 EVT VT = Bvec->getValueType(0);
6961 unsigned NumElts = VT.getVectorNumElements();
6962 for (unsigned i = 1; i < NumElts; ++i)
6963 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6964 return false;
6965 ConstVal = FirstElt->getZExtValue();
6966 return true;
6967}
6968
6969static unsigned getIntrinsicID(const SDNode *N) {
6970 unsigned Opcode = N->getOpcode();
6971 switch (Opcode) {
6972 default:
6973 return Intrinsic::not_intrinsic;
6974 case ISD::INTRINSIC_WO_CHAIN: {
6975 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6976 if (IID < Intrinsic::num_intrinsics)
6977 return IID;
6978 return Intrinsic::not_intrinsic;
6979 }
6980 }
6981}
6982
6983// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6984// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6985// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6986// Also, logical shift right -> sri, with the same structure.
6987static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6988 EVT VT = N->getValueType(0);
6989
6990 if (!VT.isVector())
6991 return SDValue();
6992
6993 SDLoc DL(N);
6994
6995 // Is the first op an AND?
6996 const SDValue And = N->getOperand(0);
6997 if (And.getOpcode() != ISD::AND)
6998 return SDValue();
6999
7000 // Is the second op an shl or lshr?
7001 SDValue Shift = N->getOperand(1);
7002 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7003 // or AArch64ISD::VLSHR vector, #shift
7004 unsigned ShiftOpc = Shift.getOpcode();
7005 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7006 return SDValue();
7007 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7008
7009 // Is the shift amount constant?
7010 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7011 if (!C2node)
7012 return SDValue();
7013
7014 // Is the and mask vector all constant?
7015 uint64_t C1;
7016 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7017 return SDValue();
7018
7019 // Is C1 == ~C2, taking into account how much one can shift elements of a
7020 // particular size?
7021 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007022 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007023 if (C2 > ElemSizeInBits)
7024 return SDValue();
7025 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7026 if ((C1 & ElemMask) != (~C2 & ElemMask))
7027 return SDValue();
7028
7029 SDValue X = And.getOperand(0);
7030 SDValue Y = Shift.getOperand(0);
7031
7032 unsigned Intrin =
7033 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7034 SDValue ResultSLI =
7035 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007036 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7037 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00007038
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007039 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7040 LLVM_DEBUG(N->dump(&DAG));
7041 LLVM_DEBUG(dbgs() << "into: \n");
7042 LLVM_DEBUG(ResultSLI->dump(&DAG));
Tim Northover3b0846e2014-05-24 12:50:23 +00007043
7044 ++NumShiftInserts;
7045 return ResultSLI;
7046}
7047
7048SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7049 SelectionDAG &DAG) const {
7050 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7051 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007052 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007053 return Res;
7054 }
7055
Tim Northover3b0846e2014-05-24 12:50:23 +00007056 EVT VT = Op.getValueType();
7057
Evandro Menezescd855f72018-03-05 17:02:47 +00007058 SDValue LHS = Op.getOperand(0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007059 BuildVectorSDNode *BVN =
7060 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007061 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007062 // OR commutes, so try swapping the operands.
7063 LHS = Op.getOperand(1);
7064 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00007065 }
7066 if (!BVN)
7067 return Op;
7068
Evandro Menezes72f39832018-02-20 20:31:45 +00007069 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007070 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00007071 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7072 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007073
Evandro Menezes72f39832018-02-20 20:31:45 +00007074 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7075 DefBits, &LHS)) ||
7076 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7077 DefBits, &LHS)))
7078 return NewOp;
Evandro Menezes2bbb4a7c2018-03-01 21:17:36 +00007079
7080 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7081 UndefBits, &LHS)) ||
7082 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7083 UndefBits, &LHS)))
7084 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007085 }
7086
Evandro Menezes72f39832018-02-20 20:31:45 +00007087 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00007088 return Op;
7089}
7090
Kevin Qin4473c192014-07-07 02:45:40 +00007091// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7092// be truncated to fit element width.
7093static SDValue NormalizeBuildVector(SDValue Op,
7094 SelectionDAG &DAG) {
7095 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007096 SDLoc dl(Op);
7097 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00007098 EVT EltTy= VT.getVectorElementType();
7099
7100 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7101 return Op;
7102
7103 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007104 for (SDValue Lane : Op->ops()) {
Bryan Chane0237062018-08-06 14:14:41 +00007105 // For integer vectors, type legalization would have promoted the
7106 // operands already. Otherwise, if Op is a floating-point splat
7107 // (with operands cast to integers), then the only possibilities
7108 // are constants and UNDEFs.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007109 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00007110 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00007111 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007112 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Bryan Chane0237062018-08-06 14:14:41 +00007113 } else if (Lane.getNode()->isUndef()) {
7114 Lane = DAG.getUNDEF(MVT::i32);
7115 } else {
7116 assert(Lane.getValueType() == MVT::i32 &&
7117 "Unexpected BUILD_VECTOR operand type");
Kevin Qin4473c192014-07-07 02:45:40 +00007118 }
7119 Ops.push_back(Lane);
7120 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007121 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00007122}
7123
Evandro Menezescd855f72018-03-05 17:02:47 +00007124static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
Kevin Qin4473c192014-07-07 02:45:40 +00007125 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00007126
Evandro Menezes72f39832018-02-20 20:31:45 +00007127 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007128 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezescd855f72018-03-05 17:02:47 +00007129 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00007130 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
Evandro Menezes72f39832018-02-20 20:31:45 +00007131 SDValue NewOp;
7132 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7133 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7134 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7135 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7136 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7137 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7138 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007139
Evandro Menezes72f39832018-02-20 20:31:45 +00007140 DefBits = ~DefBits;
7141 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7142 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7143 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7144 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007145
Evandro Menezes72f39832018-02-20 20:31:45 +00007146 DefBits = UndefBits;
7147 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7148 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7149 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7150 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7151 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7152 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7153 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007154
Evandro Menezes72f39832018-02-20 20:31:45 +00007155 DefBits = ~UndefBits;
7156 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7157 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7158 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7159 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00007160 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007161
Evandro Menezescd855f72018-03-05 17:02:47 +00007162 return SDValue();
7163}
7164
7165SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7166 SelectionDAG &DAG) const {
7167 EVT VT = Op.getValueType();
7168
7169 // Try to build a simple constant vector.
7170 Op = NormalizeBuildVector(Op, DAG);
7171 if (VT.isInteger()) {
7172 // Certain vector constants, used to express things like logical NOT and
7173 // arithmetic NEG, are passed through unmodified. This allows special
7174 // patterns for these operations to match, which will lower these constants
7175 // to whatever is proven necessary.
7176 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7177 if (BVN->isConstant())
7178 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7179 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7180 APInt Val(BitSize,
7181 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7182 if (Val.isNullValue() || Val.isAllOnesValue())
7183 return Op;
7184 }
7185 }
7186
7187 if (SDValue V = ConstantBuildVector(Op, DAG))
7188 return V;
7189
Tim Northover3b0846e2014-05-24 12:50:23 +00007190 // Scan through the operands to find some interesting properties we can
7191 // exploit:
7192 // 1) If only one value is used, we can use a DUP, or
7193 // 2) if only the low element is not undef, we can just insert that, or
7194 // 3) if only one constant value is used (w/ some non-constant lanes),
7195 // we can splat the constant value into the whole vector then fill
7196 // in the non-constant lanes.
7197 // 4) FIXME: If different constant values are used, but we can intelligently
7198 // select the values we'll be overwriting for the non-constant
7199 // lanes such that we can directly materialize the vector
7200 // some other way (MOVI, e.g.), we can be sneaky.
Sebastian Popc33af712018-03-01 15:47:39 +00007201 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
Evandro Menezescd855f72018-03-05 17:02:47 +00007202 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00007203 unsigned NumElts = VT.getVectorNumElements();
7204 bool isOnlyLowElement = true;
7205 bool usesOnlyOneValue = true;
7206 bool usesOnlyOneConstantValue = true;
7207 bool isConstant = true;
Sebastian Popc33af712018-03-01 15:47:39 +00007208 bool AllLanesExtractElt = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007209 unsigned NumConstantLanes = 0;
7210 SDValue Value;
7211 SDValue ConstantValue;
7212 for (unsigned i = 0; i < NumElts; ++i) {
7213 SDValue V = Op.getOperand(i);
Sebastian Popc33af712018-03-01 15:47:39 +00007214 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7215 AllLanesExtractElt = false;
Sanjay Patel57195842016-03-14 17:28:46 +00007216 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007217 continue;
7218 if (i > 0)
7219 isOnlyLowElement = false;
7220 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7221 isConstant = false;
7222
7223 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7224 ++NumConstantLanes;
7225 if (!ConstantValue.getNode())
7226 ConstantValue = V;
7227 else if (ConstantValue != V)
7228 usesOnlyOneConstantValue = false;
7229 }
7230
7231 if (!Value.getNode())
7232 Value = V;
7233 else if (V != Value)
7234 usesOnlyOneValue = false;
7235 }
7236
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007237 if (!Value.getNode()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007238 LLVM_DEBUG(
7239 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007240 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007241 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007242
John Brawnd6e0ebe2018-11-22 11:45:23 +00007243 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7244 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7245 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7246 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007247 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7248 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007249 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007250 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007251
Sebastian Popc33af712018-03-01 15:47:39 +00007252 if (AllLanesExtractElt) {
7253 SDNode *Vector = nullptr;
7254 bool Even = false;
7255 bool Odd = false;
7256 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7257 // the Odd pattern <1,3,5,...>.
7258 for (unsigned i = 0; i < NumElts; ++i) {
7259 SDValue V = Op.getOperand(i);
7260 const SDNode *N = V.getNode();
7261 if (!isa<ConstantSDNode>(N->getOperand(1)))
7262 break;
Sebastian Popac0bfb52018-03-05 17:35:49 +00007263 SDValue N0 = N->getOperand(0);
Sebastian Popc33af712018-03-01 15:47:39 +00007264
7265 // All elements are extracted from the same vector.
Sebastian Popac0bfb52018-03-05 17:35:49 +00007266 if (!Vector) {
7267 Vector = N0.getNode();
7268 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7269 // BUILD_VECTOR.
7270 if (VT.getVectorElementType() !=
7271 N0.getValueType().getVectorElementType())
7272 break;
7273 } else if (Vector != N0.getNode()) {
Sebastian Popc33af712018-03-01 15:47:39 +00007274 Odd = false;
7275 Even = false;
7276 break;
7277 }
7278
7279 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7280 // indices <1,3,5,...>.
7281 uint64_t Val = N->getConstantOperandVal(1);
7282 if (Val == 2 * i) {
7283 Even = true;
7284 continue;
7285 }
7286 if (Val - 1 == 2 * i) {
7287 Odd = true;
7288 continue;
7289 }
7290
7291 // Something does not match: abort.
7292 Odd = false;
7293 Even = false;
7294 break;
7295 }
7296 if (Even || Odd) {
7297 SDValue LHS =
7298 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7299 DAG.getConstant(0, dl, MVT::i64));
7300 SDValue RHS =
7301 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7302 DAG.getConstant(NumElts, dl, MVT::i64));
7303
7304 if (Even && !Odd)
7305 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7306 RHS);
7307 if (Odd && !Even)
7308 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7309 RHS);
7310 }
7311 }
7312
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007313 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00007314 // i32 and try again.
7315 if (usesOnlyOneValue) {
7316 if (!isConstant) {
7317 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007318 Value.getValueType() != VT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007319 LLVM_DEBUG(
7320 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007321 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007322 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007323
7324 // This is actually a DUPLANExx operation, which keeps everything vectory.
7325
Tim Northover3b0846e2014-05-24 12:50:23 +00007326 SDValue Lane = Value.getOperand(1);
7327 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007328 if (Value.getValueSizeInBits() == 64) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007329 LLVM_DEBUG(
7330 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7331 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007332 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007333 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007334
7335 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7336 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7337 }
7338
7339 if (VT.getVectorElementType().isFloatingPoint()) {
7340 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007341 EVT EltTy = VT.getVectorElementType();
7342 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7343 "Unsupported floating-point vector type");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007344 LLVM_DEBUG(
7345 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7346 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00007347 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00007348 for (unsigned i = 0; i < NumElts; ++i)
7349 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7350 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00007351 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007352 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7353 Val.dump(););
Tim Northover3b0846e2014-05-24 12:50:23 +00007354 Val = LowerBUILD_VECTOR(Val, DAG);
7355 if (Val.getNode())
7356 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7357 }
7358 }
7359
7360 // If there was only one constant value used and for more than one lane,
7361 // start by splatting that value, then replace the non-constant lanes. This
7362 // is better than the default, which will perform a separate initialization
7363 // for each lane.
7364 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
Evandro Menezescd855f72018-03-05 17:02:47 +00007365 // Firstly, try to materialize the splat constant.
7366 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7367 Val = ConstantBuildVector(Vec, DAG);
7368 if (!Val) {
7369 // Otherwise, materialize the constant and splat it.
7370 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7371 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7372 }
7373
Tim Northover3b0846e2014-05-24 12:50:23 +00007374 // Now insert the non-constant lanes.
7375 for (unsigned i = 0; i < NumElts; ++i) {
7376 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007377 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Evandro Menezescd855f72018-03-05 17:02:47 +00007378 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
Tim Northover3b0846e2014-05-24 12:50:23 +00007379 // Note that type legalization likely mucked about with the VT of the
7380 // source operand, so we may have to convert it here before inserting.
7381 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +00007382 }
7383 return Val;
7384 }
7385
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007386 // This will generate a load from the constant pool.
7387 if (isConstant) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007388 LLVM_DEBUG(
7389 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7390 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007391 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007392 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007393
7394 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7395 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007396 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00007397 return shuffle;
7398 }
7399
7400 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7401 // know the default expansion would otherwise fall back on something even
7402 // worse. For a vector with one or two non-undef values, that's
7403 // scalar_to_vector for the elements followed by a shuffle (provided the
7404 // shuffle is valid for the target) and materialization element by element
7405 // on the stack followed by a load for everything else.
7406 if (!isConstant && !usesOnlyOneValue) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007407 LLVM_DEBUG(
7408 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7409 "of INSERT_VECTOR_ELT\n");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00007410
Tim Northover3b0846e2014-05-24 12:50:23 +00007411 SDValue Vec = DAG.getUNDEF(VT);
7412 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007413 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00007414
7415 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00007416 // a) Avoid a RMW dependency on the full vector register, and
7417 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007418 // value is already in an S or D register, and we're forced to emit an
7419 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00007420 //
7421 // We also allow types like i8 and i16 which are illegal scalar but legal
7422 // vector element types. After type-legalization the inserted value is
7423 // extended (i32) and it is safe to cast them to the vector type by ignoring
7424 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7425 if (!Op0.isUndef()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007426 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00007427 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007428 ++i;
7429 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007430 LLVM_DEBUG(if (i < NumElts) dbgs()
7431 << "Creating nodes for the other vector elements:\n";);
Tim Northover3b0846e2014-05-24 12:50:23 +00007432 for (; i < NumElts; ++i) {
7433 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00007434 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00007435 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007436 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007437 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7438 }
7439 return Vec;
7440 }
7441
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007442 LLVM_DEBUG(
7443 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7444 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00007445 return SDValue();
7446}
7447
7448SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7449 SelectionDAG &DAG) const {
7450 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7451
Tim Northovere4b8e132014-07-15 10:00:26 +00007452 // Check for non-constant or out of range lane.
7453 EVT VT = Op.getOperand(0).getValueType();
7454 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7455 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007456 return SDValue();
7457
Tim Northover3b0846e2014-05-24 12:50:23 +00007458
7459 // Insertion/extraction are legal for V128 types.
7460 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007461 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7462 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007463 return Op;
7464
7465 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007466 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007467 return SDValue();
7468
7469 // For V64 types, we perform insertion by expanding the value
7470 // to a V128 type and perform the insertion on that.
7471 SDLoc DL(Op);
7472 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7473 EVT WideTy = WideVec.getValueType();
7474
7475 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7476 Op.getOperand(1), Op.getOperand(2));
7477 // Re-narrow the resultant vector.
7478 return NarrowVector(Node, DAG);
7479}
7480
7481SDValue
7482AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7483 SelectionDAG &DAG) const {
7484 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7485
Tim Northovere4b8e132014-07-15 10:00:26 +00007486 // Check for non-constant or out of range lane.
7487 EVT VT = Op.getOperand(0).getValueType();
7488 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7489 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00007490 return SDValue();
7491
Tim Northover3b0846e2014-05-24 12:50:23 +00007492
7493 // Insertion/extraction are legal for V128 types.
7494 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00007495 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7496 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007497 return Op;
7498
7499 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00007500 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00007501 return SDValue();
7502
7503 // For V64 types, we perform extraction by expanding the value
7504 // to a V128 type and perform the extraction on that.
7505 SDLoc DL(Op);
7506 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7507 EVT WideTy = WideVec.getValueType();
7508
7509 EVT ExtrTy = WideTy.getVectorElementType();
7510 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7511 ExtrTy = MVT::i32;
7512
7513 // For extractions, we just return the result directly.
7514 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7515 Op.getOperand(1));
7516}
7517
7518SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7519 SelectionDAG &DAG) const {
7520 EVT VT = Op.getOperand(0).getValueType();
7521 SDLoc dl(Op);
7522 // Just in case...
7523 if (!VT.isVector())
7524 return SDValue();
7525
7526 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7527 if (!Cst)
7528 return SDValue();
7529 unsigned Val = Cst->getZExtValue();
7530
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007531 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00007532
7533 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7534 if (Val == 0)
7535 return Op;
7536
Tim Northover3b0846e2014-05-24 12:50:23 +00007537 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7538 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007539 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00007540 return Op;
7541
7542 return SDValue();
7543}
7544
Zvi Rackover1b736822017-07-26 08:06:58 +00007545bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007546 if (VT.getVectorNumElements() == 4 &&
7547 (VT.is128BitVector() || VT.is64BitVector())) {
7548 unsigned PFIndexes[4];
7549 for (unsigned i = 0; i != 4; ++i) {
7550 if (M[i] < 0)
7551 PFIndexes[i] = 8;
7552 else
7553 PFIndexes[i] = M[i];
7554 }
7555
7556 // Compute the index in the perfect shuffle table.
7557 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7558 PFIndexes[2] * 9 + PFIndexes[3];
7559 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7560 unsigned Cost = (PFEntry >> 30);
7561
7562 if (Cost <= 4)
7563 return true;
7564 }
7565
7566 bool DummyBool;
7567 int DummyInt;
7568 unsigned DummyUnsigned;
7569
7570 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7571 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7572 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7573 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7574 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7575 isZIPMask(M, VT, DummyUnsigned) ||
7576 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7577 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7578 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7579 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7580 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7581}
7582
7583/// getVShiftImm - Check if this is a valid build_vector for the immediate
7584/// operand of a vector shift operation, where all the elements of the
7585/// build_vector must have the same constant integer value.
7586static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7587 // Ignore bit_converts.
7588 while (Op.getOpcode() == ISD::BITCAST)
7589 Op = Op.getOperand(0);
7590 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7591 APInt SplatBits, SplatUndef;
7592 unsigned SplatBitSize;
7593 bool HasAnyUndefs;
7594 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7595 HasAnyUndefs, ElementBits) ||
7596 SplatBitSize > ElementBits)
7597 return false;
7598 Cnt = SplatBits.getSExtValue();
7599 return true;
7600}
7601
7602/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7603/// operand of a vector shift left operation. That value must be in the range:
7604/// 0 <= Value < ElementBits for a left shift; or
7605/// 0 <= Value <= ElementBits for a long left shift.
7606static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7607 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007608 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007609 if (!getVShiftImm(Op, ElementBits, Cnt))
7610 return false;
7611 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7612}
7613
7614/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007615/// operand of a vector shift right operation. The value must be in the range:
7616/// 1 <= Value <= ElementBits for a right shift; or
7617static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007618 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007619 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007620 if (!getVShiftImm(Op, ElementBits, Cnt))
7621 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007622 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7623}
7624
7625SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7626 SelectionDAG &DAG) const {
7627 EVT VT = Op.getValueType();
7628 SDLoc DL(Op);
7629 int64_t Cnt;
7630
7631 if (!Op.getOperand(1).getValueType().isVector())
7632 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007633 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007634
7635 switch (Op.getOpcode()) {
7636 default:
7637 llvm_unreachable("unexpected shift opcode");
7638
7639 case ISD::SHL:
7640 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007641 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7642 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007643 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007644 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7645 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007646 Op.getOperand(0), Op.getOperand(1));
7647 case ISD::SRA:
7648 case ISD::SRL:
7649 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007650 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007651 unsigned Opc =
7652 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007653 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7654 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007655 }
7656
7657 // Right shift register. Note, there is not a shift right register
7658 // instruction, but the shift left register instruction takes a signed
7659 // value, where negative numbers specify a right shift.
7660 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7661 : Intrinsic::aarch64_neon_ushl;
7662 // negate the shift amount
7663 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7664 SDValue NegShiftLeft =
7665 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007666 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7667 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007668 return NegShiftLeft;
7669 }
7670
7671 return SDValue();
7672}
7673
7674static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7675 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007676 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007677 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007678 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7679 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007680
7681 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7682 APInt CnstBits(VT.getSizeInBits(), 0);
7683 APInt UndefBits(VT.getSizeInBits(), 0);
7684 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7685 bool IsZero = IsCnst && (CnstBits == 0);
7686
7687 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7688 switch (CC) {
7689 default:
7690 return SDValue();
7691 case AArch64CC::NE: {
7692 SDValue Fcmeq;
7693 if (IsZero)
7694 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7695 else
7696 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7697 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7698 }
7699 case AArch64CC::EQ:
7700 if (IsZero)
7701 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7702 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7703 case AArch64CC::GE:
7704 if (IsZero)
7705 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7706 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7707 case AArch64CC::GT:
7708 if (IsZero)
7709 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7710 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7711 case AArch64CC::LS:
7712 if (IsZero)
7713 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7714 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7715 case AArch64CC::LT:
7716 if (!NoNans)
7717 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007718 // If we ignore NaNs then we can use to the MI implementation.
7719 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007720 case AArch64CC::MI:
7721 if (IsZero)
7722 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7723 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7724 }
7725 }
7726
7727 switch (CC) {
7728 default:
7729 return SDValue();
7730 case AArch64CC::NE: {
7731 SDValue Cmeq;
7732 if (IsZero)
7733 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7734 else
7735 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7736 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7737 }
7738 case AArch64CC::EQ:
7739 if (IsZero)
7740 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7741 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7742 case AArch64CC::GE:
7743 if (IsZero)
7744 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7745 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7746 case AArch64CC::GT:
7747 if (IsZero)
7748 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7749 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7750 case AArch64CC::LE:
7751 if (IsZero)
7752 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7753 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7754 case AArch64CC::LS:
7755 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7756 case AArch64CC::LO:
7757 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7758 case AArch64CC::LT:
7759 if (IsZero)
7760 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7761 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7762 case AArch64CC::HI:
7763 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7764 case AArch64CC::HS:
7765 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7766 }
7767}
7768
7769SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7770 SelectionDAG &DAG) const {
7771 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7772 SDValue LHS = Op.getOperand(0);
7773 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007774 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007775 SDLoc dl(Op);
7776
7777 if (LHS.getValueType().getVectorElementType().isInteger()) {
7778 assert(LHS.getValueType() == RHS.getValueType());
7779 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007780 SDValue Cmp =
7781 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7782 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007783 }
7784
Carey Williamsda15b5b2018-01-22 14:16:11 +00007785 const bool FullFP16 =
7786 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7787
7788 // Make v4f16 (only) fcmp operations utilise vector instructions
7789 // v8f16 support will be a litle more complicated
7790 if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7791 if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7792 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7793 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7794 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7795 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7796 CmpVT = MVT::v4i32;
7797 } else
7798 return SDValue();
7799 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007800
Tim Northover3b0846e2014-05-24 12:50:23 +00007801 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7802 LHS.getValueType().getVectorElementType() == MVT::f64);
7803
7804 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7805 // clean. Some of them require two branches to implement.
7806 AArch64CC::CondCode CC1, CC2;
7807 bool ShouldInvert;
7808 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7809
7810 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7811 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007812 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007813 if (!Cmp.getNode())
7814 return SDValue();
7815
7816 if (CC2 != AArch64CC::AL) {
7817 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007818 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007819 if (!Cmp2.getNode())
7820 return SDValue();
7821
Tim Northover45aa89c2015-02-08 00:50:47 +00007822 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007823 }
7824
Tim Northover45aa89c2015-02-08 00:50:47 +00007825 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7826
Tim Northover3b0846e2014-05-24 12:50:23 +00007827 if (ShouldInvert)
David Blaikie1fecbec2018-11-26 22:57:18 +00007828 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007829
7830 return Cmp;
7831}
7832
Amara Emersonc9916d72017-05-16 21:29:22 +00007833static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7834 SelectionDAG &DAG) {
7835 SDValue VecOp = ScalarOp.getOperand(0);
7836 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7837 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7838 DAG.getConstant(0, DL, MVT::i64));
7839}
7840
7841SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7842 SelectionDAG &DAG) const {
7843 SDLoc dl(Op);
7844 switch (Op.getOpcode()) {
7845 case ISD::VECREDUCE_ADD:
7846 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7847 case ISD::VECREDUCE_SMAX:
7848 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7849 case ISD::VECREDUCE_SMIN:
7850 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7851 case ISD::VECREDUCE_UMAX:
7852 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7853 case ISD::VECREDUCE_UMIN:
7854 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7855 case ISD::VECREDUCE_FMAX: {
7856 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7857 return DAG.getNode(
7858 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7859 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7860 Op.getOperand(0));
7861 }
7862 case ISD::VECREDUCE_FMIN: {
7863 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7864 return DAG.getNode(
7865 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7866 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7867 Op.getOperand(0));
7868 }
7869 default:
7870 llvm_unreachable("Unhandled reduction");
7871 }
7872}
7873
Oliver Stannard42699172018-02-12 14:22:03 +00007874SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7875 SelectionDAG &DAG) const {
7876 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7877 if (!Subtarget.hasLSE())
7878 return SDValue();
7879
7880 // LSE has an atomic load-add instruction, but not a load-sub.
7881 SDLoc dl(Op);
7882 MVT VT = Op.getSimpleValueType();
7883 SDValue RHS = Op.getOperand(2);
7884 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7885 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7886 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7887 Op.getOperand(0), Op.getOperand(1), RHS,
7888 AN->getMemOperand());
7889}
7890
Oliver Stannard02f08c92018-02-12 17:03:11 +00007891SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7892 SelectionDAG &DAG) const {
7893 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7894 if (!Subtarget.hasLSE())
7895 return SDValue();
7896
7897 // LSE has an atomic load-clear instruction, but not a load-and.
7898 SDLoc dl(Op);
7899 MVT VT = Op.getSimpleValueType();
7900 SDValue RHS = Op.getOperand(2);
7901 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7902 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7903 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7904 Op.getOperand(0), Op.getOperand(1), RHS,
7905 AN->getMemOperand());
7906}
7907
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007908SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7909 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7910 SDLoc dl(Op);
7911 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7912 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7913
Tri Vo6c47c622018-09-22 22:17:50 +00007914 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7915 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7916 if (Subtarget->hasCustomCallingConv())
7917 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007918
7919 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7920 DAG.getConstant(4, dl, MVT::i64));
7921 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7922 Chain =
7923 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7924 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7925 DAG.getRegisterMask(Mask), Chain.getValue(1));
7926 // To match the actual intent better, we should read the output from X15 here
7927 // again (instead of potentially spilling it to the stack), but rereading Size
7928 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7929 // here.
7930
7931 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7932 DAG.getConstant(4, dl, MVT::i64));
7933 return Chain;
7934}
7935
7936SDValue
7937AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7938 SelectionDAG &DAG) const {
7939 assert(Subtarget->isTargetWindows() &&
7940 "Only Windows alloca probing supported");
7941 SDLoc dl(Op);
7942 // Get the inputs.
7943 SDNode *Node = Op.getNode();
7944 SDValue Chain = Op.getOperand(0);
7945 SDValue Size = Op.getOperand(1);
7946 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7947 EVT VT = Node->getValueType(0);
7948
Martin Storsjo9a55c1b2018-03-19 20:06:50 +00007949 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7950 "no-stack-arg-probe")) {
7951 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7952 Chain = SP.getValue(1);
7953 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7954 if (Align)
7955 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7956 DAG.getConstant(-(uint64_t)Align, dl, VT));
7957 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7958 SDValue Ops[2] = {SP, Chain};
7959 return DAG.getMergeValues(Ops, dl);
7960 }
7961
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007962 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7963
7964 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7965
7966 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7967 Chain = SP.getValue(1);
7968 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
Martin Storsjo36d64192018-03-17 20:08:48 +00007969 if (Align)
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007970 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7971 DAG.getConstant(-(uint64_t)Align, dl, VT));
Martin Storsjo36d64192018-03-17 20:08:48 +00007972 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007973
7974 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7975 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7976
7977 SDValue Ops[2] = {SP, Chain};
7978 return DAG.getMergeValues(Ops, dl);
7979}
7980
Tim Northover3b0846e2014-05-24 12:50:23 +00007981/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7982/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7983/// specified in the intrinsic calls.
7984bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7985 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00007986 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00007987 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007988 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007989 switch (Intrinsic) {
7990 case Intrinsic::aarch64_neon_ld2:
7991 case Intrinsic::aarch64_neon_ld3:
7992 case Intrinsic::aarch64_neon_ld4:
7993 case Intrinsic::aarch64_neon_ld1x2:
7994 case Intrinsic::aarch64_neon_ld1x3:
7995 case Intrinsic::aarch64_neon_ld1x4:
7996 case Intrinsic::aarch64_neon_ld2lane:
7997 case Intrinsic::aarch64_neon_ld3lane:
7998 case Intrinsic::aarch64_neon_ld4lane:
7999 case Intrinsic::aarch64_neon_ld2r:
8000 case Intrinsic::aarch64_neon_ld3r:
8001 case Intrinsic::aarch64_neon_ld4r: {
8002 Info.opc = ISD::INTRINSIC_W_CHAIN;
8003 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008004 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008005 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8006 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8007 Info.offset = 0;
8008 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008009 // volatile loads with NEON intrinsics not supported
8010 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00008011 return true;
8012 }
8013 case Intrinsic::aarch64_neon_st2:
8014 case Intrinsic::aarch64_neon_st3:
8015 case Intrinsic::aarch64_neon_st4:
8016 case Intrinsic::aarch64_neon_st1x2:
8017 case Intrinsic::aarch64_neon_st1x3:
8018 case Intrinsic::aarch64_neon_st1x4:
8019 case Intrinsic::aarch64_neon_st2lane:
8020 case Intrinsic::aarch64_neon_st3lane:
8021 case Intrinsic::aarch64_neon_st4lane: {
8022 Info.opc = ISD::INTRINSIC_VOID;
8023 // Conservatively set memVT to the entire set of vectors stored.
8024 unsigned NumElts = 0;
David Greene3e89fa82018-10-30 19:17:51 +00008025 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008026 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8027 if (!ArgTy->isVectorTy())
8028 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00008029 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008030 }
8031 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8032 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8033 Info.offset = 0;
8034 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00008035 // volatile stores with NEON intrinsics not supported
8036 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00008037 return true;
8038 }
8039 case Intrinsic::aarch64_ldaxr:
8040 case Intrinsic::aarch64_ldxr: {
8041 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8042 Info.opc = ISD::INTRINSIC_W_CHAIN;
8043 Info.memVT = MVT::getVT(PtrTy->getElementType());
8044 Info.ptrVal = I.getArgOperand(0);
8045 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008046 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008047 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008048 return true;
8049 }
8050 case Intrinsic::aarch64_stlxr:
8051 case Intrinsic::aarch64_stxr: {
8052 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8053 Info.opc = ISD::INTRINSIC_W_CHAIN;
8054 Info.memVT = MVT::getVT(PtrTy->getElementType());
8055 Info.ptrVal = I.getArgOperand(1);
8056 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008057 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00008058 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008059 return true;
8060 }
8061 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008062 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008063 Info.opc = ISD::INTRINSIC_W_CHAIN;
8064 Info.memVT = MVT::i128;
8065 Info.ptrVal = I.getArgOperand(0);
8066 Info.offset = 0;
8067 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008068 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008069 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008070 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00008071 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00008072 Info.opc = ISD::INTRINSIC_W_CHAIN;
8073 Info.memVT = MVT::i128;
8074 Info.ptrVal = I.getArgOperand(2);
8075 Info.offset = 0;
8076 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00008077 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00008078 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00008079 default:
8080 break;
8081 }
8082
8083 return false;
8084}
8085
John Brawne3b44f92018-03-23 14:47:07 +00008086bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8087 ISD::LoadExtType ExtTy,
8088 EVT NewVT) const {
Sanjay Patel0a515592018-11-10 20:05:31 +00008089 // TODO: This may be worth removing. Check regression tests for diffs.
8090 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8091 return false;
8092
John Brawne3b44f92018-03-23 14:47:07 +00008093 // If we're reducing the load width in order to avoid having to use an extra
8094 // instruction to do extension then it's probably a good idea.
8095 if (ExtTy != ISD::NON_EXTLOAD)
8096 return true;
8097 // Don't reduce load width if it would prevent us from combining a shift into
8098 // the offset.
8099 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8100 assert(Mem);
8101 const SDValue &Base = Mem->getBasePtr();
8102 if (Base.getOpcode() == ISD::ADD &&
8103 Base.getOperand(1).getOpcode() == ISD::SHL &&
8104 Base.getOperand(1).hasOneUse() &&
8105 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8106 // The shift can be combined if it matches the size of the value being
8107 // loaded (and so reducing the width would make it not match).
8108 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8109 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8110 if (ShiftAmount == Log2_32(LoadBytes))
8111 return false;
8112 }
8113 // We have no reason to disallow reducing the load width, so allow it.
8114 return true;
8115}
8116
Tim Northover3b0846e2014-05-24 12:50:23 +00008117// Truncations from 64-bit GPR to 32-bit GPR is free.
8118bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8119 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8120 return false;
8121 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8122 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008123 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008124}
8125bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008126 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008127 return false;
8128 unsigned NumBits1 = VT1.getSizeInBits();
8129 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008130 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00008131}
8132
Chad Rosier54390052015-02-23 19:15:16 +00008133/// Check if it is profitable to hoist instruction in then/else to if.
8134/// Not profitable if I and it's user can form a FMA instruction
8135/// because we prefer FMSUB/FMADD.
8136bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8137 if (I->getOpcode() != Instruction::FMul)
8138 return true;
8139
Davide Italiano3e9986f2017-04-18 00:29:54 +00008140 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00008141 return true;
8142
8143 Instruction *User = I->user_back();
8144
8145 if (User &&
8146 !(User->getOpcode() == Instruction::FSub ||
8147 User->getOpcode() == Instruction::FAdd))
8148 return true;
8149
8150 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00008151 const DataLayout &DL = I->getModule()->getDataLayout();
8152 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00008153
Eric Christopher114fa1c2016-02-29 22:50:49 +00008154 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8155 isOperationLegalOrCustom(ISD::FMA, VT) &&
8156 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8157 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00008158}
8159
Tim Northover3b0846e2014-05-24 12:50:23 +00008160// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8161// 64-bit GPR.
8162bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8163 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8164 return false;
8165 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8166 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008167 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008168}
8169bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00008170 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00008171 return false;
8172 unsigned NumBits1 = VT1.getSizeInBits();
8173 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00008174 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00008175}
8176
8177bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8178 EVT VT1 = Val.getValueType();
8179 if (isZExtFree(VT1, VT2)) {
8180 return true;
8181 }
8182
8183 if (Val.getOpcode() != ISD::LOAD)
8184 return false;
8185
8186 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00008187 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8188 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8189 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008190}
8191
Quentin Colombet6843ac42015-03-31 20:52:32 +00008192bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8193 if (isa<FPExtInst>(Ext))
8194 return false;
8195
Haicheng Wu50692a22017-08-01 21:26:45 +00008196 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00008197 if (Ext->getType()->isVectorTy())
8198 return false;
8199
8200 for (const Use &U : Ext->uses()) {
8201 // The extension is free if we can fold it with a left shift in an
8202 // addressing mode or an arithmetic operation: add, sub, and cmp.
8203
8204 // Is there a shift?
8205 const Instruction *Instr = cast<Instruction>(U.getUser());
8206
8207 // Is this a constant shift?
8208 switch (Instr->getOpcode()) {
8209 case Instruction::Shl:
8210 if (!isa<ConstantInt>(Instr->getOperand(1)))
8211 return false;
8212 break;
8213 case Instruction::GetElementPtr: {
8214 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008215 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00008216 std::advance(GTI, U.getOperandNo()-1);
8217 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00008218 // This extension will end up with a shift because of the scaling factor.
8219 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8220 // Get the shift amount based on the scaling factor:
8221 // log2(sizeof(IdxTy)) - log2(8).
8222 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008223 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008224 // Is the constant foldable in the shift of the addressing mode?
8225 // I.e., shift amount is between 1 and 4 inclusive.
8226 if (ShiftAmt == 0 || ShiftAmt > 4)
8227 return false;
8228 break;
8229 }
8230 case Instruction::Trunc:
8231 // Check if this is a noop.
8232 // trunc(sext ty1 to ty2) to ty1.
8233 if (Instr->getType() == Ext->getOperand(0)->getType())
8234 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00008235 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00008236 default:
8237 return false;
8238 }
8239
8240 // At this point we can use the bfm family, so this extension is free
8241 // for that use.
8242 }
8243 return true;
8244}
8245
Tim Northover3b0846e2014-05-24 12:50:23 +00008246bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8247 unsigned &RequiredAligment) const {
8248 if (!LoadedType.isSimple() ||
8249 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8250 return false;
8251 // Cyclone supports unaligned accesses.
8252 RequiredAligment = 0;
8253 unsigned NumBits = LoadedType.getSizeInBits();
8254 return NumBits == 32 || NumBits == 64;
8255}
8256
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008257/// A helper function for determining the number of interleaved accesses we
8258/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008259unsigned
8260AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8261 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008262 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8263}
8264
Geoff Berryb1e87142017-07-14 21:44:12 +00008265MachineMemOperand::Flags
8266AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8267 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8268 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8269 return MOStridedAccess;
8270 return MachineMemOperand::MONone;
8271}
8272
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008273bool AArch64TargetLowering::isLegalInterleavedAccessType(
8274 VectorType *VecTy, const DataLayout &DL) const {
8275
8276 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8277 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8278
8279 // Ensure the number of vector elements is greater than 1.
8280 if (VecTy->getNumElements() < 2)
8281 return false;
8282
8283 // Ensure the element type is legal.
8284 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8285 return false;
8286
8287 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8288 // 128 will be split into multiple interleaved accesses.
8289 return VecSize == 64 || VecSize % 128 == 0;
8290}
8291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008292/// Lower an interleaved load into a ldN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008293///
8294/// E.g. Lower an interleaved load (Factor = 2):
8295/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8296/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8297/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8298///
8299/// Into:
8300/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8301/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8302/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8303bool AArch64TargetLowering::lowerInterleavedLoad(
8304 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8305 ArrayRef<unsigned> Indices, unsigned Factor) const {
8306 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8307 "Invalid interleave factor");
8308 assert(!Shuffles.empty() && "Empty shufflevector input");
8309 assert(Shuffles.size() == Indices.size() &&
8310 "Unmatched number of shufflevectors and indices");
8311
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008312 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008313
8314 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008315
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008316 // Skip if we do not have NEON and skip illegal vector types. We can
8317 // "legalize" wide vector types into multiple interleaved accesses as long as
8318 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008319 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008320 return false;
8321
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008322 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8323
Hao Liu7ec8ee32015-06-26 02:32:07 +00008324 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8325 // load integer vectors first and then convert to pointer vectors.
8326 Type *EltTy = VecTy->getVectorElementType();
8327 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008328 VecTy =
8329 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00008330
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008331 IRBuilder<> Builder(LI);
8332
8333 // The base address of the load.
8334 Value *BaseAddr = LI->getPointerOperand();
8335
8336 if (NumLoads > 1) {
8337 // If we're going to generate more than one load, reset the sub-vector type
8338 // to something legal.
8339 VecTy = VectorType::get(VecTy->getVectorElementType(),
8340 VecTy->getVectorNumElements() / NumLoads);
8341
8342 // We will compute the pointer operand of each load from the original base
8343 // address using GEPs. Cast the base address to a pointer to the scalar
8344 // element type.
8345 BaseAddr = Builder.CreateBitCast(
8346 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8347 LI->getPointerAddressSpace()));
8348 }
8349
Hao Liu7ec8ee32015-06-26 02:32:07 +00008350 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8351 Type *Tys[2] = {VecTy, PtrTy};
8352 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8353 Intrinsic::aarch64_neon_ld3,
8354 Intrinsic::aarch64_neon_ld4};
8355 Function *LdNFunc =
8356 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8357
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008358 // Holds sub-vectors extracted from the load intrinsic return values. The
8359 // sub-vectors are associated with the shufflevector instructions they will
8360 // replace.
8361 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008362
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008363 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008364
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008365 // If we're generating more than one load, compute the base address of
8366 // subsequent loads as an offset from the previous.
8367 if (LoadCount > 0)
8368 BaseAddr = Builder.CreateConstGEP1_32(
8369 BaseAddr, VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008370
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008371 CallInst *LdN = Builder.CreateCall(
8372 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00008373
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008374 // Extract and store the sub-vectors returned by the load intrinsic.
8375 for (unsigned i = 0; i < Shuffles.size(); i++) {
8376 ShuffleVectorInst *SVI = Shuffles[i];
8377 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00008378
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008379 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8380
8381 // Convert the integer vector to pointer vector if the element is pointer.
8382 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00008383 SubVec = Builder.CreateIntToPtr(
8384 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8385 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008386 SubVecs[SVI].push_back(SubVec);
8387 }
8388 }
8389
8390 // Replace uses of the shufflevector instructions with the sub-vectors
8391 // returned by the load intrinsic. If a shufflevector instruction is
8392 // associated with more than one sub-vector, those sub-vectors will be
8393 // concatenated into a single wide vector.
8394 for (ShuffleVectorInst *SVI : Shuffles) {
8395 auto &SubVec = SubVecs[SVI];
8396 auto *WideVec =
8397 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8398 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008399 }
8400
8401 return true;
8402}
8403
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00008404/// Lower an interleaved store into a stN intrinsic.
Hao Liu7ec8ee32015-06-26 02:32:07 +00008405///
8406/// E.g. Lower an interleaved store (Factor = 3):
8407/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008408/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00008409/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8410///
8411/// Into:
8412/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8413/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8414/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8415/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8416///
8417/// Note that the new shufflevectors will be removed and we'll only generate one
8418/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008419///
8420/// Example for a more general valid mask (Factor 3). Lower:
8421/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8422/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8423/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8424///
8425/// Into:
8426/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8427/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8428/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8429/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00008430bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8431 ShuffleVectorInst *SVI,
8432 unsigned Factor) const {
8433 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8434 "Invalid interleave factor");
8435
8436 VectorType *VecTy = SVI->getType();
8437 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8438 "Invalid interleaved store");
8439
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008440 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00008441 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008442 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008443
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008444 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008445
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008446 // Skip if we do not have NEON and skip illegal vector types. We can
8447 // "legalize" wide vector types into multiple interleaved accesses as long as
8448 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00008449 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00008450 return false;
8451
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008452 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8453
Hao Liu7ec8ee32015-06-26 02:32:07 +00008454 Value *Op0 = SVI->getOperand(0);
8455 Value *Op1 = SVI->getOperand(1);
8456 IRBuilder<> Builder(SI);
8457
8458 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8459 // vectors to integer vectors.
8460 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00008461 Type *IntTy = DL.getIntPtrType(EltTy);
Craig Topper781aa182018-05-05 01:57:00 +00008462 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
Hao Liu7ec8ee32015-06-26 02:32:07 +00008463
8464 // Convert to the corresponding integer vector.
8465 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8466 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8467 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8468
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008469 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00008470 }
8471
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008472 // The base address of the store.
8473 Value *BaseAddr = SI->getPointerOperand();
8474
8475 if (NumStores > 1) {
8476 // If we're going to generate more than one store, reset the lane length
8477 // and sub-vector type to something legal.
8478 LaneLen /= NumStores;
8479 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8480
8481 // We will compute the pointer operand of each store from the original base
8482 // address using GEPs. Cast the base address to a pointer to the scalar
8483 // element type.
8484 BaseAddr = Builder.CreateBitCast(
8485 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8486 SI->getPointerAddressSpace()));
8487 }
8488
8489 auto Mask = SVI->getShuffleMask();
8490
Hao Liu7ec8ee32015-06-26 02:32:07 +00008491 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8492 Type *Tys[2] = {SubVecTy, PtrTy};
8493 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8494 Intrinsic::aarch64_neon_st3,
8495 Intrinsic::aarch64_neon_st4};
8496 Function *StNFunc =
8497 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8498
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008499 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00008500
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008501 SmallVector<Value *, 5> Ops;
8502
8503 // Split the shufflevector operands into sub vectors for the new stN call.
8504 for (unsigned i = 0; i < Factor; i++) {
8505 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8506 if (Mask[IdxI] >= 0) {
8507 Ops.push_back(Builder.CreateShuffleVector(
8508 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8509 } else {
8510 unsigned StartMask = 0;
8511 for (unsigned j = 1; j < LaneLen; j++) {
8512 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8513 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8514 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8515 break;
8516 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008517 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008518 // Note: Filling undef gaps with random elements is ok, since
8519 // those elements were being written anyway (with undefs).
8520 // In the case of all undefs we're defaulting to using elems from 0
8521 // Note: StartMask cannot be negative, it's checked in
8522 // isReInterleaveMask
8523 Ops.push_back(Builder.CreateShuffleVector(
8524 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008525 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00008526 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008527
Matthew Simpson1bfa1592017-03-02 15:11:20 +00008528 // If we generating more than one store, we compute the base address of
8529 // subsequent stores as an offset from the previous.
8530 if (StoreCount > 0)
8531 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
8532
8533 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8534 Builder.CreateCall(StNFunc, Ops);
8535 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00008536 return true;
8537}
8538
Tim Northover3b0846e2014-05-24 12:50:23 +00008539static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8540 unsigned AlignCheck) {
8541 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8542 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8543}
8544
8545EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
8546 unsigned SrcAlign, bool IsMemset,
8547 bool ZeroMemset,
8548 bool MemcpyStrSrc,
8549 MachineFunction &MF) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008550 const Function &F = MF.getFunction();
JF Bastien29200612018-09-06 16:03:32 +00008551 bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat);
8552 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8553 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8554 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8555 // taken one instruction to materialize the v2i64 zero and one store (with
8556 // restrictive addressing mode). Just do i64 stores.
8557 bool IsSmallMemset = IsMemset && Size < 32;
8558 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8559 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8560 return true;
8561 bool Fast;
8562 return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast;
8563 };
8564
8565 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8566 AlignmentIsAcceptable(MVT::v2i64, 16))
8567 return MVT::v2i64;
8568 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
Tim Northover3b0846e2014-05-24 12:50:23 +00008569 return MVT::f128;
JF Bastien29200612018-09-06 16:03:32 +00008570 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
Lang Hames90333852015-04-09 03:40:33 +00008571 return MVT::i64;
JF Bastien29200612018-09-06 16:03:32 +00008572 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
Lang Hames522bf132015-04-09 05:34:57 +00008573 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00008574 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00008575}
8576
8577// 12-bit optionally shifted immediates are legal for adds.
8578bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008579 if (Immed == std::numeric_limits<int64_t>::min()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008580 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8581 << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00008582 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008583 }
Geoff Berry486f49c2016-06-07 16:48:43 +00008584 // Same encoding for add/sub, just flip the sign.
8585 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008586 bool IsLegal = ((Immed >> 12) == 0 ||
8587 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00008588 LLVM_DEBUG(dbgs() << "Is " << Immed
8589 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00008590 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00008591}
8592
8593// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8594// immediates is the same as for an add or a sub.
8595bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008596 return isLegalAddImmediate(Immed);
8597}
8598
8599/// isLegalAddressingMode - Return true if the addressing mode represented
8600/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008601bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8602 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00008603 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008604 // AArch64 has five basic addressing modes:
8605 // reg
8606 // reg + 9-bit signed offset
8607 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8608 // reg1 + reg2
8609 // reg + SIZE_IN_BYTES * reg
8610
8611 // No global is ever allowed as a base.
8612 if (AM.BaseGV)
8613 return false;
8614
8615 // No reg+reg+imm addressing.
8616 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8617 return false;
8618
8619 // check reg + imm case:
8620 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8621 uint64_t NumBytes = 0;
8622 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008623 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008624 NumBytes = NumBits / 8;
8625 if (!isPowerOf2_64(NumBits))
8626 NumBytes = 0;
8627 }
8628
8629 if (!AM.Scale) {
8630 int64_t Offset = AM.BaseOffs;
8631
8632 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008633 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008634 return true;
8635
8636 // 12-bit unsigned offset
8637 unsigned shift = Log2_64(NumBytes);
8638 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8639 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8640 (Offset >> shift) << shift == Offset)
8641 return true;
8642 return false;
8643 }
8644
8645 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8646
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008647 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008648}
8649
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00008650bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8651 // Consider splitting large offset of struct or array.
8652 return true;
8653}
8654
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008655int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8656 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008657 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008658 // Scaling factors are not free at all.
8659 // Operands | Rt Latency
8660 // -------------------------------------------
8661 // Rt, [Xn, Xm] | 4
8662 // -------------------------------------------
8663 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8664 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008665 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008666 // Scale represents reg2 * scale, thus account for 1 if
8667 // it is not equal to 0 or 1.
8668 return AM.Scale != 0 && AM.Scale != 1;
8669 return -1;
8670}
8671
8672bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8673 VT = VT.getScalarType();
8674
8675 if (!VT.isSimple())
8676 return false;
8677
8678 switch (VT.getSimpleVT().SimpleTy) {
8679 case MVT::f32:
8680 case MVT::f64:
8681 return true;
8682 default:
8683 break;
8684 }
8685
8686 return false;
8687}
8688
8689const MCPhysReg *
8690AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8691 // LR is a callee-save register, but we must treat it as clobbered by any call
8692 // site. Hence we include LR in the scratch registers, which are in turn added
8693 // as implicit-defs for stackmaps and patchpoints.
8694 static const MCPhysReg ScratchRegs[] = {
8695 AArch64::X16, AArch64::X17, AArch64::LR, 0
8696 };
8697 return ScratchRegs;
8698}
8699
8700bool
Eli Friedman0d12e902018-08-14 22:10:25 +00008701AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8702 CombineLevel Level) const {
8703 N = N->getOperand(0).getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008704 EVT VT = N->getValueType(0);
8705 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8706 // it with shift to let it be lowered to UBFX.
8707 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8708 isa<ConstantSDNode>(N->getOperand(1))) {
8709 uint64_t TruncMask = N->getConstantOperandVal(1);
8710 if (isMask_64(TruncMask) &&
8711 N->getOperand(0).getOpcode() == ISD::SRL &&
8712 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8713 return false;
8714 }
8715 return true;
8716}
8717
8718bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8719 Type *Ty) const {
8720 assert(Ty->isIntegerTy());
8721
8722 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8723 if (BitSize == 0)
8724 return false;
8725
8726 int64_t Val = Imm.getSExtValue();
8727 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8728 return true;
8729
8730 if ((int64_t)Val < 0)
8731 Val = ~Val;
8732 if (BitSize == 32)
8733 Val &= (1LL << 32) - 1;
8734
8735 unsigned LZ = countLeadingZeros((uint64_t)Val);
8736 unsigned Shift = (63 - LZ) / 16;
8737 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008738 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008739}
8740
Sebastian Pop41073e82018-03-06 16:54:55 +00008741bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8742 unsigned Index) const {
8743 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8744 return false;
8745
8746 return (Index == 0 || Index == ResVT.getVectorNumElements());
8747}
8748
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008749/// Turn vector tests of the signbit in the form of:
8750/// xor (sra X, elt_size(X)-1), -1
8751/// into:
8752/// cmge X, X, #0
8753static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8754 const AArch64Subtarget *Subtarget) {
8755 EVT VT = N->getValueType(0);
8756 if (!Subtarget->hasNEON() || !VT.isVector())
8757 return SDValue();
8758
8759 // There must be a shift right algebraic before the xor, and the xor must be a
8760 // 'not' operation.
8761 SDValue Shift = N->getOperand(0);
8762 SDValue Ones = N->getOperand(1);
8763 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8764 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8765 return SDValue();
8766
8767 // The shift should be smearing the sign bit across each vector element.
8768 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8769 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8770 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8771 return SDValue();
8772
8773 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8774}
8775
Tim Northover3b0846e2014-05-24 12:50:23 +00008776// Generate SUBS and CSEL for integer abs.
8777static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8778 EVT VT = N->getValueType(0);
8779
8780 SDValue N0 = N->getOperand(0);
8781 SDValue N1 = N->getOperand(1);
8782 SDLoc DL(N);
8783
8784 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8785 // and change it to SUB and CSEL.
8786 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8787 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8788 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8789 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8790 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008791 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008792 N0.getOperand(0));
8793 // Generate SUBS & CSEL.
8794 SDValue Cmp =
8795 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008796 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008797 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008798 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008799 SDValue(Cmp.getNode(), 1));
8800 }
8801 return SDValue();
8802}
8803
Tim Northover3b0846e2014-05-24 12:50:23 +00008804static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8805 TargetLowering::DAGCombinerInfo &DCI,
8806 const AArch64Subtarget *Subtarget) {
8807 if (DCI.isBeforeLegalizeOps())
8808 return SDValue();
8809
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008810 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8811 return Cmp;
8812
Tim Northover3b0846e2014-05-24 12:50:23 +00008813 return performIntegerAbsCombine(N, DAG);
8814}
8815
Chad Rosier17020f92014-07-23 14:57:52 +00008816SDValue
8817AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8818 SelectionDAG &DAG,
Craig Topper2f60ef22018-07-30 23:22:00 +00008819 SmallVectorImpl<SDNode *> &Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008820 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008821 if (isIntDivCheap(N->getValueType(0), Attr))
8822 return SDValue(N,0); // Lower SDIV as SDIV
8823
Chad Rosier17020f92014-07-23 14:57:52 +00008824 // fold (sdiv X, pow2)
8825 EVT VT = N->getValueType(0);
8826 if ((VT != MVT::i32 && VT != MVT::i64) ||
8827 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8828 return SDValue();
8829
8830 SDLoc DL(N);
8831 SDValue N0 = N->getOperand(0);
8832 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008833 SDValue Zero = DAG.getConstant(0, DL, VT);
8834 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008835
8836 // Add (N0 < 0) ? Pow2 - 1 : 0;
8837 SDValue CCVal;
8838 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8839 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8840 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8841
Craig Toppera568a272018-07-30 21:04:34 +00008842 Created.push_back(Cmp.getNode());
8843 Created.push_back(Add.getNode());
8844 Created.push_back(CSel.getNode());
Chad Rosier17020f92014-07-23 14:57:52 +00008845
8846 // Divide by pow2.
8847 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008848 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008849
8850 // If we're dividing by a positive value, we're done. Otherwise, we must
8851 // negate the result.
8852 if (Divisor.isNonNegative())
8853 return SRA;
8854
Craig Toppera568a272018-07-30 21:04:34 +00008855 Created.push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008856 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008857}
8858
Tim Northover3b0846e2014-05-24 12:50:23 +00008859static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8860 TargetLowering::DAGCombinerInfo &DCI,
8861 const AArch64Subtarget *Subtarget) {
8862 if (DCI.isBeforeLegalizeOps())
8863 return SDValue();
8864
Chad Rosier31ee8132016-11-11 17:07:37 +00008865 // The below optimizations require a constant RHS.
8866 if (!isa<ConstantSDNode>(N->getOperand(1)))
8867 return SDValue();
8868
8869 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8870 const APInt &ConstValue = C->getAPIntValue();
8871
Tim Northover3b0846e2014-05-24 12:50:23 +00008872 // Multiplication of a power of two plus/minus one can be done more
8873 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8874 // future CPUs have a cheaper MADD instruction, this may need to be
8875 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8876 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008877 // More aggressively, some multiplications N0 * C can be lowered to
8878 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8879 // e.g. 6=3*2=(2+1)*2.
8880 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8881 // which equals to (1+2)*16-(1+2).
8882 SDValue N0 = N->getOperand(0);
8883 // TrailingZeroes is used to test if the mul can be lowered to
8884 // shift+add+shift.
8885 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8886 if (TrailingZeroes) {
8887 // Conservatively do not lower to shift+add+shift if the mul might be
8888 // folded into smul or umul.
8889 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8890 isZeroExtended(N0.getNode(), DAG)))
8891 return SDValue();
8892 // Conservatively do not lower to shift+add+shift if the mul might be
8893 // folded into madd or msub.
8894 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8895 N->use_begin()->getOpcode() == ISD::SUB))
8896 return SDValue();
8897 }
8898 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8899 // and shift+add+shift.
8900 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8901
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008902 unsigned ShiftAmt, AddSubOpc;
8903 // Is the shifted value the LHS operand of the add/sub?
8904 bool ShiftValUseIsN0 = true;
8905 // Do we need to negate the result?
8906 bool NegateResult = false;
8907
Chad Rosier31ee8132016-11-11 17:07:37 +00008908 if (ConstValue.isNonNegative()) {
8909 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00008910 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00008911 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8912 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008913 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00008914 if (SCVMinus1.isPowerOf2()) {
8915 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008916 AddSubOpc = ISD::ADD;
8917 } else if (CVPlus1.isPowerOf2()) {
8918 ShiftAmt = CVPlus1.logBase2();
8919 AddSubOpc = ISD::SUB;
8920 } else
8921 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00008922 } else {
8923 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00008924 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008925 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008926 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008927 if (CVNegPlus1.isPowerOf2()) {
8928 ShiftAmt = CVNegPlus1.logBase2();
8929 AddSubOpc = ISD::SUB;
8930 ShiftValUseIsN0 = false;
8931 } else if (CVNegMinus1.isPowerOf2()) {
8932 ShiftAmt = CVNegMinus1.logBase2();
8933 AddSubOpc = ISD::ADD;
8934 NegateResult = true;
8935 } else
8936 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008937 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008938
8939 SDLoc DL(N);
8940 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008941 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008942 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8943
8944 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8945 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8946 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008947 assert(!(NegateResult && TrailingZeroes) &&
8948 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008949 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008950 if (NegateResult)
8951 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8952 // Shift the result.
8953 if (TrailingZeroes)
8954 return DAG.getNode(ISD::SHL, DL, VT, Res,
8955 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8956 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00008957}
8958
Jim Grosbachf7502c42014-07-18 00:40:52 +00008959static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8960 SelectionDAG &DAG) {
8961 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8962 // optimize away operation when it's from a constant.
8963 //
8964 // The general transformation is:
8965 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8966 // AND(VECTOR_CMP(x,y), constant2)
8967 // constant2 = UNARYOP(constant)
8968
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008969 // Early exit if this isn't a vector operation, the operand of the
8970 // unary operation isn't a bitwise AND, or if the sizes of the operations
8971 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00008972 EVT VT = N->getValueType(0);
8973 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008974 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8975 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008976 return SDValue();
8977
Jim Grosbach724e4382014-07-23 20:41:43 +00008978 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00008979 // make the transformation for non-constant splats as well, but it's unclear
8980 // that would be a benefit as it would not eliminate any operations, just
8981 // perform one more step in scalar code before moving to the vector unit.
8982 if (BuildVectorSDNode *BV =
8983 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00008984 // Bail out if the vector isn't a constant.
8985 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008986 return SDValue();
8987
8988 // Everything checks out. Build up the new and improved node.
8989 SDLoc DL(N);
8990 EVT IntVT = BV->getValueType(0);
8991 // Create a new constant of the appropriate type for the transformed
8992 // DAG.
8993 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8994 // The AND node needs bitcasts to/from an integer vector type around it.
8995 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8996 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8997 N->getOperand(0)->getOperand(0), MaskConst);
8998 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8999 return Res;
9000 }
9001
9002 return SDValue();
9003}
9004
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009005static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9006 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00009007 // First try to optimize away the conversion when it's conditionally from
9008 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00009009 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00009010 return Res;
9011
Tim Northover3b0846e2014-05-24 12:50:23 +00009012 EVT VT = N->getValueType(0);
9013 if (VT != MVT::f32 && VT != MVT::f64)
9014 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00009015
Tim Northover3b0846e2014-05-24 12:50:23 +00009016 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009017 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00009018 return SDValue();
9019
9020 // If the result of an integer load is only used by an integer-to-float
9021 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00009022 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00009023 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009024 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009025 // Do not change the width of a volatile load.
9026 !cast<LoadSDNode>(N0)->isVolatile()) {
9027 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9028 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00009029 LN0->getPointerInfo(), LN0->getAlignment(),
9030 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009031
9032 // Make sure successors of the original load stay after it by updating them
9033 // to use the new Chain.
9034 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9035
9036 unsigned Opcode =
9037 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9038 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9039 }
9040
9041 return SDValue();
9042}
9043
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009044/// Fold a floating-point multiply by power of two into floating-point to
9045/// fixed-point conversion.
9046static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00009047 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009048 const AArch64Subtarget *Subtarget) {
9049 if (!Subtarget->hasNEON())
9050 return SDValue();
9051
9052 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00009053 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9054 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009055 return SDValue();
9056
9057 SDValue ConstVec = Op->getOperand(1);
9058 if (!isa<BuildVectorSDNode>(ConstVec))
9059 return SDValue();
9060
9061 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9062 uint32_t FloatBits = FloatTy.getSizeInBits();
9063 if (FloatBits != 32 && FloatBits != 64)
9064 return SDValue();
9065
9066 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9067 uint32_t IntBits = IntTy.getSizeInBits();
9068 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9069 return SDValue();
9070
9071 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9072 if (IntBits > FloatBits)
9073 return SDValue();
9074
9075 BitVector UndefElements;
9076 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9077 int32_t Bits = IntBits == 64 ? 64 : 32;
9078 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9079 if (C == -1 || C == 0 || C > Bits)
9080 return SDValue();
9081
9082 MVT ResTy;
9083 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9084 switch (NumLanes) {
9085 default:
9086 return SDValue();
9087 case 2:
9088 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9089 break;
9090 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009091 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009092 break;
9093 }
9094
Silviu Barangafa00ba32016-08-08 13:13:57 +00009095 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9096 return SDValue();
9097
9098 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9099 "Illegal vector type after legalization");
9100
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009101 SDLoc DL(N);
9102 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9103 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9104 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9105 SDValue FixConv =
9106 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9107 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9108 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9109 // We can handle smaller integers by generating an extra trunc.
9110 if (IntBits < FloatBits)
9111 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9112
9113 return FixConv;
9114}
9115
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009116/// Fold a floating-point divide by power of two into fixed-point to
9117/// floating-point conversion.
9118static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00009119 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009120 const AArch64Subtarget *Subtarget) {
9121 if (!Subtarget->hasNEON())
9122 return SDValue();
9123
9124 SDValue Op = N->getOperand(0);
9125 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00009126 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9127 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009128 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9129 return SDValue();
9130
9131 SDValue ConstVec = N->getOperand(1);
9132 if (!isa<BuildVectorSDNode>(ConstVec))
9133 return SDValue();
9134
9135 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9136 int32_t IntBits = IntTy.getSizeInBits();
9137 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9138 return SDValue();
9139
9140 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9141 int32_t FloatBits = FloatTy.getSizeInBits();
9142 if (FloatBits != 32 && FloatBits != 64)
9143 return SDValue();
9144
9145 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9146 if (IntBits > FloatBits)
9147 return SDValue();
9148
9149 BitVector UndefElements;
9150 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9151 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9152 if (C == -1 || C == 0 || C > FloatBits)
9153 return SDValue();
9154
9155 MVT ResTy;
9156 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9157 switch (NumLanes) {
9158 default:
9159 return SDValue();
9160 case 2:
9161 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9162 break;
9163 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00009164 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009165 break;
9166 }
9167
Tim Northover85cf5642016-08-26 18:52:31 +00009168 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9169 return SDValue();
9170
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009171 SDLoc DL(N);
9172 SDValue ConvInput = Op.getOperand(0);
9173 bool IsSigned = Opc == ISD::SINT_TO_FP;
9174 if (IntBits < FloatBits)
9175 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9176 ResTy, ConvInput);
9177
9178 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9179 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9180 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9181 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9182 DAG.getConstant(C, DL, MVT::i32));
9183}
9184
Tim Northover3b0846e2014-05-24 12:50:23 +00009185/// An EXTR instruction is made up of two shifts, ORed together. This helper
9186/// searches for and classifies those shifts.
9187static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9188 bool &FromHi) {
9189 if (N.getOpcode() == ISD::SHL)
9190 FromHi = false;
9191 else if (N.getOpcode() == ISD::SRL)
9192 FromHi = true;
9193 else
9194 return false;
9195
9196 if (!isa<ConstantSDNode>(N.getOperand(1)))
9197 return false;
9198
9199 ShiftAmount = N->getConstantOperandVal(1);
9200 Src = N->getOperand(0);
9201 return true;
9202}
9203
9204/// EXTR instruction extracts a contiguous chunk of bits from two existing
9205/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00009206/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9207/// with an EXTR. Can't quite be done in TableGen because the two immediates
9208/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00009209static SDValue tryCombineToEXTR(SDNode *N,
9210 TargetLowering::DAGCombinerInfo &DCI) {
9211 SelectionDAG &DAG = DCI.DAG;
9212 SDLoc DL(N);
9213 EVT VT = N->getValueType(0);
9214
9215 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9216
9217 if (VT != MVT::i32 && VT != MVT::i64)
9218 return SDValue();
9219
9220 SDValue LHS;
9221 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009222 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009223 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9224 return SDValue();
9225
9226 SDValue RHS;
9227 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009228 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00009229 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9230 return SDValue();
9231
9232 // If they're both trying to come from the high part of the register, they're
9233 // not really an EXTR.
9234 if (LHSFromHi == RHSFromHi)
9235 return SDValue();
9236
9237 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9238 return SDValue();
9239
9240 if (LHSFromHi) {
9241 std::swap(LHS, RHS);
9242 std::swap(ShiftLHS, ShiftRHS);
9243 }
9244
9245 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009246 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009247}
9248
9249static SDValue tryCombineToBSL(SDNode *N,
9250 TargetLowering::DAGCombinerInfo &DCI) {
9251 EVT VT = N->getValueType(0);
9252 SelectionDAG &DAG = DCI.DAG;
9253 SDLoc DL(N);
9254
9255 if (!VT.isVector())
9256 return SDValue();
9257
9258 SDValue N0 = N->getOperand(0);
9259 if (N0.getOpcode() != ISD::AND)
9260 return SDValue();
9261
9262 SDValue N1 = N->getOperand(1);
9263 if (N1.getOpcode() != ISD::AND)
9264 return SDValue();
9265
9266 // We only have to look for constant vectors here since the general, variable
9267 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009268 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009269 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9270 for (int i = 1; i >= 0; --i)
9271 for (int j = 1; j >= 0; --j) {
9272 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9273 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9274 if (!BVN0 || !BVN1)
9275 continue;
9276
9277 bool FoundMatch = true;
9278 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9279 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9280 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9281 if (!CN0 || !CN1 ||
9282 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9283 FoundMatch = false;
9284 break;
9285 }
9286 }
9287
9288 if (FoundMatch)
9289 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9290 N0->getOperand(1 - i), N1->getOperand(1 - j));
9291 }
9292
9293 return SDValue();
9294}
9295
9296static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9297 const AArch64Subtarget *Subtarget) {
9298 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00009299 SelectionDAG &DAG = DCI.DAG;
9300 EVT VT = N->getValueType(0);
9301
9302 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9303 return SDValue();
9304
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009305 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009306 return Res;
9307
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009308 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00009309 return Res;
9310
9311 return SDValue();
9312}
9313
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009314static SDValue performSRLCombine(SDNode *N,
9315 TargetLowering::DAGCombinerInfo &DCI) {
9316 SelectionDAG &DAG = DCI.DAG;
9317 EVT VT = N->getValueType(0);
9318 if (VT != MVT::i32 && VT != MVT::i64)
9319 return SDValue();
9320
9321 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9322 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9323 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9324 SDValue N0 = N->getOperand(0);
9325 if (N0.getOpcode() == ISD::BSWAP) {
9326 SDLoc DL(N);
9327 SDValue N1 = N->getOperand(1);
9328 SDValue N00 = N0.getOperand(0);
9329 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9330 uint64_t ShiftAmt = C->getZExtValue();
9331 if (VT == MVT::i32 && ShiftAmt == 16 &&
9332 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9333 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9334 if (VT == MVT::i64 && ShiftAmt == 32 &&
9335 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9336 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9337 }
9338 }
9339 return SDValue();
9340}
9341
Tim Northover3b0846e2014-05-24 12:50:23 +00009342static SDValue performBitcastCombine(SDNode *N,
9343 TargetLowering::DAGCombinerInfo &DCI,
9344 SelectionDAG &DAG) {
9345 // Wait 'til after everything is legalized to try this. That way we have
9346 // legal vector types and such.
9347 if (DCI.isBeforeLegalizeOps())
9348 return SDValue();
9349
9350 // Remove extraneous bitcasts around an extract_subvector.
9351 // For example,
9352 // (v4i16 (bitconvert
9353 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9354 // becomes
9355 // (extract_subvector ((v8i16 ...), (i64 4)))
9356
9357 // Only interested in 64-bit vectors as the ultimate result.
9358 EVT VT = N->getValueType(0);
9359 if (!VT.isVector())
9360 return SDValue();
9361 if (VT.getSimpleVT().getSizeInBits() != 64)
9362 return SDValue();
9363 // Is the operand an extract_subvector starting at the beginning or halfway
9364 // point of the vector? A low half may also come through as an
9365 // EXTRACT_SUBREG, so look for that, too.
9366 SDValue Op0 = N->getOperand(0);
9367 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9368 !(Op0->isMachineOpcode() &&
9369 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9370 return SDValue();
9371 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9372 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9373 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9374 return SDValue();
9375 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9376 if (idx != AArch64::dsub)
9377 return SDValue();
9378 // The dsub reference is equivalent to a lane zero subvector reference.
9379 idx = 0;
9380 }
9381 // Look through the bitcast of the input to the extract.
9382 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9383 return SDValue();
9384 SDValue Source = Op0->getOperand(0)->getOperand(0);
9385 // If the source type has twice the number of elements as our destination
9386 // type, we know this is an extract of the high or low half of the vector.
9387 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00009388 if (!SVT.isVector() ||
9389 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00009390 return SDValue();
9391
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009392 LLVM_DEBUG(
9393 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009394
9395 // Create the simplified form to just extract the low or high half of the
9396 // vector directly rather than bothering with the bitcasts.
9397 SDLoc dl(N);
9398 unsigned NumElements = VT.getVectorNumElements();
9399 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009400 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00009401 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9402 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009403 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009404 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9405 Source, SubReg),
9406 0);
9407 }
9408}
9409
9410static SDValue performConcatVectorsCombine(SDNode *N,
9411 TargetLowering::DAGCombinerInfo &DCI,
9412 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009413 SDLoc dl(N);
9414 EVT VT = N->getValueType(0);
9415 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9416
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009417 // Optimize concat_vectors of truncated vectors, where the intermediate
9418 // type is illegal, to avoid said illegality, e.g.,
9419 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9420 // (v2i16 (truncate (v2i64)))))
9421 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009422 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9423 // (v4i32 (bitcast (v2i64))),
9424 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009425 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9426 // on both input and result type, so we might generate worse code.
9427 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9428 if (N->getNumOperands() == 2 &&
9429 N0->getOpcode() == ISD::TRUNCATE &&
9430 N1->getOpcode() == ISD::TRUNCATE) {
9431 SDValue N00 = N0->getOperand(0);
9432 SDValue N10 = N1->getOperand(0);
9433 EVT N00VT = N00.getValueType();
9434
9435 if (N00VT == N10.getValueType() &&
9436 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9437 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00009438 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9439 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9440 for (size_t i = 0; i < Mask.size(); ++i)
9441 Mask[i] = i * 2;
9442 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9443 DAG.getVectorShuffle(
9444 MidVT, dl,
9445 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9446 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00009447 }
9448 }
9449
Tim Northover3b0846e2014-05-24 12:50:23 +00009450 // Wait 'til after everything is legalized to try this. That way we have
9451 // legal vector types and such.
9452 if (DCI.isBeforeLegalizeOps())
9453 return SDValue();
9454
Tim Northover3b0846e2014-05-24 12:50:23 +00009455 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9456 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9457 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009458 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009459 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009460 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009461 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009462 }
9463
9464 // Canonicalise concat_vectors so that the right-hand vector has as few
9465 // bit-casts as possible before its real operation. The primary matching
9466 // destination for these operations will be the narrowing "2" instructions,
9467 // which depend on the operation being performed on this right-hand vector.
9468 // For example,
9469 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9470 // becomes
9471 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9472
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009473 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00009474 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009475 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009476 MVT RHSTy = RHS.getValueType().getSimpleVT();
9477 // If the RHS is not a vector, this is not the pattern we're looking for.
9478 if (!RHSTy.isVector())
9479 return SDValue();
9480
Nicola Zaghend34e60c2018-05-14 12:53:11 +00009481 LLVM_DEBUG(
9482 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00009483
9484 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9485 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00009486 return DAG.getNode(ISD::BITCAST, dl, VT,
9487 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9488 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9489 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00009490}
9491
9492static SDValue tryCombineFixedPointConvert(SDNode *N,
9493 TargetLowering::DAGCombinerInfo &DCI,
9494 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00009495 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00009496 // legal vector types and such.
9497 if (DCI.isBeforeLegalizeOps())
9498 return SDValue();
9499 // Transform a scalar conversion of a value from a lane extract into a
9500 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9501 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9502 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9503 //
9504 // The second form interacts better with instruction selection and the
9505 // register allocator to avoid cross-class register copies that aren't
9506 // coalescable due to a lane reference.
9507
9508 // Check the operand and see if it originates from a lane extract.
9509 SDValue Op1 = N->getOperand(1);
9510 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9511 // Yep, no additional predication needed. Perform the transform.
9512 SDValue IID = N->getOperand(0);
9513 SDValue Shift = N->getOperand(2);
9514 SDValue Vec = Op1.getOperand(0);
9515 SDValue Lane = Op1.getOperand(1);
9516 EVT ResTy = N->getValueType(0);
9517 EVT VecResTy;
9518 SDLoc DL(N);
9519
9520 // The vector width should be 128 bits by the time we get here, even
9521 // if it started as 64 bits (the extract_vector handling will have
9522 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00009523 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00009524 "unexpected vector size on extract_vector_elt!");
9525 if (Vec.getValueType() == MVT::v4i32)
9526 VecResTy = MVT::v4f32;
9527 else if (Vec.getValueType() == MVT::v2i64)
9528 VecResTy = MVT::v2f64;
9529 else
Craig Topper2a30d782014-06-18 05:05:13 +00009530 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00009531
9532 SDValue Convert =
9533 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9534 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9535 }
9536 return SDValue();
9537}
9538
9539// AArch64 high-vector "long" operations are formed by performing the non-high
9540// version on an extract_subvector of each operand which gets the high half:
9541//
9542// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9543//
9544// However, there are cases which don't have an extract_high explicitly, but
9545// have another operation that can be made compatible with one for free. For
9546// example:
9547//
9548// (dupv64 scalar) --> (extract_high (dup128 scalar))
9549//
9550// This routine does the actual conversion of such DUPs, once outer routines
9551// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009552// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9553// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00009554static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009555 switch (N.getOpcode()) {
9556 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00009557 case AArch64ISD::DUPLANE8:
9558 case AArch64ISD::DUPLANE16:
9559 case AArch64ISD::DUPLANE32:
9560 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009561 case AArch64ISD::MOVI:
9562 case AArch64ISD::MOVIshift:
9563 case AArch64ISD::MOVIedit:
9564 case AArch64ISD::MOVImsl:
9565 case AArch64ISD::MVNIshift:
9566 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00009567 break;
9568 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009569 // FMOV could be supported, but isn't very useful, as it would only occur
9570 // if you passed a bitcast' floating point immediate to an eligible long
9571 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00009572 return SDValue();
9573 }
9574
9575 MVT NarrowTy = N.getSimpleValueType();
9576 if (!NarrowTy.is64BitVector())
9577 return SDValue();
9578
9579 MVT ElementTy = NarrowTy.getVectorElementType();
9580 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009581 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009582
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009583 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009584 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9585 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009586 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009587}
9588
9589static bool isEssentiallyExtractSubvector(SDValue N) {
9590 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9591 return true;
9592
9593 return N.getOpcode() == ISD::BITCAST &&
9594 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
9595}
9596
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009597/// Helper structure to keep track of ISD::SET_CC operands.
Tim Northover3b0846e2014-05-24 12:50:23 +00009598struct GenericSetCCInfo {
9599 const SDValue *Opnd0;
9600 const SDValue *Opnd1;
9601 ISD::CondCode CC;
9602};
9603
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009604/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
Tim Northover3b0846e2014-05-24 12:50:23 +00009605struct AArch64SetCCInfo {
9606 const SDValue *Cmp;
9607 AArch64CC::CondCode CC;
9608};
9609
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009610/// Helper structure to keep track of SetCC information.
Tim Northover3b0846e2014-05-24 12:50:23 +00009611union SetCCInfo {
9612 GenericSetCCInfo Generic;
9613 AArch64SetCCInfo AArch64;
9614};
9615
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009616/// Helper structure to be able to read SetCC information. If set to
Tim Northover3b0846e2014-05-24 12:50:23 +00009617/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9618/// GenericSetCCInfo.
9619struct SetCCInfoAndKind {
9620 SetCCInfo Info;
9621 bool IsAArch64;
9622};
9623
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00009624/// Check whether or not \p Op is a SET_CC operation, either a generic or
Tim Northover3b0846e2014-05-24 12:50:23 +00009625/// an
9626/// AArch64 lowered one.
9627/// \p SetCCInfo is filled accordingly.
9628/// \post SetCCInfo is meanginfull only when this function returns true.
9629/// \return True when Op is a kind of SET_CC operation.
9630static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9631 // If this is a setcc, this is straight forward.
9632 if (Op.getOpcode() == ISD::SETCC) {
9633 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9634 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9635 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9636 SetCCInfo.IsAArch64 = false;
9637 return true;
9638 }
9639 // Otherwise, check if this is a matching csel instruction.
9640 // In other words:
9641 // - csel 1, 0, cc
9642 // - csel 0, 1, !cc
9643 if (Op.getOpcode() != AArch64ISD::CSEL)
9644 return false;
9645 // Set the information about the operands.
9646 // TODO: we want the operands of the Cmp not the csel
9647 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9648 SetCCInfo.IsAArch64 = true;
9649 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9650 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9651
9652 // Check that the operands matches the constraints:
9653 // (1) Both operands must be constants.
9654 // (2) One must be 1 and the other must be 0.
9655 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9656 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9657
9658 // Check (1).
9659 if (!TValue || !FValue)
9660 return false;
9661
9662 // Check (2).
9663 if (!TValue->isOne()) {
9664 // Update the comparison when we are interested in !cc.
9665 std::swap(TValue, FValue);
9666 SetCCInfo.Info.AArch64.CC =
9667 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9668 }
9669 return TValue->isOne() && FValue->isNullValue();
9670}
9671
9672// Returns true if Op is setcc or zext of setcc.
9673static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9674 if (isSetCC(Op, Info))
9675 return true;
9676 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9677 isSetCC(Op->getOperand(0), Info));
9678}
9679
9680// The folding we want to perform is:
9681// (add x, [zext] (setcc cc ...) )
9682// -->
9683// (csel x, (add x, 1), !cc ...)
9684//
9685// The latter will get matched to a CSINC instruction.
9686static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9687 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9688 SDValue LHS = Op->getOperand(0);
9689 SDValue RHS = Op->getOperand(1);
9690 SetCCInfoAndKind InfoAndKind;
9691
9692 // If neither operand is a SET_CC, give up.
9693 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9694 std::swap(LHS, RHS);
9695 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9696 return SDValue();
9697 }
9698
9699 // FIXME: This could be generatized to work for FP comparisons.
9700 EVT CmpVT = InfoAndKind.IsAArch64
9701 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9702 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9703 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9704 return SDValue();
9705
9706 SDValue CCVal;
9707 SDValue Cmp;
9708 SDLoc dl(Op);
9709 if (InfoAndKind.IsAArch64) {
9710 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009711 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9712 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009713 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9714 } else
9715 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9716 *InfoAndKind.Info.Generic.Opnd1,
9717 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9718 CCVal, DAG, dl);
9719
9720 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009721 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009722 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9723}
9724
9725// The basic add/sub long vector instructions have variants with "2" on the end
9726// which act on the high-half of their inputs. They are normally matched by
9727// patterns like:
9728//
9729// (add (zeroext (extract_high LHS)),
9730// (zeroext (extract_high RHS)))
9731// -> uaddl2 vD, vN, vM
9732//
9733// However, if one of the extracts is something like a duplicate, this
9734// instruction can still be used profitably. This function puts the DAG into a
9735// more appropriate form for those patterns to trigger.
9736static SDValue performAddSubLongCombine(SDNode *N,
9737 TargetLowering::DAGCombinerInfo &DCI,
9738 SelectionDAG &DAG) {
9739 if (DCI.isBeforeLegalizeOps())
9740 return SDValue();
9741
9742 MVT VT = N->getSimpleValueType(0);
9743 if (!VT.is128BitVector()) {
9744 if (N->getOpcode() == ISD::ADD)
9745 return performSetccAddFolding(N, DAG);
9746 return SDValue();
9747 }
9748
9749 // Make sure both branches are extended in the same way.
9750 SDValue LHS = N->getOperand(0);
9751 SDValue RHS = N->getOperand(1);
9752 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9753 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9754 LHS.getOpcode() != RHS.getOpcode())
9755 return SDValue();
9756
9757 unsigned ExtType = LHS.getOpcode();
9758
9759 // It's not worth doing if at least one of the inputs isn't already an
9760 // extract, but we don't know which it'll be so we have to try both.
9761 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9762 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9763 if (!RHS.getNode())
9764 return SDValue();
9765
9766 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9767 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9768 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9769 if (!LHS.getNode())
9770 return SDValue();
9771
9772 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9773 }
9774
9775 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9776}
9777
9778// Massage DAGs which we can use the high-half "long" operations on into
9779// something isel will recognize better. E.g.
9780//
9781// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9782// (aarch64_neon_umull (extract_high (v2i64 vec)))
9783// (extract_high (v2i64 (dup128 scalar)))))
9784//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009785static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009786 TargetLowering::DAGCombinerInfo &DCI,
9787 SelectionDAG &DAG) {
9788 if (DCI.isBeforeLegalizeOps())
9789 return SDValue();
9790
Hal Finkelcd8664c2015-12-11 23:11:52 +00009791 SDValue LHS = N->getOperand(1);
9792 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009793 assert(LHS.getValueType().is64BitVector() &&
9794 RHS.getValueType().is64BitVector() &&
9795 "unexpected shape for long operation");
9796
9797 // Either node could be a DUP, but it's not worth doing both of them (you'd
9798 // just as well use the non-high version) so look for a corresponding extract
9799 // operation on the other "wing".
9800 if (isEssentiallyExtractSubvector(LHS)) {
9801 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9802 if (!RHS.getNode())
9803 return SDValue();
9804 } else if (isEssentiallyExtractSubvector(RHS)) {
9805 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9806 if (!LHS.getNode())
9807 return SDValue();
9808 }
9809
Hal Finkelcd8664c2015-12-11 23:11:52 +00009810 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9811 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009812}
9813
9814static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9815 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9816 unsigned ElemBits = ElemTy.getSizeInBits();
9817
9818 int64_t ShiftAmount;
9819 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9820 APInt SplatValue, SplatUndef;
9821 unsigned SplatBitSize;
9822 bool HasAnyUndefs;
9823 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9824 HasAnyUndefs, ElemBits) ||
9825 SplatBitSize != ElemBits)
9826 return SDValue();
9827
9828 ShiftAmount = SplatValue.getSExtValue();
9829 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9830 ShiftAmount = CVN->getSExtValue();
9831 } else
9832 return SDValue();
9833
9834 unsigned Opcode;
9835 bool IsRightShift;
9836 switch (IID) {
9837 default:
9838 llvm_unreachable("Unknown shift intrinsic");
9839 case Intrinsic::aarch64_neon_sqshl:
9840 Opcode = AArch64ISD::SQSHL_I;
9841 IsRightShift = false;
9842 break;
9843 case Intrinsic::aarch64_neon_uqshl:
9844 Opcode = AArch64ISD::UQSHL_I;
9845 IsRightShift = false;
9846 break;
9847 case Intrinsic::aarch64_neon_srshl:
9848 Opcode = AArch64ISD::SRSHR_I;
9849 IsRightShift = true;
9850 break;
9851 case Intrinsic::aarch64_neon_urshl:
9852 Opcode = AArch64ISD::URSHR_I;
9853 IsRightShift = true;
9854 break;
9855 case Intrinsic::aarch64_neon_sqshlu:
9856 Opcode = AArch64ISD::SQSHLU_I;
9857 IsRightShift = false;
9858 break;
9859 }
9860
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009861 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9862 SDLoc dl(N);
9863 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9864 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9865 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9866 SDLoc dl(N);
9867 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9868 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9869 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009870
9871 return SDValue();
9872}
9873
9874// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9875// the intrinsics must be legal and take an i32, this means there's almost
9876// certainly going to be a zext in the DAG which we can eliminate.
9877static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9878 SDValue AndN = N->getOperand(2);
9879 if (AndN.getOpcode() != ISD::AND)
9880 return SDValue();
9881
9882 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9883 if (!CMask || CMask->getZExtValue() != Mask)
9884 return SDValue();
9885
9886 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9887 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9888}
9889
Ahmed Bougachafab58922015-03-10 20:45:38 +00009890static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9891 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009892 SDLoc dl(N);
9893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9894 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00009895 N->getOperand(1).getSimpleValueType(),
9896 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009897 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00009898}
9899
Tim Northover3b0846e2014-05-24 12:50:23 +00009900static SDValue performIntrinsicCombine(SDNode *N,
9901 TargetLowering::DAGCombinerInfo &DCI,
9902 const AArch64Subtarget *Subtarget) {
9903 SelectionDAG &DAG = DCI.DAG;
9904 unsigned IID = getIntrinsicID(N);
9905 switch (IID) {
9906 default:
9907 break;
9908 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9909 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9910 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00009911 case Intrinsic::aarch64_neon_saddv:
9912 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9913 case Intrinsic::aarch64_neon_uaddv:
9914 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9915 case Intrinsic::aarch64_neon_sminv:
9916 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9917 case Intrinsic::aarch64_neon_uminv:
9918 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9919 case Intrinsic::aarch64_neon_smaxv:
9920 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9921 case Intrinsic::aarch64_neon_umaxv:
9922 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009923 case Intrinsic::aarch64_neon_fmax:
Thomas Lively30f1d692018-10-24 22:49:55 +00009924 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009925 N->getOperand(1), N->getOperand(2));
9926 case Intrinsic::aarch64_neon_fmin:
Thomas Lively30f1d692018-10-24 22:49:55 +00009927 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009928 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00009929 case Intrinsic::aarch64_neon_fmaxnm:
9930 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9931 N->getOperand(1), N->getOperand(2));
9932 case Intrinsic::aarch64_neon_fminnm:
9933 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9934 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009935 case Intrinsic::aarch64_neon_smull:
9936 case Intrinsic::aarch64_neon_umull:
9937 case Intrinsic::aarch64_neon_pmull:
9938 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00009939 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009940 case Intrinsic::aarch64_neon_sqshl:
9941 case Intrinsic::aarch64_neon_uqshl:
9942 case Intrinsic::aarch64_neon_sqshlu:
9943 case Intrinsic::aarch64_neon_srshl:
9944 case Intrinsic::aarch64_neon_urshl:
9945 return tryCombineShiftImm(IID, N, DAG);
9946 case Intrinsic::aarch64_crc32b:
9947 case Intrinsic::aarch64_crc32cb:
9948 return tryCombineCRC32(0xff, N, DAG);
9949 case Intrinsic::aarch64_crc32h:
9950 case Intrinsic::aarch64_crc32ch:
9951 return tryCombineCRC32(0xffff, N, DAG);
9952 }
9953 return SDValue();
9954}
9955
9956static SDValue performExtendCombine(SDNode *N,
9957 TargetLowering::DAGCombinerInfo &DCI,
9958 SelectionDAG &DAG) {
9959 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9960 // we can convert that DUP into another extract_high (of a bigger DUP), which
9961 // helps the backend to decide that an sabdl2 would be useful, saving a real
9962 // extract_high operation.
9963 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00009964 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009965 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00009966 unsigned IID = getIntrinsicID(ABDNode);
9967 if (IID == Intrinsic::aarch64_neon_sabd ||
9968 IID == Intrinsic::aarch64_neon_uabd) {
9969 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9970 if (!NewABD.getNode())
9971 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009972
Hal Finkelcd8664c2015-12-11 23:11:52 +00009973 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9974 NewABD);
9975 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009976 }
9977
9978 // This is effectively a custom type legalization for AArch64.
9979 //
9980 // Type legalization will split an extend of a small, legal, type to a larger
9981 // illegal type by first splitting the destination type, often creating
9982 // illegal source types, which then get legalized in isel-confusing ways,
9983 // leading to really terrible codegen. E.g.,
9984 // %result = v8i32 sext v8i8 %value
9985 // becomes
9986 // %losrc = extract_subreg %value, ...
9987 // %hisrc = extract_subreg %value, ...
9988 // %lo = v4i32 sext v4i8 %losrc
9989 // %hi = v4i32 sext v4i8 %hisrc
9990 // Things go rapidly downhill from there.
9991 //
9992 // For AArch64, the [sz]ext vector instructions can only go up one element
9993 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9994 // take two instructions.
9995 //
9996 // This implies that the most efficient way to do the extend from v8i8
9997 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9998 // the normal splitting to happen for the v8i16->v8i32.
9999
10000 // This is pre-legalization to catch some cases where the default
10001 // type legalization will create ill-tempered code.
10002 if (!DCI.isBeforeLegalizeOps())
10003 return SDValue();
10004
10005 // We're only interested in cleaning things up for non-legal vector types
10006 // here. If both the source and destination are legal, things will just
10007 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +000010008 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +000010009 EVT ResVT = N->getValueType(0);
10010 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10011 return SDValue();
10012 // If the vector type isn't a simple VT, it's beyond the scope of what
10013 // we're worried about here. Let legalization do its thing and hope for
10014 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +000010015 SDValue Src = N->getOperand(0);
10016 EVT SrcVT = Src->getValueType(0);
10017 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +000010018 return SDValue();
10019
Tim Northover3b0846e2014-05-24 12:50:23 +000010020 // If the source VT is a 64-bit vector, we can play games and get the
10021 // better results we want.
10022 if (SrcVT.getSizeInBits() != 64)
10023 return SDValue();
10024
Sanjay Patel1ed771f2016-09-14 16:37:15 +000010025 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +000010026 unsigned ElementCount = SrcVT.getVectorNumElements();
10027 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10028 SDLoc DL(N);
10029 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10030
10031 // Now split the rest of the operation into two halves, each with a 64
10032 // bit source.
10033 EVT LoVT, HiVT;
10034 SDValue Lo, Hi;
10035 unsigned NumElements = ResVT.getVectorNumElements();
10036 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10037 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10038 ResVT.getVectorElementType(), NumElements / 2);
10039
10040 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10041 LoVT.getVectorNumElements());
10042 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010043 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010044 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010045 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010046 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10047 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10048
10049 // Now combine the parts back together so we still have a single result
10050 // like the combiner expects.
10051 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10052}
10053
Geoff Berry8301c642016-11-16 19:35:19 +000010054static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10055 SDValue SplatVal, unsigned NumVecElts) {
Tim Northover964eea72019-01-08 13:30:27 +000010056 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010057 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +000010058 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010059
10060 // Create scalar stores. This is at least as good as the code sequence for a
10061 // split unaligned store which is a dup.s, ext.b, and two stores.
10062 // Most of the time the three stores should be replaced by store pair
10063 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010064 SDLoc DL(&St);
10065 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010066 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +000010067
John Brawn3a9c8422017-02-06 18:07:20 +000010068 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010069 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +000010070 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +000010071 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010072
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010073 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +000010074 if (BasePtr->getOpcode() == ISD::ADD &&
10075 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10076 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10077 BasePtr = BasePtr->getOperand(0);
10078 }
10079
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010080 unsigned Offset = EltOffset;
10081 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +000010082 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +000010083 SDValue OffsetPtr =
10084 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10085 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010086 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +000010087 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010088 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +000010089 Offset += EltOffset;
10090 }
10091 return NewST1;
10092}
10093
Geoff Berry526c5052016-11-14 19:39:04 +000010094/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10095/// load store optimizer pass will merge them to store pair stores. This should
10096/// be better than a movi to create the vector zero followed by a vector store
10097/// if the zero constant is not re-used, since one instructions and one register
10098/// live range will be removed.
10099///
10100/// For example, the final generated code should be:
10101///
10102/// stp xzr, xzr, [x0]
10103///
10104/// instead of:
10105///
10106/// movi v0.2d, #0
10107/// str q0, [x0]
10108///
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010109static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10110 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +000010111 EVT VT = StVal.getValueType();
10112
Geoff Berry8301c642016-11-16 19:35:19 +000010113 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10114 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +000010115 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +000010116 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10117 VT.getVectorElementType().getSizeInBits() == 64) ||
10118 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10119 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +000010120 return SDValue();
10121
10122 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10123 return SDValue();
10124
10125 // If the zero constant has more than one use then the vector store could be
10126 // better since the constant mov will be amortized and stp q instructions
10127 // should be able to be formed.
10128 if (!StVal.hasOneUse())
10129 return SDValue();
10130
Tim Northover964eea72019-01-08 13:30:27 +000010131 // If the store is truncating then it's going down to i16 or smaller, which
10132 // means it can be implemented in a single store anyway.
10133 if (St.isTruncatingStore())
10134 return SDValue();
10135
Geoff Berry526c5052016-11-14 19:39:04 +000010136 // If the immediate offset of the address operand is too large for the stp
10137 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010138 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10139 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +000010140 if (Offset < -512 || Offset > 504)
10141 return SDValue();
10142 }
10143
10144 for (int I = 0; I < NumVecElts; ++I) {
10145 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +000010146 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +000010147 return SDValue();
10148 }
Geoff Berry8301c642016-11-16 19:35:19 +000010149
Geoff Berrybb23df92017-09-21 21:10:06 +000010150 // Use a CopyFromReg WZR/XZR here to prevent
10151 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10152 SDLoc DL(&St);
10153 unsigned ZeroReg;
10154 EVT ZeroVT;
10155 if (VT.getVectorElementType().getSizeInBits() == 32) {
10156 ZeroReg = AArch64::WZR;
10157 ZeroVT = MVT::i32;
10158 } else {
10159 ZeroReg = AArch64::XZR;
10160 ZeroVT = MVT::i64;
10161 }
10162 SDValue SplatVal =
10163 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +000010164 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +000010165}
10166
Tim Northover3b0846e2014-05-24 12:50:23 +000010167/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10168/// value. The load store optimizer pass will merge them to store pair stores.
10169/// This has better performance than a splat of the scalar followed by a split
10170/// vector store. Even if the stores are not merged it is four stores vs a dup,
10171/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010172static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10173 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010174 EVT VT = StVal.getValueType();
10175
10176 // Don't replace floating point stores, they possibly won't be transformed to
10177 // stp because of the store pair suppress pass.
10178 if (VT.isFloatingPoint())
10179 return SDValue();
10180
Tim Northover3b0846e2014-05-24 12:50:23 +000010181 // We can express a splat as store pair(s) for 2 or 4 elements.
10182 unsigned NumVecElts = VT.getVectorNumElements();
10183 if (NumVecElts != 4 && NumVecElts != 2)
10184 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010185
Tim Northover964eea72019-01-08 13:30:27 +000010186 // If the store is truncating then it's going down to i16 or smaller, which
10187 // means it can be implemented in a single store anyway.
10188 if (St.isTruncatingStore())
10189 return SDValue();
10190
Tim Northover3b0846e2014-05-24 12:50:23 +000010191 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +000010192 // Make sure that each of the relevant vector element locations are inserted
10193 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10194 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10195 SDValue SplatVal;
10196 for (unsigned I = 0; I < NumVecElts; ++I) {
10197 // Check for insert vector elements.
10198 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +000010199 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010200
10201 // Check that same value is inserted at each vector element.
10202 if (I == 0)
10203 SplatVal = StVal.getOperand(1);
10204 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +000010205 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +000010206
10207 // Check insert element index.
10208 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10209 if (!CIndex)
10210 return SDValue();
10211 uint64_t IndexVal = CIndex->getZExtValue();
10212 if (IndexVal >= NumVecElts)
10213 return SDValue();
10214 IndexNotInserted.reset(IndexVal);
10215
10216 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010217 }
Geoff Berry25fa4992016-11-11 19:25:20 +000010218 // Check that all vector element locations were inserted to.
10219 if (IndexNotInserted.any())
10220 return SDValue();
10221
Geoff Berry8301c642016-11-16 19:35:19 +000010222 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010223}
10224
Geoff Berry8301c642016-11-16 19:35:19 +000010225static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10226 SelectionDAG &DAG,
10227 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +000010228
10229 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +000010230 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +000010231 return SDValue();
10232
Geoff Berry526c5052016-11-14 19:39:04 +000010233 SDValue StVal = S->getValue();
10234 EVT VT = StVal.getValueType();
10235 if (!VT.isVector())
10236 return SDValue();
10237
10238 // If we get a splat of zeros, convert this vector store to a store of
10239 // scalars. They will be merged into store pairs of xzr thereby removing one
10240 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010241 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +000010242 return ReplacedZeroSplat;
10243
Sanjay Patelbbbf9a12015-09-25 21:49:48 +000010244 // FIXME: The logic for deciding if an unaligned store should be split should
10245 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10246 // a call to that function here.
10247
Matthias Braun651cff42016-06-02 18:03:53 +000010248 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +000010249 return SDValue();
10250
Sanjay Patel924879a2015-08-04 15:49:57 +000010251 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +000010252 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +000010253 return SDValue();
10254
Tim Northover3b0846e2014-05-24 12:50:23 +000010255 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10256 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +000010257 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +000010258 return SDValue();
10259
10260 // Split unaligned 16B stores. They are terrible for performance.
10261 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10262 // extensions can use this to mark that it does not want splitting to happen
10263 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10264 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10265 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10266 S->getAlignment() <= 2)
10267 return SDValue();
10268
10269 // If we get a splat of a scalar convert this vector store to a store of
10270 // scalars. They will be merged into store pairs thereby removing two
10271 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +000010272 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +000010273 return ReplacedSplat;
10274
10275 SDLoc DL(S);
10276 unsigned NumElts = VT.getVectorNumElements() / 2;
10277 // Split VT into two.
10278 EVT HalfVT =
10279 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10280 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010281 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010282 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010283 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010284 SDValue BasePtr = S->getBasePtr();
10285 SDValue NewST1 =
10286 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +000010287 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010288 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010289 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +000010290 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +000010291 S->getPointerInfo(), S->getAlignment(),
10292 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +000010293}
10294
10295/// Target-specific DAG combine function for post-increment LD1 (lane) and
10296/// post-increment LD1R.
10297static SDValue performPostLD1Combine(SDNode *N,
10298 TargetLowering::DAGCombinerInfo &DCI,
10299 bool IsLaneOp) {
10300 if (DCI.isBeforeLegalizeOps())
10301 return SDValue();
10302
10303 SelectionDAG &DAG = DCI.DAG;
10304 EVT VT = N->getValueType(0);
10305
10306 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10307 SDNode *LD = N->getOperand(LoadIdx).getNode();
10308 // If it is not LOAD, can not do such combine.
10309 if (LD->getOpcode() != ISD::LOAD)
10310 return SDValue();
10311
Geoff Berry60460262018-05-11 16:25:06 +000010312 // The vector lane must be a constant in the LD1LANE opcode.
10313 SDValue Lane;
10314 if (IsLaneOp) {
10315 Lane = N->getOperand(2);
10316 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10317 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10318 return SDValue();
10319 }
10320
Tim Northover3b0846e2014-05-24 12:50:23 +000010321 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10322 EVT MemVT = LoadSDN->getMemoryVT();
10323 // Check if memory operand is the same type as the vector element.
10324 if (MemVT != VT.getVectorElementType())
10325 return SDValue();
10326
10327 // Check if there are other uses. If so, do not combine as it will introduce
10328 // an extra load.
10329 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10330 ++UI) {
10331 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10332 continue;
10333 if (*UI != N)
10334 return SDValue();
10335 }
10336
10337 SDValue Addr = LD->getOperand(1);
10338 SDValue Vector = N->getOperand(0);
10339 // Search for a use of the address operand that is an increment.
10340 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10341 Addr.getNode()->use_end(); UI != UE; ++UI) {
10342 SDNode *User = *UI;
10343 if (User->getOpcode() != ISD::ADD
10344 || UI.getUse().getResNo() != Addr.getResNo())
10345 continue;
10346
Tim Northover3b0846e2014-05-24 12:50:23 +000010347 // If the increment is a constant, it must match the memory ref size.
10348 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10349 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10350 uint32_t IncVal = CInc->getZExtValue();
10351 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10352 if (IncVal != NumBytes)
10353 continue;
10354 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10355 }
10356
Nirav Davee40e2bb2018-09-25 15:30:22 +000010357 // To avoid cycle construction make sure that neither the load nor the add
10358 // are predecessors to each other or the Vector.
10359 SmallPtrSet<const SDNode *, 32> Visited;
10360 SmallVector<const SDNode *, 16> Worklist;
10361 Visited.insert(N);
10362 Worklist.push_back(User);
10363 Worklist.push_back(LD);
10364 Worklist.push_back(Vector.getNode());
10365 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10366 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Ahmed Bougacha2448ef52015-04-17 21:02:30 +000010367 continue;
10368
Tim Northover3b0846e2014-05-24 12:50:23 +000010369 SmallVector<SDValue, 8> Ops;
10370 Ops.push_back(LD->getOperand(0)); // Chain
10371 if (IsLaneOp) {
10372 Ops.push_back(Vector); // The vector to be inserted
Geoff Berry60460262018-05-11 16:25:06 +000010373 Ops.push_back(Lane); // The lane to be inserted in the vector
Tim Northover3b0846e2014-05-24 12:50:23 +000010374 }
10375 Ops.push_back(Addr);
10376 Ops.push_back(Inc);
10377
10378 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +000010379 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010380 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10381 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10382 MemVT,
10383 LoadSDN->getMemOperand());
10384
10385 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +000010386 SDValue NewResults[] = {
10387 SDValue(LD, 0), // The result of load
10388 SDValue(UpdN.getNode(), 2) // Chain
10389 };
Tim Northover3b0846e2014-05-24 12:50:23 +000010390 DCI.CombineTo(LD, NewResults);
10391 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10392 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10393
10394 break;
10395 }
10396 return SDValue();
10397}
10398
Joel Jones7466ccf2017-07-10 22:11:50 +000010399/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +000010400/// address translation.
10401static bool performTBISimplification(SDValue Addr,
10402 TargetLowering::DAGCombinerInfo &DCI,
10403 SelectionDAG &DAG) {
10404 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +000010405 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +000010406 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10407 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +000010408 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +000010409 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +000010410 DCI.CommitTargetLoweringOpt(TLO);
10411 return true;
10412 }
10413 return false;
10414}
10415
10416static SDValue performSTORECombine(SDNode *N,
10417 TargetLowering::DAGCombinerInfo &DCI,
10418 SelectionDAG &DAG,
10419 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +000010420 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +000010421 return Split;
10422
10423 if (Subtarget->supportsAddressTopByteIgnored() &&
10424 performTBISimplification(N->getOperand(2), DCI, DAG))
10425 return SDValue(N, 0);
10426
10427 return SDValue();
10428}
10429
Chad Rosier6c36eff2015-09-03 18:13:57 +000010430
Tim Northover3b0846e2014-05-24 12:50:23 +000010431/// Target-specific DAG combine function for NEON load/store intrinsics
10432/// to merge base address updates.
10433static SDValue performNEONPostLDSTCombine(SDNode *N,
10434 TargetLowering::DAGCombinerInfo &DCI,
10435 SelectionDAG &DAG) {
10436 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10437 return SDValue();
10438
10439 unsigned AddrOpIdx = N->getNumOperands() - 1;
10440 SDValue Addr = N->getOperand(AddrOpIdx);
10441
10442 // Search for a use of the address operand that is an increment.
10443 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10444 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10445 SDNode *User = *UI;
10446 if (User->getOpcode() != ISD::ADD ||
10447 UI.getUse().getResNo() != Addr.getResNo())
10448 continue;
10449
10450 // Check that the add is independent of the load/store. Otherwise, folding
10451 // it would create a cycle.
Nirav Davee40e2bb2018-09-25 15:30:22 +000010452 SmallPtrSet<const SDNode *, 32> Visited;
10453 SmallVector<const SDNode *, 16> Worklist;
10454 Visited.insert(Addr.getNode());
10455 Worklist.push_back(N);
10456 Worklist.push_back(User);
10457 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10458 SDNode::hasPredecessorHelper(User, Visited, Worklist))
Tim Northover3b0846e2014-05-24 12:50:23 +000010459 continue;
10460
10461 // Find the new opcode for the updating load/store.
10462 bool IsStore = false;
10463 bool IsLaneOp = false;
10464 bool IsDupOp = false;
10465 unsigned NewOpc = 0;
10466 unsigned NumVecs = 0;
10467 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10468 switch (IntNo) {
10469 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10470 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10471 NumVecs = 2; break;
10472 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10473 NumVecs = 3; break;
10474 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10475 NumVecs = 4; break;
10476 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10477 NumVecs = 2; IsStore = true; break;
10478 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10479 NumVecs = 3; IsStore = true; break;
10480 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10481 NumVecs = 4; IsStore = true; break;
10482 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10483 NumVecs = 2; break;
10484 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10485 NumVecs = 3; break;
10486 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10487 NumVecs = 4; break;
10488 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10489 NumVecs = 2; IsStore = true; break;
10490 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10491 NumVecs = 3; IsStore = true; break;
10492 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10493 NumVecs = 4; IsStore = true; break;
10494 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10495 NumVecs = 2; IsDupOp = true; break;
10496 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10497 NumVecs = 3; IsDupOp = true; break;
10498 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10499 NumVecs = 4; IsDupOp = true; break;
10500 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10501 NumVecs = 2; IsLaneOp = true; break;
10502 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10503 NumVecs = 3; IsLaneOp = true; break;
10504 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10505 NumVecs = 4; IsLaneOp = true; break;
10506 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10507 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10508 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10509 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10510 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10511 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10512 }
10513
10514 EVT VecTy;
10515 if (IsStore)
10516 VecTy = N->getOperand(2).getValueType();
10517 else
10518 VecTy = N->getValueType(0);
10519
10520 // If the increment is a constant, it must match the memory ref size.
10521 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10522 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10523 uint32_t IncVal = CInc->getZExtValue();
10524 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10525 if (IsLaneOp || IsDupOp)
10526 NumBytes /= VecTy.getVectorNumElements();
10527 if (IncVal != NumBytes)
10528 continue;
10529 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10530 }
10531 SmallVector<SDValue, 8> Ops;
10532 Ops.push_back(N->getOperand(0)); // Incoming chain
10533 // Load lane and store have vector list as input.
10534 if (IsLaneOp || IsStore)
10535 for (unsigned i = 2; i < AddrOpIdx; ++i)
10536 Ops.push_back(N->getOperand(i));
10537 Ops.push_back(Addr); // Base register
10538 Ops.push_back(Inc);
10539
10540 // Return Types.
10541 EVT Tys[6];
10542 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10543 unsigned n;
10544 for (n = 0; n < NumResultVecs; ++n)
10545 Tys[n] = VecTy;
10546 Tys[n++] = MVT::i64; // Type of write back register
10547 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +000010548 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +000010549
10550 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10551 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10552 MemInt->getMemoryVT(),
10553 MemInt->getMemOperand());
10554
10555 // Update the uses.
10556 std::vector<SDValue> NewResults;
10557 for (unsigned i = 0; i < NumResultVecs; ++i) {
10558 NewResults.push_back(SDValue(UpdN.getNode(), i));
10559 }
10560 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10561 DCI.CombineTo(N, NewResults);
10562 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10563
10564 break;
10565 }
10566 return SDValue();
10567}
10568
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010569// Checks to see if the value is the prescribed width and returns information
10570// about its extension mode.
10571static
10572bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10573 ExtType = ISD::NON_EXTLOAD;
10574 switch(V.getNode()->getOpcode()) {
10575 default:
10576 return false;
10577 case ISD::LOAD: {
10578 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10579 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10580 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10581 ExtType = LoadNode->getExtensionType();
10582 return true;
10583 }
10584 return false;
10585 }
10586 case ISD::AssertSext: {
10587 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10588 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10589 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10590 ExtType = ISD::SEXTLOAD;
10591 return true;
10592 }
10593 return false;
10594 }
10595 case ISD::AssertZext: {
10596 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10597 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10598 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10599 ExtType = ISD::ZEXTLOAD;
10600 return true;
10601 }
10602 return false;
10603 }
10604 case ISD::Constant:
10605 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010606 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10607 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010608 }
10609 }
10610
10611 return true;
10612}
10613
10614// This function does a whole lot of voodoo to determine if the tests are
10615// equivalent without and with a mask. Essentially what happens is that given a
10616// DAG resembling:
10617//
10618// +-------------+ +-------------+ +-------------+ +-------------+
10619// | Input | | AddConstant | | CompConstant| | CC |
10620// +-------------+ +-------------+ +-------------+ +-------------+
10621// | | | |
10622// V V | +----------+
10623// +-------------+ +----+ | |
10624// | ADD | |0xff| | |
10625// +-------------+ +----+ | |
10626// | | | |
10627// V V | |
10628// +-------------+ | |
10629// | AND | | |
10630// +-------------+ | |
10631// | | |
10632// +-----+ | |
10633// | | |
10634// V V V
10635// +-------------+
10636// | CMP |
10637// +-------------+
10638//
10639// The AND node may be safely removed for some combinations of inputs. In
10640// particular we need to take into account the extension type of the Input,
10641// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10642// width of the input (this can work for any width inputs, the above graph is
10643// specific to 8 bits.
10644//
10645// The specific equations were worked out by generating output tables for each
10646// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10647// problem was simplified by working with 4 bit inputs, which means we only
10648// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10649// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10650// patterns present in both extensions (0,7). For every distinct set of
10651// AddConstant and CompConstants bit patterns we can consider the masked and
10652// unmasked versions to be equivalent if the result of this function is true for
10653// all 16 distinct bit patterns of for the current extension type of Input (w0).
10654//
10655// sub w8, w0, w1
10656// and w10, w8, #0x0f
10657// cmp w8, w2
10658// cset w9, AArch64CC
10659// cmp w10, w2
10660// cset w11, AArch64CC
10661// cmp w9, w11
10662// cset w0, eq
10663// ret
10664//
10665// Since the above function shows when the outputs are equivalent it defines
10666// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10667// would be expensive to run during compiles. The equations below were written
10668// in a test harness that confirmed they gave equivalent outputs to the above
10669// for all inputs function, so they can be used determine if the removal is
10670// legal instead.
10671//
10672// isEquivalentMaskless() is the code for testing if the AND can be removed
10673// factored out of the DAG recognition as the DAG can take several forms.
10674
David Majnemere61e4bf2016-06-21 05:10:24 +000010675static bool isEquivalentMaskless(unsigned CC, unsigned width,
10676 ISD::LoadExtType ExtType, int AddConstant,
10677 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010678 // By being careful about our equations and only writing the in term
10679 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10680 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010681 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010682
10683 // For the purposes of these comparisons sign extending the type is
10684 // equivalent to zero extending the add and displacing it by half the integer
10685 // width. Provided we are careful and make sure our equations are valid over
10686 // the whole range we can just adjust the input and avoid writing equations
10687 // for sign extended inputs.
10688 if (ExtType == ISD::SEXTLOAD)
10689 AddConstant -= (1 << (width-1));
10690
10691 switch(CC) {
10692 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010693 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010694 if ((AddConstant == 0) ||
10695 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10696 (AddConstant >= 0 && CompConstant < 0) ||
10697 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10698 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010699 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010700 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010701 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010702 if ((AddConstant == 0) ||
10703 (AddConstant >= 0 && CompConstant <= 0) ||
10704 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10705 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010706 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010707 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010708 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010709 if ((AddConstant >= 0 && CompConstant < 0) ||
10710 (AddConstant <= 0 && CompConstant >= -1 &&
10711 CompConstant < AddConstant + MaxUInt))
10712 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010713 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010714 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010715 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010716 if ((AddConstant == 0) ||
10717 (AddConstant > 0 && CompConstant <= 0) ||
10718 (AddConstant < 0 && CompConstant <= AddConstant))
10719 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010720 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010721 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010722 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010723 if ((AddConstant >= 0 && CompConstant <= 0) ||
10724 (AddConstant <= 0 && CompConstant >= 0 &&
10725 CompConstant <= AddConstant + MaxUInt))
10726 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010727 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010728 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010729 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010730 if ((AddConstant > 0 && CompConstant < 0) ||
10731 (AddConstant < 0 && CompConstant >= 0 &&
10732 CompConstant < AddConstant + MaxUInt) ||
10733 (AddConstant >= 0 && CompConstant >= 0 &&
10734 CompConstant >= AddConstant) ||
10735 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010736 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010737 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010738 case AArch64CC::VS:
10739 case AArch64CC::VC:
10740 case AArch64CC::AL:
10741 case AArch64CC::NV:
10742 return true;
10743 case AArch64CC::Invalid:
10744 break;
10745 }
10746
10747 return false;
10748}
10749
10750static
10751SDValue performCONDCombine(SDNode *N,
10752 TargetLowering::DAGCombinerInfo &DCI,
10753 SelectionDAG &DAG, unsigned CCIndex,
10754 unsigned CmpIndex) {
10755 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10756 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10757 unsigned CondOpcode = SubsNode->getOpcode();
10758
10759 if (CondOpcode != AArch64ISD::SUBS)
10760 return SDValue();
10761
10762 // There is a SUBS feeding this condition. Is it fed by a mask we can
10763 // use?
10764
10765 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10766 unsigned MaskBits = 0;
10767
10768 if (AndNode->getOpcode() != ISD::AND)
10769 return SDValue();
10770
10771 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10772 uint32_t CNV = CN->getZExtValue();
10773 if (CNV == 255)
10774 MaskBits = 8;
10775 else if (CNV == 65535)
10776 MaskBits = 16;
10777 }
10778
10779 if (!MaskBits)
10780 return SDValue();
10781
10782 SDValue AddValue = AndNode->getOperand(0);
10783
10784 if (AddValue.getOpcode() != ISD::ADD)
10785 return SDValue();
10786
10787 // The basic dag structure is correct, grab the inputs and validate them.
10788
10789 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10790 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10791 SDValue SubsInputValue = SubsNode->getOperand(1);
10792
10793 // The mask is present and the provenance of all the values is a smaller type,
10794 // lets see if the mask is superfluous.
10795
10796 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10797 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10798 return SDValue();
10799
10800 ISD::LoadExtType ExtType;
10801
10802 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10803 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10804 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10805 return SDValue();
10806
10807 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10808 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10809 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10810 return SDValue();
10811
10812 // The AND is not necessary, remove it.
10813
10814 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10815 SubsNode->getValueType(1));
10816 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10817
10818 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10819 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10820
10821 return SDValue(N, 0);
10822}
10823
Tim Northover3b0846e2014-05-24 12:50:23 +000010824// Optimize compare with zero and branch.
10825static SDValue performBRCONDCombine(SDNode *N,
10826 TargetLowering::DAGCombinerInfo &DCI,
10827 SelectionDAG &DAG) {
Kristof Beylse66bc1f2018-12-18 08:50:02 +000010828 MachineFunction &MF = DAG.getMachineFunction();
10829 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
10830 // will not be produced, as they are conditional branch instructions that do
10831 // not set flags.
10832 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
10833 return SDValue();
10834
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010835 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010836 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010837 SDValue Chain = N->getOperand(0);
10838 SDValue Dest = N->getOperand(1);
10839 SDValue CCVal = N->getOperand(2);
10840 SDValue Cmp = N->getOperand(3);
10841
10842 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10843 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10844 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10845 return SDValue();
10846
10847 unsigned CmpOpc = Cmp.getOpcode();
10848 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10849 return SDValue();
10850
10851 // Only attempt folding if there is only one use of the flag and no use of the
10852 // value.
10853 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10854 return SDValue();
10855
10856 SDValue LHS = Cmp.getOperand(0);
10857 SDValue RHS = Cmp.getOperand(1);
10858
10859 assert(LHS.getValueType() == RHS.getValueType() &&
10860 "Expected the value type to be the same for both operands!");
10861 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10862 return SDValue();
10863
Artyom Skrobov314ee042015-11-25 19:41:11 +000010864 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010865 std::swap(LHS, RHS);
10866
Artyom Skrobov314ee042015-11-25 19:41:11 +000010867 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010868 return SDValue();
10869
10870 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10871 LHS.getOpcode() == ISD::SRL)
10872 return SDValue();
10873
10874 // Fold the compare into the branch instruction.
10875 SDValue BR;
10876 if (CC == AArch64CC::EQ)
10877 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10878 else
10879 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10880
10881 // Do not add new nodes to DAG combiner worklist.
10882 DCI.CombineTo(N, BR, false);
10883
10884 return SDValue();
10885}
10886
Geoff Berry9e934b02016-01-04 18:55:47 +000010887// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10888// as well as whether the test should be inverted. This code is required to
10889// catch these cases (as opposed to standard dag combines) because
10890// AArch64ISD::TBZ is matched during legalization.
10891static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10892 SelectionDAG &DAG) {
10893
10894 if (!Op->hasOneUse())
10895 return Op;
10896
10897 // We don't handle undef/constant-fold cases below, as they should have
10898 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10899 // etc.)
10900
10901 // (tbz (trunc x), b) -> (tbz x, b)
10902 // This case is just here to enable more of the below cases to be caught.
10903 if (Op->getOpcode() == ISD::TRUNCATE &&
10904 Bit < Op->getValueType(0).getSizeInBits()) {
10905 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10906 }
10907
10908 if (Op->getNumOperands() != 2)
10909 return Op;
10910
10911 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10912 if (!C)
10913 return Op;
10914
10915 switch (Op->getOpcode()) {
10916 default:
10917 return Op;
10918
10919 // (tbz (and x, m), b) -> (tbz x, b)
10920 case ISD::AND:
10921 if ((C->getZExtValue() >> Bit) & 1)
10922 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10923 return Op;
10924
10925 // (tbz (shl x, c), b) -> (tbz x, b-c)
10926 case ISD::SHL:
10927 if (C->getZExtValue() <= Bit &&
10928 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10929 Bit = Bit - C->getZExtValue();
10930 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10931 }
10932 return Op;
10933
10934 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10935 case ISD::SRA:
10936 Bit = Bit + C->getZExtValue();
10937 if (Bit >= Op->getValueType(0).getSizeInBits())
10938 Bit = Op->getValueType(0).getSizeInBits() - 1;
10939 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10940
10941 // (tbz (srl x, c), b) -> (tbz x, b+c)
10942 case ISD::SRL:
10943 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10944 Bit = Bit + C->getZExtValue();
10945 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10946 }
10947 return Op;
10948
10949 // (tbz (xor x, -1), b) -> (tbnz x, b)
10950 case ISD::XOR:
10951 if ((C->getZExtValue() >> Bit) & 1)
10952 Invert = !Invert;
10953 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10954 }
10955}
10956
10957// Optimize test single bit zero/non-zero and branch.
10958static SDValue performTBZCombine(SDNode *N,
10959 TargetLowering::DAGCombinerInfo &DCI,
10960 SelectionDAG &DAG) {
10961 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10962 bool Invert = false;
10963 SDValue TestSrc = N->getOperand(1);
10964 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10965
10966 if (TestSrc == NewTestSrc)
10967 return SDValue();
10968
10969 unsigned NewOpc = N->getOpcode();
10970 if (Invert) {
10971 if (NewOpc == AArch64ISD::TBZ)
10972 NewOpc = AArch64ISD::TBNZ;
10973 else {
10974 assert(NewOpc == AArch64ISD::TBNZ);
10975 NewOpc = AArch64ISD::TBZ;
10976 }
10977 }
10978
10979 SDLoc DL(N);
10980 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10981 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10982}
10983
Tim Northover3b0846e2014-05-24 12:50:23 +000010984// vselect (v1i1 setcc) ->
10985// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10986// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10987// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10988// such VSELECT.
10989static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10990 SDValue N0 = N->getOperand(0);
10991 EVT CCVT = N0.getValueType();
10992
10993 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10994 CCVT.getVectorElementType() != MVT::i1)
10995 return SDValue();
10996
10997 EVT ResVT = N->getValueType(0);
10998 EVT CmpVT = N0.getOperand(0).getValueType();
10999 // Only combine when the result type is of the same size as the compared
11000 // operands.
11001 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11002 return SDValue();
11003
11004 SDValue IfTrue = N->getOperand(1);
11005 SDValue IfFalse = N->getOperand(2);
11006 SDValue SetCC =
11007 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11008 N0.getOperand(0), N0.getOperand(1),
11009 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11010 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11011 IfTrue, IfFalse);
11012}
11013
11014/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11015/// the compare-mask instructions rather than going via NZCV, even if LHS and
11016/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11017/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000011018static SDValue performSelectCombine(SDNode *N,
11019 TargetLowering::DAGCombinerInfo &DCI) {
11020 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000011021 SDValue N0 = N->getOperand(0);
11022 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000011023
Ahmed Bougachac004c602015-04-27 21:43:12 +000011024 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000011025 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000011026
Ahmed Bougachac004c602015-04-27 21:43:12 +000011027 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11028 // scalar SetCCResultType. We also don't expect vectors, because we assume
11029 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11030 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11031 "Scalar-SETCC feeding SELECT has unexpected result type!");
11032
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011033 // If NumMaskElts == 0, the comparison is larger than select result. The
11034 // largest real NEON comparison is 64-bits per lane, which means the result is
11035 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000011036 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000011037
11038 // Don't try to do this optimization when the setcc itself has i1 operands.
11039 // There are no legal vectors of i1, so this would be pointless.
11040 if (SrcVT == MVT::i1)
11041 return SDValue();
11042
Tim Northover3c0915e2014-08-29 15:34:58 +000011043 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011044 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000011045 return SDValue();
11046
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011047 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000011048 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11049
Ahmed Bougacha89bba612015-04-27 21:01:20 +000011050 // Also bail out if the vector CCVT isn't the same size as ResVT.
11051 // This can happen if the SETCC operand size doesn't divide the ResVT size
11052 // (e.g., f64 vs v3f32).
11053 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11054 return SDValue();
11055
Ahmed Bougachac004c602015-04-27 21:43:12 +000011056 // Make sure we didn't create illegal types, if we're not supposed to.
11057 assert(DCI.isBeforeLegalize() ||
11058 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11059
Tim Northover3b0846e2014-05-24 12:50:23 +000011060 // First perform a vector comparison, where lane 0 is the one we're interested
11061 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011062 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000011063 SDValue LHS =
11064 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11065 SDValue RHS =
11066 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11067 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11068
11069 // Now duplicate the comparison mask we want across all other lanes.
11070 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000011071 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000011072 Mask = DAG.getNode(ISD::BITCAST, DL,
11073 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000011074
11075 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11076}
11077
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011078/// Get rid of unnecessary NVCASTs (that don't change the type).
11079static SDValue performNVCASTCombine(SDNode *N) {
11080 if (N->getValueType(0) == N->getOperand(0).getValueType())
11081 return N->getOperand(0);
11082
11083 return SDValue();
11084}
11085
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011086// If all users of the globaladdr are of the form (globaladdr + constant), find
11087// the smallest constant, fold it into the globaladdr's offset and rewrite the
11088// globaladdr as (globaladdr + constant) - constant.
11089static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11090 const AArch64Subtarget *Subtarget,
11091 const TargetMachine &TM) {
Reid Klecknereb568942018-11-01 18:02:27 +000011092 auto *GN = cast<GlobalAddressSDNode>(N);
11093 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11094 AArch64II::MO_NO_FLAG)
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011095 return SDValue();
11096
11097 uint64_t MinOffset = -1ull;
11098 for (SDNode *N : GN->uses()) {
11099 if (N->getOpcode() != ISD::ADD)
11100 return SDValue();
11101 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11102 if (!C)
11103 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11104 if (!C)
11105 return SDValue();
11106 MinOffset = std::min(MinOffset, C->getZExtValue());
11107 }
11108 uint64_t Offset = MinOffset + GN->getOffset();
11109
11110 // Require that the new offset is larger than the existing one. Otherwise, we
11111 // can end up oscillating between two possible DAGs, for example,
11112 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11113 if (Offset <= uint64_t(GN->getOffset()))
11114 return SDValue();
11115
11116 // Check whether folding this offset is legal. It must not go out of bounds of
11117 // the referenced object to avoid violating the code model, and must be
11118 // smaller than 2^21 because this is the largest offset expressible in all
11119 // object formats.
11120 //
11121 // This check also prevents us from folding negative offsets, which will end
11122 // up being treated in the same way as large positive ones. They could also
11123 // cause code model violations, and aren't really common enough to matter.
11124 if (Offset >= (1 << 21))
11125 return SDValue();
11126
11127 const GlobalValue *GV = GN->getGlobal();
11128 Type *T = GV->getValueType();
11129 if (!T->isSized() ||
11130 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11131 return SDValue();
11132
11133 SDLoc DL(GN);
11134 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11135 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11136 DAG.getConstant(MinOffset, DL, MVT::i64));
11137}
11138
Tim Northover3b0846e2014-05-24 12:50:23 +000011139SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11140 DAGCombinerInfo &DCI) const {
11141 SelectionDAG &DAG = DCI.DAG;
11142 switch (N->getOpcode()) {
11143 default:
Nicola Zaghend34e60c2018-05-14 12:53:11 +000011144 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000011145 break;
11146 case ISD::ADD:
11147 case ISD::SUB:
11148 return performAddSubLongCombine(N, DCI, DAG);
11149 case ISD::XOR:
11150 return performXorCombine(N, DAG, DCI, Subtarget);
11151 case ISD::MUL:
11152 return performMulCombine(N, DAG, DCI, Subtarget);
11153 case ISD::SINT_TO_FP:
11154 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000011155 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000011156 case ISD::FP_TO_SINT:
11157 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000011158 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000011159 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000011160 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000011161 case ISD::OR:
11162 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000011163 case ISD::SRL:
11164 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011165 case ISD::INTRINSIC_WO_CHAIN:
11166 return performIntrinsicCombine(N, DCI, Subtarget);
11167 case ISD::ANY_EXTEND:
11168 case ISD::ZERO_EXTEND:
11169 case ISD::SIGN_EXTEND:
11170 return performExtendCombine(N, DCI, DAG);
11171 case ISD::BITCAST:
11172 return performBitcastCombine(N, DCI, DAG);
11173 case ISD::CONCAT_VECTORS:
11174 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000011175 case ISD::SELECT:
11176 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000011177 case ISD::VSELECT:
11178 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000011179 case ISD::LOAD:
11180 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11181 return SDValue(N, 0);
11182 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000011183 case ISD::STORE:
11184 return performSTORECombine(N, DCI, DAG, Subtarget);
11185 case AArch64ISD::BRCOND:
11186 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000011187 case AArch64ISD::TBNZ:
11188 case AArch64ISD::TBZ:
11189 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000011190 case AArch64ISD::CSEL:
11191 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000011192 case AArch64ISD::DUP:
11193 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000011194 case AArch64ISD::NVCAST:
11195 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000011196 case ISD::INSERT_VECTOR_ELT:
11197 return performPostLD1Combine(N, DCI, true);
11198 case ISD::INTRINSIC_VOID:
11199 case ISD::INTRINSIC_W_CHAIN:
11200 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11201 case Intrinsic::aarch64_neon_ld2:
11202 case Intrinsic::aarch64_neon_ld3:
11203 case Intrinsic::aarch64_neon_ld4:
11204 case Intrinsic::aarch64_neon_ld1x2:
11205 case Intrinsic::aarch64_neon_ld1x3:
11206 case Intrinsic::aarch64_neon_ld1x4:
11207 case Intrinsic::aarch64_neon_ld2lane:
11208 case Intrinsic::aarch64_neon_ld3lane:
11209 case Intrinsic::aarch64_neon_ld4lane:
11210 case Intrinsic::aarch64_neon_ld2r:
11211 case Intrinsic::aarch64_neon_ld3r:
11212 case Intrinsic::aarch64_neon_ld4r:
11213 case Intrinsic::aarch64_neon_st2:
11214 case Intrinsic::aarch64_neon_st3:
11215 case Intrinsic::aarch64_neon_st4:
11216 case Intrinsic::aarch64_neon_st1x2:
11217 case Intrinsic::aarch64_neon_st1x3:
11218 case Intrinsic::aarch64_neon_st1x4:
11219 case Intrinsic::aarch64_neon_st2lane:
11220 case Intrinsic::aarch64_neon_st3lane:
11221 case Intrinsic::aarch64_neon_st4lane:
11222 return performNEONPostLDSTCombine(N, DCI, DAG);
11223 default:
11224 break;
11225 }
Reid Klecknereb568942018-11-01 18:02:27 +000011226 break;
Peter Collingbourne5ab4a472018-04-23 19:09:34 +000011227 case ISD::GlobalAddress:
11228 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
Tim Northover3b0846e2014-05-24 12:50:23 +000011229 }
11230 return SDValue();
11231}
11232
11233// Check if the return value is used as only a return value, as otherwise
11234// we can't perform a tail-call. In particular, we need to check for
11235// target ISD nodes that are returns and any other "odd" constructs
11236// that the generic analysis code won't necessarily catch.
11237bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11238 SDValue &Chain) const {
11239 if (N->getNumValues() != 1)
11240 return false;
11241 if (!N->hasNUsesOfValue(1, 0))
11242 return false;
11243
11244 SDValue TCChain = Chain;
11245 SDNode *Copy = *N->use_begin();
11246 if (Copy->getOpcode() == ISD::CopyToReg) {
11247 // If the copy has a glue operand, we conservatively assume it isn't safe to
11248 // perform a tail call.
11249 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11250 MVT::Glue)
11251 return false;
11252 TCChain = Copy->getOperand(0);
11253 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11254 return false;
11255
11256 bool HasRet = false;
11257 for (SDNode *Node : Copy->uses()) {
11258 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11259 return false;
11260 HasRet = true;
11261 }
11262
11263 if (!HasRet)
11264 return false;
11265
11266 Chain = TCChain;
11267 return true;
11268}
11269
11270// Return whether the an instruction can potentially be optimized to a tail
11271// call. This will cause the optimizers to attempt to move, or duplicate,
11272// return instructions to help enable tail call optimizations for this
11273// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000011274bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000011275 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000011276}
11277
11278bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11279 SDValue &Offset,
11280 ISD::MemIndexedMode &AM,
11281 bool &IsInc,
11282 SelectionDAG &DAG) const {
11283 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11284 return false;
11285
11286 Base = Op->getOperand(0);
11287 // All of the indexed addressing mode instructions take a signed
11288 // 9 bit immediate offset.
11289 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000011290 int64_t RHSC = RHS->getSExtValue();
11291 if (Op->getOpcode() == ISD::SUB)
11292 RHSC = -(uint64_t)RHSC;
11293 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000011294 return false;
11295 IsInc = (Op->getOpcode() == ISD::ADD);
11296 Offset = Op->getOperand(1);
11297 return true;
11298 }
11299 return false;
11300}
11301
11302bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11303 SDValue &Offset,
11304 ISD::MemIndexedMode &AM,
11305 SelectionDAG &DAG) const {
11306 EVT VT;
11307 SDValue Ptr;
11308 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11309 VT = LD->getMemoryVT();
11310 Ptr = LD->getBasePtr();
11311 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11312 VT = ST->getMemoryVT();
11313 Ptr = ST->getBasePtr();
11314 } else
11315 return false;
11316
11317 bool IsInc;
11318 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11319 return false;
11320 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11321 return true;
11322}
11323
11324bool AArch64TargetLowering::getPostIndexedAddressParts(
11325 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11326 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11327 EVT VT;
11328 SDValue Ptr;
11329 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11330 VT = LD->getMemoryVT();
11331 Ptr = LD->getBasePtr();
11332 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11333 VT = ST->getMemoryVT();
11334 Ptr = ST->getBasePtr();
11335 } else
11336 return false;
11337
11338 bool IsInc;
11339 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11340 return false;
11341 // Post-indexing updates the base, so it's not a valid transform
11342 // if that's not the same as the load's pointer.
11343 if (Ptr != Base)
11344 return false;
11345 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11346 return true;
11347}
11348
Tim Northoverf8bfe212014-07-18 13:07:05 +000011349static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11350 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000011351 SDLoc DL(N);
11352 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000011353
11354 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11355 return;
11356
Tim Northoverf8bfe212014-07-18 13:07:05 +000011357 Op = SDValue(
11358 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11359 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011360 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000011361 0);
11362 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11363 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11364}
11365
Charlie Turner434d4592015-10-16 15:38:25 +000011366static void ReplaceReductionResults(SDNode *N,
11367 SmallVectorImpl<SDValue> &Results,
11368 SelectionDAG &DAG, unsigned InterOp,
11369 unsigned AcrossOp) {
11370 EVT LoVT, HiVT;
11371 SDValue Lo, Hi;
11372 SDLoc dl(N);
11373 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11374 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11375 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11376 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11377 Results.push_back(SplitVal);
11378}
11379
Tim Northover2f32e7f2016-08-04 19:32:28 +000011380static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11381 SDLoc DL(N);
11382 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11383 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11384 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11385 DAG.getConstant(64, DL, MVT::i64)));
11386 return std::make_pair(Lo, Hi);
11387}
11388
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011389// Create an even/odd pair of X registers holding integer value V.
11390static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11391 SDLoc dl(V.getNode());
11392 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11393 SDValue VHi = DAG.getAnyExtOrTrunc(
11394 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11395 dl, MVT::i64);
11396 if (DAG.getDataLayout().isBigEndian())
11397 std::swap (VLo, VHi);
11398 SDValue RegClass =
11399 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11400 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11401 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11402 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11403 return SDValue(
11404 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11405}
11406
Tim Northovercdf15292016-04-14 17:03:29 +000011407static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011408 SmallVectorImpl<SDValue> &Results,
11409 SelectionDAG &DAG,
11410 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000011411 assert(N->getValueType(0) == MVT::i128 &&
11412 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011413
11414 if (Subtarget->hasLSE()) {
11415 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11416 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11417 SDValue Ops[] = {
11418 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11419 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11420 N->getOperand(1), // Ptr
11421 N->getOperand(0), // Chain in
11422 };
11423
Chandler Carruth66654b72018-08-14 23:30:32 +000011424 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011425
11426 unsigned Opcode;
Chandler Carruth66654b72018-08-14 23:30:32 +000011427 switch (MemOp->getOrdering()) {
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011428 case AtomicOrdering::Monotonic:
11429 Opcode = AArch64::CASPX;
11430 break;
11431 case AtomicOrdering::Acquire:
11432 Opcode = AArch64::CASPAX;
11433 break;
11434 case AtomicOrdering::Release:
11435 Opcode = AArch64::CASPLX;
11436 break;
11437 case AtomicOrdering::AcquireRelease:
11438 case AtomicOrdering::SequentiallyConsistent:
11439 Opcode = AArch64::CASPALX;
11440 break;
11441 default:
11442 llvm_unreachable("Unexpected ordering!");
11443 }
11444
11445 MachineSDNode *CmpSwap = DAG.getMachineNode(
11446 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
Chandler Carruth66654b72018-08-14 23:30:32 +000011447 DAG.setNodeMemRefs(CmpSwap, {MemOp});
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011448
11449 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11450 if (DAG.getDataLayout().isBigEndian())
11451 std::swap(SubReg1, SubReg2);
11452 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11453 SDValue(CmpSwap, 0)));
11454 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11455 SDValue(CmpSwap, 0)));
11456 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11457 return;
11458 }
11459
Tim Northover2f32e7f2016-08-04 19:32:28 +000011460 auto Desired = splitInt128(N->getOperand(2), DAG);
11461 auto New = splitInt128(N->getOperand(3), DAG);
11462 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11463 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000011464 SDNode *CmpSwap = DAG.getMachineNode(
11465 AArch64::CMP_SWAP_128, SDLoc(N),
11466 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11467
Chandler Carruth66654b72018-08-14 23:30:32 +000011468 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11469 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
Tim Northovercdf15292016-04-14 17:03:29 +000011470
11471 Results.push_back(SDValue(CmpSwap, 0));
11472 Results.push_back(SDValue(CmpSwap, 1));
11473 Results.push_back(SDValue(CmpSwap, 3));
11474}
11475
Tim Northover3b0846e2014-05-24 12:50:23 +000011476void AArch64TargetLowering::ReplaceNodeResults(
11477 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11478 switch (N->getOpcode()) {
11479 default:
11480 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000011481 case ISD::BITCAST:
11482 ReplaceBITCASTResults(N, Results, DAG);
11483 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000011484 case ISD::VECREDUCE_ADD:
11485 case ISD::VECREDUCE_SMAX:
11486 case ISD::VECREDUCE_SMIN:
11487 case ISD::VECREDUCE_UMAX:
11488 case ISD::VECREDUCE_UMIN:
11489 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11490 return;
11491
Charlie Turner434d4592015-10-16 15:38:25 +000011492 case AArch64ISD::SADDV:
11493 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11494 return;
11495 case AArch64ISD::UADDV:
11496 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11497 return;
11498 case AArch64ISD::SMINV:
11499 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11500 return;
11501 case AArch64ISD::UMINV:
11502 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11503 return;
11504 case AArch64ISD::SMAXV:
11505 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11506 return;
11507 case AArch64ISD::UMAXV:
11508 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11509 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011510 case ISD::FP_TO_UINT:
11511 case ISD::FP_TO_SINT:
11512 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11513 // Let normal code take care of it by not adding anything to Results.
11514 return;
Tim Northovercdf15292016-04-14 17:03:29 +000011515 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000011516 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000011517 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000011518 }
11519}
11520
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011521bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000011522 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11523 return TargetLowering::useLoadStackGuardNode();
11524 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000011525}
11526
Sanjay Patel1dd15592015-07-28 23:05:48 +000011527unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000011528 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11529 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000011530 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000011531}
11532
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011533TargetLoweringBase::LegalizeTypeAction
Craig Topper0b5f8162018-11-05 23:26:13 +000011534AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011535 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11536 // v4i16, v2i32 instead of to promote.
Craig Topper0b5f8162018-11-05 23:26:13 +000011537 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11538 VT == MVT::v1f32)
Chandler Carruth9d010ff2014-07-03 00:23:43 +000011539 return TypeWidenVector;
11540
11541 return TargetLoweringBase::getPreferredVectorAction(VT);
11542}
11543
Robin Morisseted3d48f2014-09-03 21:29:59 +000011544// Loads and stores less than 128-bits are already atomic; ones above that
11545// are doomed anyway, so defer to the default libcall and blame the OS when
11546// things go wrong.
11547bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11548 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11549 return Size == 128;
11550}
11551
11552// Loads and stores less than 128-bits are already atomic; ones above that
11553// are doomed anyway, so defer to the default libcall and blame the OS when
11554// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000011555TargetLowering::AtomicExpansionKind
11556AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011557 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000011558 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011559}
11560
11561// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000011562TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000011563AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000011564 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000011565 if (Size > 128) return AtomicExpansionKind::None;
11566 // Nand not supported in LSE.
11567 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000011568 // Leave 128 bits to LLSC.
11569 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000011570}
11571
Alex Bradbury79518b02018-09-19 14:51:42 +000011572TargetLowering::AtomicExpansionKind
11573AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
Ahmed Bougacha52468672015-09-11 17:08:28 +000011574 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000011575 // If subtarget has LSE, leave cmpxchg intact for codegen.
Alex Bradbury79518b02018-09-19 14:51:42 +000011576 if (Subtarget->hasLSE())
11577 return AtomicExpansionKind::None;
Tim Northovercdf15292016-04-14 17:03:29 +000011578 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11579 // implement cmpxchg without spilling. If the address being exchanged is also
11580 // on the stack and close enough to the spill slot, this can lead to a
11581 // situation where the monitor always gets cleared and the atomic operation
11582 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
Alex Bradbury79518b02018-09-19 14:51:42 +000011583 if (getTargetMachine().getOptLevel() == 0)
11584 return AtomicExpansionKind::None;
11585 return AtomicExpansionKind::LLSC;
Robin Morisset25c8e312014-09-17 00:06:58 +000011586}
11587
Tim Northover3b0846e2014-05-24 12:50:23 +000011588Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11589 AtomicOrdering Ord) const {
11590 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11591 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000011592 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011593
11594 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11595 // intrinsic must return {i64, i64} and we have to recombine them into a
11596 // single i128 here.
11597 if (ValTy->getPrimitiveSizeInBits() == 128) {
11598 Intrinsic::ID Int =
11599 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011600 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000011601
11602 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11603 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11604
11605 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11606 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11607 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11608 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11609 return Builder.CreateOr(
11610 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11611 }
11612
11613 Type *Tys[] = { Addr->getType() };
11614 Intrinsic::ID Int =
11615 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000011616 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000011617
11618 return Builder.CreateTruncOrBitCast(
11619 Builder.CreateCall(Ldxr, Addr),
11620 cast<PointerType>(Addr->getType())->getElementType());
11621}
11622
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011623void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11624 IRBuilder<> &Builder) const {
11625 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000011626 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000011627}
11628
Tim Northover3b0846e2014-05-24 12:50:23 +000011629Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11630 Value *Val, Value *Addr,
11631 AtomicOrdering Ord) const {
11632 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000011633 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000011634
11635 // Since the intrinsics must have legal type, the i128 intrinsics take two
11636 // parameters: "i64, i64". We must marshal Val into the appropriate form
11637 // before the call.
11638 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11639 Intrinsic::ID Int =
11640 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11641 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11642 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11643
11644 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11645 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11646 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000011647 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011648 }
11649
11650 Intrinsic::ID Int =
11651 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11652 Type *Tys[] = { Addr->getType() };
11653 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11654
David Blaikieff6409d2015-05-18 22:13:54 +000011655 return Builder.CreateCall(Stxr,
11656 {Builder.CreateZExtOrBitCast(
11657 Val, Stxr->getFunctionType()->getParamType(0)),
11658 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000011659}
Tim Northover3c55cca2014-11-27 21:02:42 +000011660
11661bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11662 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11663 return Ty->isArrayTy();
11664}
Matthias Braunaf7d7702015-07-16 20:02:37 +000011665
11666bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11667 EVT) const {
11668 return false;
11669}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011670
Petr Hoseka7d59162017-02-24 03:10:10 +000011671static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011672 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11673 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000011674 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011675 return IRB.CreatePointerCast(
Petr Hoseka7d59162017-02-24 03:10:10 +000011676 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000011677 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
11678}
11679
Petr Hoseka7d59162017-02-24 03:10:10 +000011680Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11681 // Android provides a fixed TLS slot for the stack cookie. See the definition
11682 // of TLS_SLOT_STACK_GUARD in
11683 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11684 if (Subtarget->isTargetAndroid())
11685 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011686
Petr Hoseka7d59162017-02-24 03:10:10 +000011687 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011688 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011689 if (Subtarget->isTargetFuchsia())
11690 return UseTlsOffset(IRB, -0x10);
11691
11692 return TargetLowering::getIRStackGuard(IRB);
11693}
11694
Mandeep Singh Grang397765b2018-11-09 02:48:36 +000011695void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11696 // MSVC CRT provides functionalities for stack protection.
11697 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11698 // MSVC CRT has a global variable holding security cookie.
11699 M.getOrInsertGlobal("__security_cookie",
11700 Type::getInt8PtrTy(M.getContext()));
11701
11702 // MSVC CRT has a function to validate security cookie.
11703 auto *SecurityCheckCookie = cast<Function>(
11704 M.getOrInsertFunction("__security_check_cookie",
11705 Type::getVoidTy(M.getContext()),
11706 Type::getInt8PtrTy(M.getContext())));
11707 SecurityCheckCookie->setCallingConv(CallingConv::Win64);
11708 SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
11709 return;
11710 }
11711 TargetLowering::insertSSPDeclarations(M);
11712}
11713
11714Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
11715 // MSVC CRT has a global variable holding security cookie.
11716 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11717 return M.getGlobalVariable("__security_cookie");
11718 return TargetLowering::getSDagStackGuard(M);
11719}
11720
11721Value *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
11722 // MSVC CRT has a function to validate security cookie.
11723 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11724 return M.getFunction("__security_check_cookie");
11725 return TargetLowering::getSSPStackGuardCheck(M);
11726}
11727
Petr Hoseka7d59162017-02-24 03:10:10 +000011728Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011729 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11730 // definition of TLS_SLOT_SAFESTACK in
11731 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000011732 if (Subtarget->isTargetAndroid())
11733 return UseTlsOffset(IRB, 0x48);
11734
11735 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000011736 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000011737 if (Subtarget->isTargetFuchsia())
11738 return UseTlsOffset(IRB, -0x8);
11739
11740 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000011741}
Manman Rencbe4f942015-12-16 21:04:19 +000011742
Geoff Berry5d534b62017-02-21 18:53:14 +000011743bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11744 const Instruction &AndI) const {
11745 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11746 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11747 // may be beneficial to sink in other cases, but we would have to check that
11748 // the cmp would not get folded into the br to form a cbz for these to be
11749 // beneficial.
11750 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11751 if (!Mask)
11752 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011753 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011754}
11755
Manman Rencbe4f942015-12-16 21:04:19 +000011756void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11757 // Update IsSplitCSR in AArch64unctionInfo.
11758 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11759 AFI->setIsSplitCSR(true);
11760}
11761
11762void AArch64TargetLowering::insertCopiesSplitCSR(
11763 MachineBasicBlock *Entry,
11764 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11765 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11766 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11767 if (!IStart)
11768 return;
11769
11770 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11771 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011772 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011773 for (const MCPhysReg *I = IStart; *I; ++I) {
11774 const TargetRegisterClass *RC = nullptr;
11775 if (AArch64::GPR64RegClass.contains(*I))
11776 RC = &AArch64::GPR64RegClass;
11777 else if (AArch64::FPR64RegClass.contains(*I))
11778 RC = &AArch64::FPR64RegClass;
11779 else
11780 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11781
11782 unsigned NewVR = MRI->createVirtualRegister(RC);
11783 // Create copy from CSR to a virtual register.
11784 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11785 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11786 // nounwind. If we want to generalize this later, we may need to emit
11787 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011788 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011789 Attribute::NoUnwind) &&
11790 "Function should be nounwind in insertCopiesSplitCSR!");
11791 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011792 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011793 .addReg(*I);
11794
Manman Ren4632e8e2016-01-15 20:13:28 +000011795 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011796 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011797 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11798 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011799 .addReg(NewVR);
11800 }
11801}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011802
Reid Klecknerb5180542017-03-21 16:57:19 +000011803bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011804 // Integer division on AArch64 is expensive. However, when aggressively
11805 // optimizing for code size, we prefer to use a div instruction, as it is
11806 // usually smaller than the alternative sequence.
11807 // The exception to this is vector division. Since AArch64 doesn't have vector
11808 // integer division, leaving the division as-is is a loss even in terms of
11809 // size, because it will have to be scalarized, while the alternative code
11810 // sequence can be performed in vector form.
11811 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011812 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011813 return OptSize && !VT.isVector();
11814}
Tim Northoverf19d4672017-02-08 17:57:20 +000011815
Joel Jones07150922018-01-25 21:55:39 +000011816bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11817 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11818}
11819
Tim Northoverf19d4672017-02-08 17:57:20 +000011820unsigned
11821AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011822 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011823 return getPointerTy(DL).getSizeInBits();
11824
11825 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11826}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011827
11828void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11829 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11830 TargetLoweringBase::finalizeLowering(MF);
11831}
Eli Friedmanad1151c2018-11-09 23:33:30 +000011832
11833// Unlike X86, we let frame lowering assign offsets to all catch objects.
11834bool AArch64TargetLowering::needsFixedCatchObjects() const {
11835 return false;
11836}