blob: eb21585508f879fd2db29696d02e52b92b5a0006 [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/MachineValueType.h"
42#include "llvm/CodeGen/RuntimeLibcalls.h"
43#include "llvm/CodeGen/SelectionDAG.h"
44#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000045#include "llvm/CodeGen/TargetCallingConv.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000046#include "llvm/CodeGen/TargetInstrInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000047#include "llvm/CodeGen/ValueTypes.h"
48#include "llvm/IR/Attributes.h"
49#include "llvm/IR/Constants.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/DebugLoc.h"
52#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000053#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000054#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000055#include "llvm/IR/GlobalValue.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000056#include "llvm/IR/IRBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000057#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Instructions.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000059#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000060#include "llvm/IR/Module.h"
61#include "llvm/IR/OperandTraits.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000062#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000063#include "llvm/IR/Use.h"
64#include "llvm/IR/Value.h"
65#include "llvm/MC/MCRegisterInfo.h"
66#include "llvm/Support/Casting.h"
67#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000068#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000069#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000070#include "llvm/Support/Debug.h"
71#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000072#include "llvm/Support/KnownBits.h"
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);
190 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
191 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
201 // Custom lowering hooks are needed for XOR
202 // to fold it into CSINC/CSINV.
203 setOperationAction(ISD::XOR, MVT::i32, Custom);
204 setOperationAction(ISD::XOR, MVT::i64, Custom);
205
206 // Virtually no operation on f128 is legal, but LLVM can't expand them when
207 // there's a valid register class, so we need custom operations in most cases.
208 setOperationAction(ISD::FABS, MVT::f128, Expand);
209 setOperationAction(ISD::FADD, MVT::f128, Custom);
210 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
211 setOperationAction(ISD::FCOS, MVT::f128, Expand);
212 setOperationAction(ISD::FDIV, MVT::f128, Custom);
213 setOperationAction(ISD::FMA, MVT::f128, Expand);
214 setOperationAction(ISD::FMUL, MVT::f128, Custom);
215 setOperationAction(ISD::FNEG, MVT::f128, Expand);
216 setOperationAction(ISD::FPOW, MVT::f128, Expand);
217 setOperationAction(ISD::FREM, MVT::f128, Expand);
218 setOperationAction(ISD::FRINT, MVT::f128, Expand);
219 setOperationAction(ISD::FSIN, MVT::f128, Expand);
220 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
221 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
222 setOperationAction(ISD::FSUB, MVT::f128, Custom);
223 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
224 setOperationAction(ISD::SETCC, MVT::f128, Custom);
225 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
226 setOperationAction(ISD::SELECT, MVT::f128, Custom);
227 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
228 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
229
230 // Lowering for many of the conversions is actually specified by the non-f128
231 // type. The LowerXXX function will be trivial when f128 isn't involved.
232 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
233 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
234 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
235 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
236 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
237 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
238 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
239 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
240 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
241 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
242 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
243 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
244 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
245 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
246
247 // Variable arguments.
248 setOperationAction(ISD::VASTART, MVT::Other, Custom);
249 setOperationAction(ISD::VAARG, MVT::Other, Custom);
250 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
251 setOperationAction(ISD::VAEND, MVT::Other, Expand);
252
253 // Variable-sized objects.
254 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
255 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Martin Storsjoa63a5b92018-02-17 14:26:32 +0000256
257 if (Subtarget->isTargetWindows())
258 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
259 else
260 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000261
Tim Northover3b0846e2014-05-24 12:50:23 +0000262 // Constant pool entries
263 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
264
265 // BlockAddress
266 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
267
268 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
269 setOperationAction(ISD::ADDC, MVT::i32, Custom);
270 setOperationAction(ISD::ADDE, MVT::i32, Custom);
271 setOperationAction(ISD::SUBC, MVT::i32, Custom);
272 setOperationAction(ISD::SUBE, MVT::i32, Custom);
273 setOperationAction(ISD::ADDC, MVT::i64, Custom);
274 setOperationAction(ISD::ADDE, MVT::i64, Custom);
275 setOperationAction(ISD::SUBC, MVT::i64, Custom);
276 setOperationAction(ISD::SUBE, MVT::i64, Custom);
277
278 // AArch64 lacks both left-rotate and popcount instructions.
279 setOperationAction(ISD::ROTL, MVT::i32, Expand);
280 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000281 for (MVT VT : MVT::vector_valuetypes()) {
282 setOperationAction(ISD::ROTL, VT, Expand);
283 setOperationAction(ISD::ROTR, VT, Expand);
284 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000285
286 // AArch64 doesn't have {U|S}MUL_LOHI.
287 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
288 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
289
Tim Northover3b0846e2014-05-24 12:50:23 +0000290 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
291 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
292
293 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
294 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000295 for (MVT VT : MVT::vector_valuetypes()) {
296 setOperationAction(ISD::SDIVREM, VT, Expand);
297 setOperationAction(ISD::UDIVREM, VT, Expand);
298 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000299 setOperationAction(ISD::SREM, MVT::i32, Expand);
300 setOperationAction(ISD::SREM, MVT::i64, Expand);
301 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
302 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
303 setOperationAction(ISD::UREM, MVT::i32, Expand);
304 setOperationAction(ISD::UREM, MVT::i64, Expand);
305
306 // Custom lower Add/Sub/Mul with overflow.
307 setOperationAction(ISD::SADDO, MVT::i32, Custom);
308 setOperationAction(ISD::SADDO, MVT::i64, Custom);
309 setOperationAction(ISD::UADDO, MVT::i32, Custom);
310 setOperationAction(ISD::UADDO, MVT::i64, Custom);
311 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
312 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
313 setOperationAction(ISD::USUBO, MVT::i32, Custom);
314 setOperationAction(ISD::USUBO, MVT::i64, Custom);
315 setOperationAction(ISD::SMULO, MVT::i32, Custom);
316 setOperationAction(ISD::SMULO, MVT::i64, Custom);
317 setOperationAction(ISD::UMULO, MVT::i32, Custom);
318 setOperationAction(ISD::UMULO, MVT::i64, Custom);
319
320 setOperationAction(ISD::FSIN, MVT::f32, Expand);
321 setOperationAction(ISD::FSIN, MVT::f64, Expand);
322 setOperationAction(ISD::FCOS, MVT::f32, Expand);
323 setOperationAction(ISD::FCOS, MVT::f64, Expand);
324 setOperationAction(ISD::FPOW, MVT::f32, Expand);
325 setOperationAction(ISD::FPOW, MVT::f64, Expand);
326 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
327 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +0000328 if (Subtarget->hasFullFP16())
329 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
330 else
331 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000332
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000333 setOperationAction(ISD::FREM, MVT::f16, Promote);
334 setOperationAction(ISD::FREM, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000335 setOperationAction(ISD::FREM, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000336 setOperationAction(ISD::FPOW, MVT::f16, Promote);
337 setOperationAction(ISD::FPOW, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000338 setOperationAction(ISD::FPOW, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000339 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
340 setOperationAction(ISD::FCOS, MVT::f16, Promote);
341 setOperationAction(ISD::FCOS, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000342 setOperationAction(ISD::FCOS, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000343 setOperationAction(ISD::FSIN, MVT::f16, Promote);
344 setOperationAction(ISD::FSIN, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000345 setOperationAction(ISD::FSIN, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000346 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
347 setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000348 setOperationAction(ISD::FSINCOS, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000349 setOperationAction(ISD::FEXP, MVT::f16, Promote);
350 setOperationAction(ISD::FEXP, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000351 setOperationAction(ISD::FEXP, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000352 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
353 setOperationAction(ISD::FEXP2, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000354 setOperationAction(ISD::FEXP2, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000355 setOperationAction(ISD::FLOG, MVT::f16, Promote);
356 setOperationAction(ISD::FLOG, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000357 setOperationAction(ISD::FLOG, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000358 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
359 setOperationAction(ISD::FLOG2, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000360 setOperationAction(ISD::FLOG2, MVT::v8f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000361 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
362 setOperationAction(ISD::FLOG10, MVT::v4f16, Promote);
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000363 setOperationAction(ISD::FLOG10, MVT::v8f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000364
365 if (!Subtarget->hasFullFP16()) {
366 setOperationAction(ISD::SELECT, MVT::f16, Promote);
367 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
368 setOperationAction(ISD::SETCC, MVT::f16, Promote);
369 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
370 setOperationAction(ISD::FADD, MVT::f16, Promote);
371 setOperationAction(ISD::FSUB, MVT::f16, Promote);
372 setOperationAction(ISD::FMUL, MVT::f16, Promote);
373 setOperationAction(ISD::FDIV, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000374 setOperationAction(ISD::FMA, MVT::f16, Promote);
375 setOperationAction(ISD::FNEG, MVT::f16, Promote);
376 setOperationAction(ISD::FABS, MVT::f16, Promote);
377 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
378 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000379 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
380 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
381 setOperationAction(ISD::FRINT, MVT::f16, Promote);
382 setOperationAction(ISD::FROUND, MVT::f16, Promote);
383 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
384 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
385 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
386 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
387 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Sjoerd Meijerbe5b60f2017-08-30 08:38:13 +0000388
389 // promote v4f16 to v4f32 when that is known to be safe.
390 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
391 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
392 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
393 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
394 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
395 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
396 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
397 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
398 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
399 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
400 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
401 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
402
403 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
404 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
405 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
406 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
407 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
408 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
409 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
410 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
411 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
412 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
413 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
414 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
415 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
416 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
417 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000418
Sjoerd Meijer0c5ba212017-09-15 09:24:48 +0000419 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
420 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
421 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
422 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
423 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
424 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
425 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
426 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
427 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
428 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
429 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
430 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
431 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
432 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
433 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
434 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
435 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
436 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
437 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
438 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
439 }
Oliver Stannard89d15422014-08-27 16:16:04 +0000440
Tim Northover3b0846e2014-05-24 12:50:23 +0000441 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000442 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000443 setOperationAction(ISD::FFLOOR, Ty, Legal);
444 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
445 setOperationAction(ISD::FCEIL, Ty, Legal);
446 setOperationAction(ISD::FRINT, Ty, Legal);
447 setOperationAction(ISD::FTRUNC, Ty, Legal);
448 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000449 setOperationAction(ISD::FMINNUM, Ty, Legal);
450 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000451 setOperationAction(ISD::FMINNAN, Ty, Legal);
452 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000453 }
454
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000455 if (Subtarget->hasFullFP16()) {
456 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
457 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
458 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
459 setOperationAction(ISD::FRINT, MVT::f16, Legal);
460 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
461 setOperationAction(ISD::FROUND, MVT::f16, Legal);
462 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
463 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
464 setOperationAction(ISD::FMINNAN, MVT::f16, Legal);
465 setOperationAction(ISD::FMAXNAN, MVT::f16, Legal);
466 }
467
Tim Northover3b0846e2014-05-24 12:50:23 +0000468 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
469
Tim Northovercdf15292016-04-14 17:03:29 +0000470 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
Oliver Stannard42699172018-02-12 14:22:03 +0000471 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
472 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
Oliver Stannard02f08c92018-02-12 17:03:11 +0000473 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
474 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
Tim Northovercdf15292016-04-14 17:03:29 +0000475
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000476 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
477 // This requires the Performance Monitors extension.
478 if (Subtarget->hasPerfMon())
479 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
480
Matthias Brauna4852d2c2017-12-18 23:19:42 +0000481 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
482 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
483 // Issue __sincos_stret if available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000484 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
485 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
486 } else {
487 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
488 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
489 }
490
Juergen Ributzka23266502014-12-10 19:43:32 +0000491 // Make floating-point constants legal for the large code model, so they don't
492 // become loads from the constant pool.
493 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
494 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
495 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
496 }
497
Tim Northover3b0846e2014-05-24 12:50:23 +0000498 // AArch64 does not have floating-point extending loads, i1 sign-extending
499 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000500 for (MVT VT : MVT::fp_valuetypes()) {
501 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
502 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
503 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
504 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
505 }
506 for (MVT VT : MVT::integer_valuetypes())
507 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
508
Tim Northover3b0846e2014-05-24 12:50:23 +0000509 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
510 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
511 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
512 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
513 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
514 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
515 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000516
517 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
518 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
519
Tim Northover3b0846e2014-05-24 12:50:23 +0000520 // Indexed loads and stores are supported.
521 for (unsigned im = (unsigned)ISD::PRE_INC;
522 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
523 setIndexedLoadAction(im, MVT::i8, Legal);
524 setIndexedLoadAction(im, MVT::i16, Legal);
525 setIndexedLoadAction(im, MVT::i32, Legal);
526 setIndexedLoadAction(im, MVT::i64, Legal);
527 setIndexedLoadAction(im, MVT::f64, Legal);
528 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000529 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000530 setIndexedStoreAction(im, MVT::i8, Legal);
531 setIndexedStoreAction(im, MVT::i16, Legal);
532 setIndexedStoreAction(im, MVT::i32, Legal);
533 setIndexedStoreAction(im, MVT::i64, Legal);
534 setIndexedStoreAction(im, MVT::f64, Legal);
535 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000536 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000537 }
538
539 // Trap.
540 setOperationAction(ISD::TRAP, MVT::Other, Legal);
541
542 // We combine OR nodes for bitfield operations.
543 setTargetDAGCombine(ISD::OR);
544
545 // Vector add and sub nodes may conceal a high-half opportunity.
546 // Also, try to fold ADD into CSINC/CSINV..
547 setTargetDAGCombine(ISD::ADD);
548 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000549 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000550 setTargetDAGCombine(ISD::XOR);
551 setTargetDAGCombine(ISD::SINT_TO_FP);
552 setTargetDAGCombine(ISD::UINT_TO_FP);
553
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000554 setTargetDAGCombine(ISD::FP_TO_SINT);
555 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000556 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000557
Tim Northover3b0846e2014-05-24 12:50:23 +0000558 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
559
560 setTargetDAGCombine(ISD::ANY_EXTEND);
561 setTargetDAGCombine(ISD::ZERO_EXTEND);
562 setTargetDAGCombine(ISD::SIGN_EXTEND);
563 setTargetDAGCombine(ISD::BITCAST);
564 setTargetDAGCombine(ISD::CONCAT_VECTORS);
565 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000566 if (Subtarget->supportsAddressTopByteIgnored())
567 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000568
569 setTargetDAGCombine(ISD::MUL);
570
571 setTargetDAGCombine(ISD::SELECT);
572 setTargetDAGCombine(ISD::VSELECT);
573
574 setTargetDAGCombine(ISD::INTRINSIC_VOID);
575 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
576 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
577
578 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
579 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
580 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
581
582 setStackPointerRegisterToSaveRestore(AArch64::SP);
583
584 setSchedulingPreference(Sched::Hybrid);
585
Quentin Colombet6843ac42015-03-31 20:52:32 +0000586 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000587
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000588 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000589 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000590 // Set preferred alignments.
591 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
592 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000593
Evandro Menezese45de8a2016-09-26 15:32:33 +0000594 // Only change the limit for entries in a jump table if specified by
595 // the subtarget, but not at the command line.
596 unsigned MaxJT = STI.getMaximumJumpTableSize();
597 if (MaxJT && getMaximumJumpTableSize() == 0)
598 setMaximumJumpTableSize(MaxJT);
599
Tim Northover3b0846e2014-05-24 12:50:23 +0000600 setHasExtractBitsInsn(true);
601
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000602 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
603
Tim Northover3b0846e2014-05-24 12:50:23 +0000604 if (Subtarget->hasNEON()) {
605 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
606 // silliness like this:
607 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
608 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
609 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
610 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
611 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
612 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
613 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
614 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
615 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
616 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
617 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
618 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
619 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
620 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
621 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
622 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
623 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
624 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
625 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
626 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
627 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
628 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
629 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
630 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
631 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
632
633 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
634 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
635 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
636 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
637 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
638
639 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
640
641 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
642 // elements smaller than i32, so promote the input to i32 first.
Craig Toppera4f99972018-01-01 19:21:35 +0000643 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
644 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
645 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
646 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000647 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
648 // -> v8f16 conversions.
Craig Toppera4f99972018-01-01 19:21:35 +0000649 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
650 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
651 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
652 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000653 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
654 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
655 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
656 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
657 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000658 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
659 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
660 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
661 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000662
Craig Topperc5551bf2016-04-26 05:26:51 +0000663 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
664 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
665
Craig Topper3b4842b2016-04-28 01:58:21 +0000666 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
667 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
668 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
669 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
670 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
671 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
672 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
673 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
674
Tim Northover3b0846e2014-05-24 12:50:23 +0000675 // AArch64 doesn't have MUL.2d:
676 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000677 // Custom handling for some quad-vector types to detect MULL.
678 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
679 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
680 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
681
Amara Emersonc9916d72017-05-16 21:29:22 +0000682 // Vector reductions
683 for (MVT VT : MVT::integer_valuetypes()) {
684 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
685 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
686 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
687 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
688 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
689 }
690 for (MVT VT : MVT::fp_valuetypes()) {
691 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
692 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
693 }
694
Tim Northover3b0846e2014-05-24 12:50:23 +0000695 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
696 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
697 // Likewise, narrowing and extending vector loads/stores aren't handled
698 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000699 for (MVT VT : MVT::vector_valuetypes()) {
700 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000701
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000702 setOperationAction(ISD::MULHS, VT, Expand);
703 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
704 setOperationAction(ISD::MULHU, VT, Expand);
705 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000706
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000707 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000708
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000709 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000710 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000711 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
712 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
713 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
714 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000715 }
716
717 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000718 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000719 setOperationAction(ISD::FFLOOR, Ty, Legal);
720 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
721 setOperationAction(ISD::FCEIL, Ty, Legal);
722 setOperationAction(ISD::FRINT, Ty, Legal);
723 setOperationAction(ISD::FTRUNC, Ty, Legal);
724 setOperationAction(ISD::FROUND, Ty, Legal);
725 }
726 }
James Molloyf089ab72014-08-06 10:42:18 +0000727
Matthias Braun651cff42016-06-02 18:03:53 +0000728 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000729}
730
Craig Topper18e69f42016-04-15 06:20:21 +0000731void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000732 assert(VT.isVector() && "VT should be a vector type");
Tim Northover3b0846e2014-05-24 12:50:23 +0000733
Pablo Barrio9b3d4c02018-01-24 14:13:47 +0000734 if (VT.isFloatingPoint()) {
735 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
736 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
737 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
Tim Northover3b0846e2014-05-24 12:50:23 +0000738 }
739
740 // Mark vector float intrinsics as expand.
741 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000742 setOperationAction(ISD::FSIN, VT, Expand);
743 setOperationAction(ISD::FCOS, VT, Expand);
Craig Topper18e69f42016-04-15 06:20:21 +0000744 setOperationAction(ISD::FPOW, VT, Expand);
745 setOperationAction(ISD::FLOG, VT, Expand);
746 setOperationAction(ISD::FLOG2, VT, Expand);
747 setOperationAction(ISD::FLOG10, VT, Expand);
748 setOperationAction(ISD::FEXP, VT, Expand);
749 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000750
751 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000752 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000753 }
754
Craig Topper18e69f42016-04-15 06:20:21 +0000755 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
756 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
757 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
758 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
759 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
760 setOperationAction(ISD::SRA, VT, Custom);
761 setOperationAction(ISD::SRL, VT, Custom);
762 setOperationAction(ISD::SHL, VT, Custom);
763 setOperationAction(ISD::AND, VT, Custom);
764 setOperationAction(ISD::OR, VT, Custom);
765 setOperationAction(ISD::SETCC, VT, Custom);
766 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000767
Craig Topper18e69f42016-04-15 06:20:21 +0000768 setOperationAction(ISD::SELECT, VT, Expand);
769 setOperationAction(ISD::SELECT_CC, VT, Expand);
770 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000771 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000772 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000773
774 // CNT supports only B element sizes.
775 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000776 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000777
Craig Topper18e69f42016-04-15 06:20:21 +0000778 setOperationAction(ISD::UDIV, VT, Expand);
779 setOperationAction(ISD::SDIV, VT, Expand);
780 setOperationAction(ISD::UREM, VT, Expand);
781 setOperationAction(ISD::SREM, VT, Expand);
782 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000783
Craig Topper18e69f42016-04-15 06:20:21 +0000784 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
785 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000786
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +0000787 if (!VT.isFloatingPoint())
788 setOperationAction(ISD::ABS, VT, Legal);
789
Hal Finkelcd8664c2015-12-11 23:11:52 +0000790 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000791 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000792 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000793 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000794
Sjoerd Meijerec9581e2017-08-18 10:51:14 +0000795 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
796 if (VT.isFloatingPoint() &&
797 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
James Molloyb7b2a1e2015-08-11 12:06:37 +0000798 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
799 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000800 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000801
Tim Northover3b0846e2014-05-24 12:50:23 +0000802 if (Subtarget->isLittleEndian()) {
803 for (unsigned im = (unsigned)ISD::PRE_INC;
804 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000805 setIndexedLoadAction(im, VT, Legal);
806 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000807 }
808 }
809}
810
811void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
812 addRegisterClass(VT, &AArch64::FPR64RegClass);
813 addTypeForNEON(VT, MVT::v2i32);
814}
815
816void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
817 addRegisterClass(VT, &AArch64::FPR128RegClass);
818 addTypeForNEON(VT, MVT::v4i32);
819}
820
Mehdi Amini44ede332015-07-09 02:09:04 +0000821EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
822 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000823 if (!VT.isVector())
824 return MVT::i32;
825 return VT.changeVectorElementTypeToInteger();
826}
827
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000828static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
829 const APInt &Demanded,
830 TargetLowering::TargetLoweringOpt &TLO,
831 unsigned NewOpc) {
832 uint64_t OldImm = Imm, NewImm, Enc;
833 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
834
835 // Return if the immediate is already all zeros, all ones, a bimm32 or a
836 // bimm64.
837 if (Imm == 0 || Imm == Mask ||
838 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
839 return false;
840
841 unsigned EltSize = Size;
842 uint64_t DemandedBits = Demanded.getZExtValue();
843
844 // Clear bits that are not demanded.
845 Imm &= DemandedBits;
846
847 while (true) {
848 // The goal here is to set the non-demanded bits in a way that minimizes
849 // the number of switching between 0 and 1. In order to achieve this goal,
850 // we set the non-demanded bits to the value of the preceding demanded bits.
851 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
852 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
853 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
854 // The final result is 0b11000011.
855 uint64_t NonDemandedBits = ~DemandedBits;
856 uint64_t InvertedImm = ~Imm & DemandedBits;
857 uint64_t RotatedImm =
858 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
859 NonDemandedBits;
860 uint64_t Sum = RotatedImm + NonDemandedBits;
861 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
862 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
863 NewImm = (Imm | Ones) & Mask;
864
865 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
866 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
867 // we halve the element size and continue the search.
868 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
869 break;
870
871 // We cannot shrink the element size any further if it is 2-bits.
872 if (EltSize == 2)
873 return false;
874
875 EltSize /= 2;
876 Mask >>= EltSize;
877 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
878
879 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
880 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
881 return false;
882
883 // Merge the upper and lower halves of Imm and DemandedBits.
884 Imm |= Hi;
885 DemandedBits |= DemandedBitsHi;
886 }
887
888 ++NumOptimizedImms;
889
890 // Replicate the element across the register width.
891 while (EltSize < Size) {
892 NewImm |= NewImm << EltSize;
893 EltSize *= 2;
894 }
895
896 (void)OldImm;
897 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
898 "demanded bits should never be altered");
899 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
900
901 // Create the new constant immediate node.
902 EVT VT = Op.getValueType();
903 SDLoc DL(Op);
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000904 SDValue New;
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000905
906 // If the new constant immediate is all-zeros or all-ones, let the target
907 // independent DAG combine optimize this node.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000908 if (NewImm == 0 || NewImm == OrigMask) {
909 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
910 TLO.DAG.getConstant(NewImm, DL, VT));
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000911 // Otherwise, create a machine node so that target independent DAG combine
912 // doesn't undo this optimization.
Akira Hatanakae8ae3342017-05-23 06:08:37 +0000913 } else {
914 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
915 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
916 New = SDValue(
917 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
918 }
Akira Hatanaka22e839f2017-04-21 18:53:12 +0000919
920 return TLO.CombineTo(Op, New);
921}
922
923bool AArch64TargetLowering::targetShrinkDemandedConstant(
924 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
925 // Delay this optimization to as late as possible.
926 if (!TLO.LegalOps)
927 return false;
928
929 if (!EnableOptimizeLogicalImm)
930 return false;
931
932 EVT VT = Op.getValueType();
933 if (VT.isVector())
934 return false;
935
936 unsigned Size = VT.getSizeInBits();
937 assert((Size == 32 || Size == 64) &&
938 "i32 or i64 is expected after legalization.");
939
940 // Exit early if we demand all bits.
941 if (Demanded.countPopulation() == Size)
942 return false;
943
944 unsigned NewOpc;
945 switch (Op.getOpcode()) {
946 default:
947 return false;
948 case ISD::AND:
949 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
950 break;
951 case ISD::OR:
952 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
953 break;
954 case ISD::XOR:
955 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
956 break;
957 }
958 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
959 if (!C)
960 return false;
961 uint64_t Imm = C->getZExtValue();
962 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
963}
964
Tim Northover3b0846e2014-05-24 12:50:23 +0000965/// computeKnownBitsForTargetNode - Determine which of the bits specified in
Craig Topperd0af7e82017-04-28 05:31:46 +0000966/// Mask are known to be either zero or one and return them Known.
Tim Northover3b0846e2014-05-24 12:50:23 +0000967void AArch64TargetLowering::computeKnownBitsForTargetNode(
Craig Topperd0af7e82017-04-28 05:31:46 +0000968 const SDValue Op, KnownBits &Known,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000969 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000970 switch (Op.getOpcode()) {
971 default:
972 break;
973 case AArch64ISD::CSEL: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000974 KnownBits Known2;
975 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
976 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
977 Known.Zero &= Known2.Zero;
978 Known.One &= Known2.One;
Tim Northover3b0846e2014-05-24 12:50:23 +0000979 break;
980 }
981 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000982 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000983 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
984 switch (IntID) {
985 default: return;
986 case Intrinsic::aarch64_ldaxr:
987 case Intrinsic::aarch64_ldxr: {
Craig Topperd0af7e82017-04-28 05:31:46 +0000988 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +0000989 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +0000990 unsigned MemBits = VT.getScalarSizeInBits();
Craig Topperd0af7e82017-04-28 05:31:46 +0000991 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
Tim Northover3b0846e2014-05-24 12:50:23 +0000992 return;
993 }
994 }
995 break;
996 }
997 case ISD::INTRINSIC_WO_CHAIN:
998 case ISD::INTRINSIC_VOID: {
999 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1000 switch (IntNo) {
1001 default:
1002 break;
1003 case Intrinsic::aarch64_neon_umaxv:
1004 case Intrinsic::aarch64_neon_uminv: {
1005 // Figure out the datatype of the vector operand. The UMINV instruction
1006 // will zero extend the result, so we can mark as known zero all the
1007 // bits larger than the element datatype. 32-bit or larget doesn't need
1008 // this as those are legal types and will be handled by isel directly.
1009 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
Craig Topperd0af7e82017-04-28 05:31:46 +00001010 unsigned BitWidth = Known.getBitWidth();
Tim Northover3b0846e2014-05-24 12:50:23 +00001011 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1012 assert(BitWidth >= 8 && "Unexpected width!");
1013 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
Craig Topperd0af7e82017-04-28 05:31:46 +00001014 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001015 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1016 assert(BitWidth >= 16 && "Unexpected width!");
1017 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
Craig Topperd0af7e82017-04-28 05:31:46 +00001018 Known.Zero |= Mask;
Tim Northover3b0846e2014-05-24 12:50:23 +00001019 }
1020 break;
1021 } break;
1022 }
1023 }
1024 }
1025}
1026
Mehdi Aminieaabc512015-07-09 15:12:23 +00001027MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1028 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00001029 return MVT::i64;
1030}
1031
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001032bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1033 unsigned AddrSpace,
1034 unsigned Align,
1035 bool *Fast) const {
1036 if (Subtarget->requiresStrictAlign())
1037 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001038
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001039 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +00001040 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1041 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00001042 // See comments in performSTORECombine() for more details about
1043 // these conditions.
1044
1045 // Code that uses clang vector extensions can mark that it
1046 // wants unaligned accesses to be treated as fast by
1047 // underspecifying alignment to be 1 or 2.
1048 Align <= 2 ||
1049
1050 // Disregard v2i64. Memcpy lowering produces those and splitting
1051 // them regresses performance on micro-benchmarks and olden/bh.
1052 VT == MVT::v2i64;
1053 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +00001054 return true;
1055}
1056
Tim Northover3b0846e2014-05-24 12:50:23 +00001057FastISel *
1058AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1059 const TargetLibraryInfo *libInfo) const {
1060 return AArch64::createFastISel(funcInfo, libInfo);
1061}
1062
1063const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +00001064 switch ((AArch64ISD::NodeType)Opcode) {
1065 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001066 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1067 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1068 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1069 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1070 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1071 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1072 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1073 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1074 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1075 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1076 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1077 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +00001078 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +00001079 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1080 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1081 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1082 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1083 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1084 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1085 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +00001086 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1087 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1088 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001089 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +00001090 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1091 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1092 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1093 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1094 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1095 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1096 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1097 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1098 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1099 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1100 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1101 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1102 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1103 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1104 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1105 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1106 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1107 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1108 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1109 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1110 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1111 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1112 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1113 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1114 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1115 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1116 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1117 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1118 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1119 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1120 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1121 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1122 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1123 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1124 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1125 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1126 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1127 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1128 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1129 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1130 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1131 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1132 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1133 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1134 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1135 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1136 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1137 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +00001138 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1139 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1140 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1141 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1142 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1143 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +00001144 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1145 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1146 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1147 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1148 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1149 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1150 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +00001151 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +00001152 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1153 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +00001154 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +00001155 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1156 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1157 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1158 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1159 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1160 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1161 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1162 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1163 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1164 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1165 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1166 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1167 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1168 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1169 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1170 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1171 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1172 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1173 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1174 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1175 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1176 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1177 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1178 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1179 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1180 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1181 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1182 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1183 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001184 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1185 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001186 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001187 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1188 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1189 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001190 }
Matthias Braund04893f2015-05-07 21:33:59 +00001191 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001192}
1193
1194MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001195AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001196 MachineBasicBlock *MBB) const {
1197 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1198 // phi node:
1199
1200 // OrigBB:
1201 // [... previous instrs leading to comparison ...]
1202 // b.ne TrueBB
1203 // b EndBB
1204 // TrueBB:
1205 // ; Fallthrough
1206 // EndBB:
1207 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1208
Tim Northover3b0846e2014-05-24 12:50:23 +00001209 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001210 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001211 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001212 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001213 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001214
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001215 unsigned DestReg = MI.getOperand(0).getReg();
1216 unsigned IfTrueReg = MI.getOperand(1).getReg();
1217 unsigned IfFalseReg = MI.getOperand(2).getReg();
1218 unsigned CondCode = MI.getOperand(3).getImm();
1219 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001220
1221 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1222 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1223 MF->insert(It, TrueBB);
1224 MF->insert(It, EndBB);
1225
1226 // Transfer rest of current basic-block to EndBB
1227 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1228 MBB->end());
1229 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1230
1231 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1232 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1233 MBB->addSuccessor(TrueBB);
1234 MBB->addSuccessor(EndBB);
1235
1236 // TrueBB falls through to the end.
1237 TrueBB->addSuccessor(EndBB);
1238
1239 if (!NZCVKilled) {
1240 TrueBB->addLiveIn(AArch64::NZCV);
1241 EndBB->addLiveIn(AArch64::NZCV);
1242 }
1243
1244 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1245 .addReg(IfTrueReg)
1246 .addMBB(TrueBB)
1247 .addReg(IfFalseReg)
1248 .addMBB(MBB);
1249
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001250 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001251 return EndBB;
1252}
1253
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001254MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1255 MachineInstr &MI, MachineBasicBlock *BB) const {
1256 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001257 default:
1258#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001259 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001260#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001261 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001262
1263 case AArch64::F128CSEL:
1264 return EmitF128CSEL(MI, BB);
1265
1266 case TargetOpcode::STACKMAP:
1267 case TargetOpcode::PATCHPOINT:
1268 return emitPatchPoint(MI, BB);
1269 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001270}
1271
1272//===----------------------------------------------------------------------===//
1273// AArch64 Lowering private implementation.
1274//===----------------------------------------------------------------------===//
1275
1276//===----------------------------------------------------------------------===//
1277// Lowering Code
1278//===----------------------------------------------------------------------===//
1279
1280/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1281/// CC
1282static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1283 switch (CC) {
1284 default:
1285 llvm_unreachable("Unknown condition code!");
1286 case ISD::SETNE:
1287 return AArch64CC::NE;
1288 case ISD::SETEQ:
1289 return AArch64CC::EQ;
1290 case ISD::SETGT:
1291 return AArch64CC::GT;
1292 case ISD::SETGE:
1293 return AArch64CC::GE;
1294 case ISD::SETLT:
1295 return AArch64CC::LT;
1296 case ISD::SETLE:
1297 return AArch64CC::LE;
1298 case ISD::SETUGT:
1299 return AArch64CC::HI;
1300 case ISD::SETUGE:
1301 return AArch64CC::HS;
1302 case ISD::SETULT:
1303 return AArch64CC::LO;
1304 case ISD::SETULE:
1305 return AArch64CC::LS;
1306 }
1307}
1308
1309/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1310static void changeFPCCToAArch64CC(ISD::CondCode CC,
1311 AArch64CC::CondCode &CondCode,
1312 AArch64CC::CondCode &CondCode2) {
1313 CondCode2 = AArch64CC::AL;
1314 switch (CC) {
1315 default:
1316 llvm_unreachable("Unknown FP condition!");
1317 case ISD::SETEQ:
1318 case ISD::SETOEQ:
1319 CondCode = AArch64CC::EQ;
1320 break;
1321 case ISD::SETGT:
1322 case ISD::SETOGT:
1323 CondCode = AArch64CC::GT;
1324 break;
1325 case ISD::SETGE:
1326 case ISD::SETOGE:
1327 CondCode = AArch64CC::GE;
1328 break;
1329 case ISD::SETOLT:
1330 CondCode = AArch64CC::MI;
1331 break;
1332 case ISD::SETOLE:
1333 CondCode = AArch64CC::LS;
1334 break;
1335 case ISD::SETONE:
1336 CondCode = AArch64CC::MI;
1337 CondCode2 = AArch64CC::GT;
1338 break;
1339 case ISD::SETO:
1340 CondCode = AArch64CC::VC;
1341 break;
1342 case ISD::SETUO:
1343 CondCode = AArch64CC::VS;
1344 break;
1345 case ISD::SETUEQ:
1346 CondCode = AArch64CC::EQ;
1347 CondCode2 = AArch64CC::VS;
1348 break;
1349 case ISD::SETUGT:
1350 CondCode = AArch64CC::HI;
1351 break;
1352 case ISD::SETUGE:
1353 CondCode = AArch64CC::PL;
1354 break;
1355 case ISD::SETLT:
1356 case ISD::SETULT:
1357 CondCode = AArch64CC::LT;
1358 break;
1359 case ISD::SETLE:
1360 case ISD::SETULE:
1361 CondCode = AArch64CC::LE;
1362 break;
1363 case ISD::SETNE:
1364 case ISD::SETUNE:
1365 CondCode = AArch64CC::NE;
1366 break;
1367 }
1368}
1369
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001370/// Convert a DAG fp condition code to an AArch64 CC.
1371/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1372/// should be AND'ed instead of OR'ed.
1373static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1374 AArch64CC::CondCode &CondCode,
1375 AArch64CC::CondCode &CondCode2) {
1376 CondCode2 = AArch64CC::AL;
1377 switch (CC) {
1378 default:
1379 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1380 assert(CondCode2 == AArch64CC::AL);
1381 break;
1382 case ISD::SETONE:
1383 // (a one b)
1384 // == ((a olt b) || (a ogt b))
1385 // == ((a ord b) && (a une b))
1386 CondCode = AArch64CC::VC;
1387 CondCode2 = AArch64CC::NE;
1388 break;
1389 case ISD::SETUEQ:
1390 // (a ueq b)
1391 // == ((a uno b) || (a oeq b))
1392 // == ((a ule b) && (a uge b))
1393 CondCode = AArch64CC::PL;
1394 CondCode2 = AArch64CC::LE;
1395 break;
1396 }
1397}
1398
Tim Northover3b0846e2014-05-24 12:50:23 +00001399/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1400/// CC usable with the vector instructions. Fewer operations are available
1401/// without a real NZCV register, so we have to use less efficient combinations
1402/// to get the same effect.
1403static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1404 AArch64CC::CondCode &CondCode,
1405 AArch64CC::CondCode &CondCode2,
1406 bool &Invert) {
1407 Invert = false;
1408 switch (CC) {
1409 default:
1410 // Mostly the scalar mappings work fine.
1411 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1412 break;
1413 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001414 Invert = true;
1415 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001416 case ISD::SETO:
1417 CondCode = AArch64CC::MI;
1418 CondCode2 = AArch64CC::GE;
1419 break;
1420 case ISD::SETUEQ:
1421 case ISD::SETULT:
1422 case ISD::SETULE:
1423 case ISD::SETUGT:
1424 case ISD::SETUGE:
1425 // All of the compare-mask comparisons are ordered, but we can switch
1426 // between the two by a double inversion. E.g. ULE == !OGT.
1427 Invert = true;
1428 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1429 break;
1430 }
1431}
1432
1433static bool isLegalArithImmed(uint64_t C) {
1434 // Matches AArch64DAGToDAGISel::SelectArithImmed().
Sjoerd Meijer24c98182017-08-23 08:18:37 +00001435 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1436 DEBUG(dbgs() << "Is imm " << C << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1437 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00001438}
1439
1440static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001441 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001442 EVT VT = LHS.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001443 const bool FullFP16 =
1444 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
Tim Northover3b0846e2014-05-24 12:50:23 +00001445
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001446 if (VT.isFloatingPoint()) {
1447 assert(VT != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001448 if (VT == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001449 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1450 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001451 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001452 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001453 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001454 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001455
1456 // The CMP instruction is just an alias for SUBS, and representing it as
1457 // SUBS means that it's possible to get CSE with subtract operations.
1458 // A later phase can perform the optimization of setting the destination
1459 // register to WZR/XZR if it ends up being unused.
1460 unsigned Opcode = AArch64ISD::SUBS;
1461
Artyom Skrobov314ee042015-11-25 19:41:11 +00001462 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001463 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1464 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1465 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1466 // can be set differently by this operation. It comes down to whether
1467 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1468 // everything is fine. If not then the optimization is wrong. Thus general
1469 // comparisons are only valid if op2 != 0.
1470
1471 // So, finally, the only LLVM-native comparisons that don't mention C and V
1472 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1473 // the absence of information about op2.
1474 Opcode = AArch64ISD::ADDS;
1475 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001476 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001477 !isUnsignedIntSetCC(CC)) {
1478 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1479 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1480 // of the signed comparisons.
1481 Opcode = AArch64ISD::ANDS;
1482 RHS = LHS.getOperand(1);
1483 LHS = LHS.getOperand(0);
1484 }
1485
Matthias Braunaf7d7702015-07-16 20:02:37 +00001486 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001487 .getValue(1);
1488}
1489
Matthias Braunaf7d7702015-07-16 20:02:37 +00001490/// \defgroup AArch64CCMP CMP;CCMP matching
1491///
1492/// These functions deal with the formation of CMP;CCMP;... sequences.
1493/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1494/// a comparison. They set the NZCV flags to a predefined value if their
1495/// predicate is false. This allows to express arbitrary conjunctions, for
1496/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1497/// expressed as:
1498/// cmp A
1499/// ccmp B, inv(CB), CA
1500/// check for CB flags
1501///
1502/// In general we can create code for arbitrary "... (and (and A B) C)"
1503/// sequences. We can also implement some "or" expressions, because "(or A B)"
1504/// is equivalent to "not (and (not A) (not B))" and we can implement some
1505/// negation operations:
1506/// We can negate the results of a single comparison by inverting the flags
1507/// used when the predicate fails and inverting the flags tested in the next
1508/// instruction; We can also negate the results of the whole previous
1509/// conditional compare sequence by inverting the flags tested in the next
1510/// instruction. However there is no way to negate the result of a partial
1511/// sequence.
1512///
1513/// Therefore on encountering an "or" expression we can negate the subtree on
1514/// one side and have to be able to push the negate to the leafs of the subtree
1515/// on the other side (see also the comments in code). As complete example:
1516/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1517/// (and (setCC (cmp C)) (setCD (cmp D)))"
1518/// is transformed to
1519/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1520/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1521/// and implemented as:
1522/// cmp C
1523/// ccmp D, inv(CD), CC
1524/// ccmp A, CA, inv(CD)
1525/// ccmp B, CB, inv(CA)
1526/// check for CB flags
1527/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1528/// by conditional compare sequences.
1529/// @{
1530
Geoff Berrye41c2df2015-07-20 22:03:52 +00001531/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001532static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1533 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001534 AArch64CC::CondCode Predicate,
1535 AArch64CC::CondCode OutCC,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001536 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001537 unsigned Opcode = 0;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001538 const bool FullFP16 =
1539 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1540
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001541 if (LHS.getValueType().isFloatingPoint()) {
1542 assert(LHS.getValueType() != MVT::f128);
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00001543 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001544 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1545 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1546 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001547 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001548 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001549 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001550 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001551 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1552 Opcode = AArch64ISD::CCMN;
1553 RHS = RHS.getOperand(1);
1554 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001555 }
1556 if (Opcode == 0)
1557 Opcode = AArch64ISD::CCMP;
1558
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001559 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1560 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1561 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001562 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1563 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1564}
1565
1566/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1567/// CanPushNegate is set to true if we can push a negate operation through
1568/// the tree in a was that we are left with AND operations and negate operations
1569/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1570/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1571/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001572static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001573 unsigned Depth = 0) {
1574 if (!Val.hasOneUse())
1575 return false;
1576 unsigned Opcode = Val->getOpcode();
1577 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001578 if (Val->getOperand(0).getValueType() == MVT::f128)
1579 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001580 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001581 return true;
1582 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001583 // Protect against exponential runtime and stack overflow.
1584 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001585 return false;
1586 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1587 SDValue O0 = Val->getOperand(0);
1588 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001589 bool CanNegateL;
1590 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001591 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001592 bool CanNegateR;
1593 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001594 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001595
1596 if (Opcode == ISD::OR) {
1597 // For an OR expression we need to be able to negate at least one side or
1598 // we cannot do the transformation at all.
1599 if (!CanNegateL && !CanNegateR)
1600 return false;
1601 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1602 // can negate the x and y subtrees.
1603 CanNegate = CanNegateL && CanNegateR;
1604 } else {
1605 // If the operands are OR expressions then we finally need to negate their
1606 // outputs, we can only do that for the operand with emitted last by
1607 // negating OutCC, not for both operands.
1608 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1609 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1610 if (NeedsNegOutL && NeedsNegOutR)
1611 return false;
1612 // We cannot negate an AND operation (it would become an OR),
1613 CanNegate = false;
1614 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001615 return true;
1616 }
1617 return false;
1618}
1619
1620/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1621/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1622/// Tries to transform the given i1 producing node @p Val to a series compare
1623/// and conditional compare operations. @returns an NZCV flags producing node
1624/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1625/// transformation was not possible.
1626/// On recursive invocations @p PushNegate may be set to true to have negation
1627/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1628/// for the comparisons in the current subtree; @p Depth limits the search
1629/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001630static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1631 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001632 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001633 // We're at a tree leaf, produce a conditional comparison operation.
1634 unsigned Opcode = Val->getOpcode();
1635 if (Opcode == ISD::SETCC) {
1636 SDValue LHS = Val->getOperand(0);
1637 SDValue RHS = Val->getOperand(1);
1638 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1639 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001640 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001641 CC = getSetCCInverse(CC, isInteger);
1642 SDLoc DL(Val);
1643 // Determine OutCC and handle FP special case.
1644 if (isInteger) {
1645 OutCC = changeIntCCToAArch64CC(CC);
1646 } else {
1647 assert(LHS.getValueType().isFloatingPoint());
1648 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001649 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1650 // Some floating point conditions can't be tested with a single condition
1651 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001652 if (ExtraCC != AArch64CC::AL) {
1653 SDValue ExtraCmp;
1654 if (!CCOp.getNode())
1655 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001656 else
1657 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001658 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001659 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001660 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001661 }
1662 }
1663
1664 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001665 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001666 return emitComparison(LHS, RHS, CC, DL, DAG);
1667 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001668 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001669 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001670 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001671 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1672 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001673
1674 // Check if both sides can be transformed.
1675 SDValue LHS = Val->getOperand(0);
1676 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001677
Matthias Braunfdef49b2016-01-23 04:05:22 +00001678 // In case of an OR we need to negate our operands and the result.
1679 // (A v B) <=> not(not(A) ^ not(B))
1680 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001681 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001682 // predicate flags giving us a free negation for one side. The other side
1683 // must be negatable by itself.
1684 if (NegateOpsAndResult) {
1685 // See which side we can negate.
1686 bool CanNegateL;
1687 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1688 assert(isValidL && "Valid conjunction/disjunction tree");
1689 (void)isValidL;
1690
1691#ifndef NDEBUG
1692 bool CanNegateR;
1693 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1694 assert(isValidR && "Valid conjunction/disjunction tree");
1695 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1696#endif
1697
1698 // Order the side which we cannot negate to RHS so we can emit it first.
1699 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001700 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001701 } else {
1702 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001703 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001704 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001705 // Order the side where we need to negate the output flags to RHS so it
1706 // gets emitted first.
1707 if (NeedsNegOutL)
1708 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001709 }
1710
1711 // Emit RHS. If we want to negate the tree we only need to push a negate
1712 // through if we are already in a PushNegate case, otherwise we can negate
1713 // the "flags to test" afterwards.
1714 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001715 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001716 CCOp, Predicate);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001717 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001718 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001719 // Emit LHS. We may need to negate it.
1720 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1721 NegateOpsAndResult, CmpR,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001722 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001723 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001724 // (or absorb the Negate parameter).
1725 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001726 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1727 return CmpL;
1728}
1729
Matthias Braunfdef49b2016-01-23 04:05:22 +00001730/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1731/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1732/// \see emitConjunctionDisjunctionTreeRec().
1733static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001734 AArch64CC::CondCode &OutCC) {
Matthias Braunfdef49b2016-01-23 04:05:22 +00001735 bool CanNegate;
1736 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1737 return SDValue();
1738
1739 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001740 AArch64CC::AL);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001741}
1742
Matthias Braunaf7d7702015-07-16 20:02:37 +00001743/// @}
1744
Tim Northover3b0846e2014-05-24 12:50:23 +00001745static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001746 SDValue &AArch64cc, SelectionDAG &DAG,
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001747 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001748 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1749 EVT VT = RHS.getValueType();
1750 uint64_t C = RHSC->getZExtValue();
1751 if (!isLegalArithImmed(C)) {
1752 // Constant does not fit, try adjusting it by one?
1753 switch (CC) {
1754 default:
1755 break;
1756 case ISD::SETLT:
1757 case ISD::SETGE:
1758 if ((VT == MVT::i32 && C != 0x80000000 &&
1759 isLegalArithImmed((uint32_t)(C - 1))) ||
1760 (VT == MVT::i64 && C != 0x80000000ULL &&
1761 isLegalArithImmed(C - 1ULL))) {
1762 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1763 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001764 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001765 }
1766 break;
1767 case ISD::SETULT:
1768 case ISD::SETUGE:
1769 if ((VT == MVT::i32 && C != 0 &&
1770 isLegalArithImmed((uint32_t)(C - 1))) ||
1771 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1772 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1773 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001774 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001775 }
1776 break;
1777 case ISD::SETLE:
1778 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001779 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001780 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001781 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001782 isLegalArithImmed(C + 1ULL))) {
1783 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1784 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001785 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001786 }
1787 break;
1788 case ISD::SETULE:
1789 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001790 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001791 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001792 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001793 isLegalArithImmed(C + 1ULL))) {
1794 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1795 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001796 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001797 }
1798 break;
1799 }
1800 }
1801 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001802 SDValue Cmp;
1803 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001804 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001805 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1806
1807 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1808 // For the i8 operand, the largest immediate is 255, so this can be easily
1809 // encoded in the compare instruction. For the i16 operand, however, the
1810 // largest immediate cannot be encoded in the compare.
1811 // Therefore, use a sign extending load and cmn to avoid materializing the
1812 // -1 constant. For example,
1813 // movz w1, #65535
1814 // ldrh w0, [x0, #0]
1815 // cmp w0, w1
1816 // >
1817 // ldrsh w0, [x0, #0]
1818 // cmn w0, #1
1819 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1820 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001821 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001822 // transformation is profitable.
1823 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1824 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1825 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1826 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1827 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1828 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1829 SDValue SExt =
1830 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1831 DAG.getValueType(MVT::i16));
1832 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1833 RHS.getValueType()),
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001834 CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001835 AArch64CC = changeIntCCToAArch64CC(CC);
1836 }
1837 }
1838
1839 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001840 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001841 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1842 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001843 }
1844 }
1845 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001846
1847 if (!Cmp) {
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00001848 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001849 AArch64CC = changeIntCCToAArch64CC(CC);
1850 }
1851 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001852 return Cmp;
1853}
1854
1855static std::pair<SDValue, SDValue>
1856getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1857 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1858 "Unsupported value type");
1859 SDValue Value, Overflow;
1860 SDLoc DL(Op);
1861 SDValue LHS = Op.getOperand(0);
1862 SDValue RHS = Op.getOperand(1);
1863 unsigned Opc = 0;
1864 switch (Op.getOpcode()) {
1865 default:
1866 llvm_unreachable("Unknown overflow instruction!");
1867 case ISD::SADDO:
1868 Opc = AArch64ISD::ADDS;
1869 CC = AArch64CC::VS;
1870 break;
1871 case ISD::UADDO:
1872 Opc = AArch64ISD::ADDS;
1873 CC = AArch64CC::HS;
1874 break;
1875 case ISD::SSUBO:
1876 Opc = AArch64ISD::SUBS;
1877 CC = AArch64CC::VS;
1878 break;
1879 case ISD::USUBO:
1880 Opc = AArch64ISD::SUBS;
1881 CC = AArch64CC::LO;
1882 break;
1883 // Multiply needs a little bit extra work.
1884 case ISD::SMULO:
1885 case ISD::UMULO: {
1886 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001887 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001888 if (Op.getValueType() == MVT::i32) {
1889 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1890 // For a 32 bit multiply with overflow check we want the instruction
1891 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1892 // need to generate the following pattern:
1893 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1894 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1895 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1896 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1897 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001898 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001899 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1900 // operation. We need to clear out the upper 32 bits, because we used a
1901 // widening multiply that wrote all 64 bits. In the end this should be a
1902 // noop.
1903 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1904 if (IsSigned) {
1905 // The signed overflow check requires more than just a simple check for
1906 // any bit set in the upper 32 bits of the result. These bits could be
1907 // just the sign bits of a negative number. To perform the overflow
1908 // check we have to arithmetic shift right the 32nd bit of the result by
1909 // 31 bits. Then we compare the result to the upper 32 bits.
1910 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001911 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001912 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1913 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001914 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001915 // It is important that LowerBits is last, otherwise the arithmetic
1916 // shift will not be folded into the compare (SUBS).
1917 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1918 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1919 .getValue(1);
1920 } else {
1921 // The overflow check for unsigned multiply is easy. We only need to
1922 // check if any of the upper 32 bits are set. This can be done with a
1923 // CMP (shifted register). For that we need to generate the following
1924 // pattern:
1925 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1926 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001927 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001928 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1929 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001930 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1931 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001932 UpperBits).getValue(1);
1933 }
1934 break;
1935 }
1936 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1937 // For the 64 bit multiply
1938 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1939 if (IsSigned) {
1940 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1941 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001942 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001943 // It is important that LowerBits is last, otherwise the arithmetic
1944 // shift will not be folded into the compare (SUBS).
1945 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1946 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1947 .getValue(1);
1948 } else {
1949 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1950 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1951 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001952 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1953 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001954 UpperBits).getValue(1);
1955 }
1956 break;
1957 }
1958 } // switch (...)
1959
1960 if (Opc) {
1961 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1962
1963 // Emit the AArch64 operation with overflow check.
1964 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1965 Overflow = Value.getValue(1);
1966 }
1967 return std::make_pair(Value, Overflow);
1968}
1969
1970SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1971 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001972 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001973 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001974}
1975
Amara Emerson24ca39c2017-10-09 15:15:09 +00001976// Returns true if the given Op is the overflow flag result of an overflow
1977// intrinsic operation.
1978static bool isOverflowIntrOpRes(SDValue Op) {
1979 unsigned Opc = Op.getOpcode();
1980 return (Op.getResNo() == 1 &&
1981 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
1982 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
1983}
1984
Tim Northover3b0846e2014-05-24 12:50:23 +00001985static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1986 SDValue Sel = Op.getOperand(0);
1987 SDValue Other = Op.getOperand(1);
Amara Emerson24ca39c2017-10-09 15:15:09 +00001988 SDLoc dl(Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00001989
Amara Emerson24ca39c2017-10-09 15:15:09 +00001990 // If the operand is an overflow checking operation, invert the condition
1991 // code and kill the Not operation. I.e., transform:
1992 // (xor (overflow_op_bool, 1))
1993 // -->
1994 // (csel 1, 0, invert(cc), overflow_op_bool)
1995 // ... which later gets transformed to just a cset instruction with an
1996 // inverted condition code, rather than a cset + eor sequence.
1997 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
1998 // Only lower legal XALUO ops.
1999 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2000 return SDValue();
2001
2002 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2003 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2004 AArch64CC::CondCode CC;
2005 SDValue Value, Overflow;
2006 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2007 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2008 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2009 CCVal, Overflow);
2010 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002011 // If neither operand is a SELECT_CC, give up.
2012 if (Sel.getOpcode() != ISD::SELECT_CC)
2013 std::swap(Sel, Other);
2014 if (Sel.getOpcode() != ISD::SELECT_CC)
2015 return Op;
2016
2017 // The folding we want to perform is:
2018 // (xor x, (select_cc a, b, cc, 0, -1) )
2019 // -->
2020 // (csel x, (xor x, -1), cc ...)
2021 //
2022 // The latter will get matched to a CSINV instruction.
2023
2024 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2025 SDValue LHS = Sel.getOperand(0);
2026 SDValue RHS = Sel.getOperand(1);
2027 SDValue TVal = Sel.getOperand(2);
2028 SDValue FVal = Sel.getOperand(3);
Tim Northover3b0846e2014-05-24 12:50:23 +00002029
2030 // FIXME: This could be generalized to non-integer comparisons.
2031 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2032 return Op;
2033
2034 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2035 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2036
Eric Christopher572e03a2015-06-19 01:53:21 +00002037 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00002038 if (!CFVal || !CTVal)
2039 return Op;
2040
2041 // We can commute the SELECT_CC by inverting the condition. This
2042 // might be needed to make this fit into a CSINV pattern.
2043 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2044 std::swap(TVal, FVal);
2045 std::swap(CTVal, CFVal);
2046 CC = ISD::getSetCCInverse(CC, true);
2047 }
2048
2049 // If the constants line up, perform the transform!
2050 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2051 SDValue CCVal;
2052 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2053
2054 FVal = Other;
2055 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002056 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002057
2058 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2059 CCVal, Cmp);
2060 }
2061
2062 return Op;
2063}
2064
2065static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2066 EVT VT = Op.getValueType();
2067
2068 // Let legalize expand this if it isn't a legal type yet.
2069 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2070 return SDValue();
2071
2072 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2073
2074 unsigned Opc;
2075 bool ExtraOp = false;
2076 switch (Op.getOpcode()) {
2077 default:
Craig Topper2a30d782014-06-18 05:05:13 +00002078 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00002079 case ISD::ADDC:
2080 Opc = AArch64ISD::ADDS;
2081 break;
2082 case ISD::SUBC:
2083 Opc = AArch64ISD::SUBS;
2084 break;
2085 case ISD::ADDE:
2086 Opc = AArch64ISD::ADCS;
2087 ExtraOp = true;
2088 break;
2089 case ISD::SUBE:
2090 Opc = AArch64ISD::SBCS;
2091 ExtraOp = true;
2092 break;
2093 }
2094
2095 if (!ExtraOp)
2096 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2097 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2098 Op.getOperand(2));
2099}
2100
2101static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2102 // Let legalize expand this if it isn't a legal type yet.
2103 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2104 return SDValue();
2105
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002106 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00002107 AArch64CC::CondCode CC;
2108 // The actual operation that sets the overflow or carry flag.
2109 SDValue Value, Overflow;
2110 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2111
2112 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002113 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2114 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00002115
2116 // We use an inverted condition, because the conditional select is inverted
2117 // too. This will allow it to be selected to a single instruction:
2118 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002119 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2120 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00002121 CCVal, Overflow);
2122
2123 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002124 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00002125}
2126
2127// Prefetch operands are:
2128// 1: Address to prefetch
2129// 2: bool isWrite
2130// 3: int locality (0 = no locality ... 3 = extreme locality)
2131// 4: bool isDataCache
2132static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2133 SDLoc DL(Op);
2134 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2135 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00002136 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00002137
2138 bool IsStream = !Locality;
2139 // When the locality number is set
2140 if (Locality) {
2141 // The front-end should have filtered out the out-of-range values
2142 assert(Locality <= 3 && "Prefetch locality out-of-range");
2143 // The locality degree is the opposite of the cache speed.
2144 // Put the number the other way around.
2145 // The encoding starts at 0 for level 1
2146 Locality = 3 - Locality;
2147 }
2148
2149 // built the mask value encoding the expected behavior.
2150 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00002151 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00002152 (Locality << 1) | // Cache level bits
2153 (unsigned)IsStream; // Stream bit
2154 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002155 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00002156}
2157
2158SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2159 SelectionDAG &DAG) const {
2160 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2161
2162 RTLIB::Libcall LC;
2163 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2164
2165 return LowerF128Call(Op, DAG, LC);
2166}
2167
2168SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2169 SelectionDAG &DAG) const {
2170 if (Op.getOperand(0).getValueType() != MVT::f128) {
2171 // It's legal except when f128 is involved
2172 return Op;
2173 }
2174
2175 RTLIB::Libcall LC;
2176 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2177
2178 // FP_ROUND node has a second operand indicating whether it is known to be
2179 // precise. That doesn't take part in the LibCall so we can't directly use
2180 // LowerF128Call.
2181 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00002182 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2183 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002184}
2185
2186static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2187 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2188 // Any additional optimization in this function should be recorded
2189 // in the cost tables.
2190 EVT InVT = Op.getOperand(0).getValueType();
2191 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00002192 unsigned NumElts = InVT.getVectorNumElements();
2193
2194 // f16 vectors are promoted to f32 before a conversion.
2195 if (InVT.getVectorElementType() == MVT::f16) {
2196 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2197 SDLoc dl(Op);
2198 return DAG.getNode(
2199 Op.getOpcode(), dl, Op.getValueType(),
2200 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2201 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002202
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002203 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002204 SDLoc dl(Op);
2205 SDValue Cv =
2206 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2207 Op.getOperand(0));
2208 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002209 }
2210
2211 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002212 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002213 MVT ExtVT =
2214 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2215 VT.getVectorNumElements());
2216 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002217 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2218 }
2219
2220 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002221 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002222}
2223
2224SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2225 SelectionDAG &DAG) const {
2226 if (Op.getOperand(0).getValueType().isVector())
2227 return LowerVectorFP_TO_INT(Op, DAG);
2228
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002229 // f16 conversions are promoted to f32 when full fp16 is not supported.
2230 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2231 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002232 SDLoc dl(Op);
2233 return DAG.getNode(
2234 Op.getOpcode(), dl, Op.getValueType(),
2235 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2236 }
2237
Tim Northover3b0846e2014-05-24 12:50:23 +00002238 if (Op.getOperand(0).getValueType() != MVT::f128) {
2239 // It's legal except when f128 is involved
2240 return Op;
2241 }
2242
2243 RTLIB::Libcall LC;
2244 if (Op.getOpcode() == ISD::FP_TO_SINT)
2245 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2246 else
2247 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2248
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002249 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002250 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002251}
2252
2253static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2254 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2255 // Any additional optimization in this function should be recorded
2256 // in the cost tables.
2257 EVT VT = Op.getValueType();
2258 SDLoc dl(Op);
2259 SDValue In = Op.getOperand(0);
2260 EVT InVT = In.getValueType();
2261
Tim Northoveref0d7602014-06-15 09:27:06 +00002262 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2263 MVT CastVT =
2264 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2265 InVT.getVectorNumElements());
2266 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002267 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002268 }
2269
Tim Northoveref0d7602014-06-15 09:27:06 +00002270 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2271 unsigned CastOpc =
2272 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2273 EVT CastVT = VT.changeVectorElementTypeToInteger();
2274 In = DAG.getNode(CastOpc, dl, CastVT, In);
2275 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002276 }
2277
Tim Northoveref0d7602014-06-15 09:27:06 +00002278 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002279}
2280
2281SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2282 SelectionDAG &DAG) const {
2283 if (Op.getValueType().isVector())
2284 return LowerVectorINT_TO_FP(Op, DAG);
2285
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00002286 // f16 conversions are promoted to f32 when full fp16 is not supported.
2287 if (Op.getValueType() == MVT::f16 &&
2288 !Subtarget->hasFullFP16()) {
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002289 SDLoc dl(Op);
2290 return DAG.getNode(
2291 ISD::FP_ROUND, dl, MVT::f16,
2292 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002293 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002294 }
2295
Tim Northover3b0846e2014-05-24 12:50:23 +00002296 // i128 conversions are libcalls.
2297 if (Op.getOperand(0).getValueType() == MVT::i128)
2298 return SDValue();
2299
2300 // Other conversions are legal, unless it's to the completely software-based
2301 // fp128.
2302 if (Op.getValueType() != MVT::f128)
2303 return Op;
2304
2305 RTLIB::Libcall LC;
2306 if (Op.getOpcode() == ISD::SINT_TO_FP)
2307 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2308 else
2309 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2310
2311 return LowerF128Call(Op, DAG, LC);
2312}
2313
2314SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2315 SelectionDAG &DAG) const {
2316 // For iOS, we want to call an alternative entry point: __sincos_stret,
2317 // which returns the values in two S / D registers.
2318 SDLoc dl(Op);
2319 SDValue Arg = Op.getOperand(0);
2320 EVT ArgVT = Arg.getValueType();
2321 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2322
2323 ArgListTy Args;
2324 ArgListEntry Entry;
2325
2326 Entry.Node = Arg;
2327 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002328 Entry.IsSExt = false;
2329 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002330 Args.push_back(Entry);
2331
Matthias Brauna4852d2c2017-12-18 23:19:42 +00002332 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2333 : RTLIB::SINCOS_STRET_F32;
2334 const char *LibcallName = getLibcallName(LC);
Mehdi Amini44ede332015-07-09 02:09:04 +00002335 SDValue Callee =
2336 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002337
Serge Gueltone38003f2017-05-09 19:31:13 +00002338 StructType *RetTy = StructType::get(ArgTy, ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00002339 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002340 CLI.setDebugLoc(dl)
2341 .setChain(DAG.getEntryNode())
2342 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002343
2344 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2345 return CallResult.first;
2346}
2347
Tim Northoverf8bfe212014-07-18 13:07:05 +00002348static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2349 if (Op.getValueType() != MVT::f16)
2350 return SDValue();
2351
2352 assert(Op.getOperand(0).getValueType() == MVT::i16);
2353 SDLoc DL(Op);
2354
2355 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2356 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2357 return SDValue(
2358 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002359 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002360 0);
2361}
2362
Chad Rosierd9d0f862014-10-08 02:31:24 +00002363static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2364 if (OrigVT.getSizeInBits() >= 64)
2365 return OrigVT;
2366
2367 assert(OrigVT.isSimple() && "Expecting a simple value type");
2368
2369 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2370 switch (OrigSimpleTy) {
2371 default: llvm_unreachable("Unexpected Vector Type");
2372 case MVT::v2i8:
2373 case MVT::v2i16:
2374 return MVT::v2i32;
2375 case MVT::v4i8:
2376 return MVT::v4i16;
2377 }
2378}
2379
2380static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2381 const EVT &OrigTy,
2382 const EVT &ExtTy,
2383 unsigned ExtOpcode) {
2384 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2385 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2386 // 64-bits we need to insert a new extension so that it will be 64-bits.
2387 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2388 if (OrigTy.getSizeInBits() >= 64)
2389 return N;
2390
2391 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2392 EVT NewVT = getExtensionTo64Bits(OrigTy);
2393
2394 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2395}
2396
2397static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2398 bool isSigned) {
2399 EVT VT = N->getValueType(0);
2400
2401 if (N->getOpcode() != ISD::BUILD_VECTOR)
2402 return false;
2403
Pete Cooper3af9a252015-06-26 18:17:36 +00002404 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002405 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002406 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002407 unsigned HalfSize = EltSize / 2;
2408 if (isSigned) {
2409 if (!isIntN(HalfSize, C->getSExtValue()))
2410 return false;
2411 } else {
2412 if (!isUIntN(HalfSize, C->getZExtValue()))
2413 return false;
2414 }
2415 continue;
2416 }
2417 return false;
2418 }
2419
2420 return true;
2421}
2422
2423static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2424 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2425 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2426 N->getOperand(0)->getValueType(0),
2427 N->getValueType(0),
2428 N->getOpcode());
2429
2430 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2431 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002432 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002433 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002434 unsigned NumElts = VT.getVectorNumElements();
2435 MVT TruncVT = MVT::getIntegerVT(EltSize);
2436 SmallVector<SDValue, 8> Ops;
2437 for (unsigned i = 0; i != NumElts; ++i) {
2438 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2439 const APInt &CInt = C->getAPIntValue();
2440 // Element types smaller than 32 bits are not legal, so use i32 elements.
2441 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002442 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002443 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002444 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002445}
2446
2447static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002448 return N->getOpcode() == ISD::SIGN_EXTEND ||
2449 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002450}
2451
2452static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002453 return N->getOpcode() == ISD::ZERO_EXTEND ||
2454 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002455}
2456
2457static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2458 unsigned Opcode = N->getOpcode();
2459 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2460 SDNode *N0 = N->getOperand(0).getNode();
2461 SDNode *N1 = N->getOperand(1).getNode();
2462 return N0->hasOneUse() && N1->hasOneUse() &&
2463 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2464 }
2465 return false;
2466}
2467
2468static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2469 unsigned Opcode = N->getOpcode();
2470 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2471 SDNode *N0 = N->getOperand(0).getNode();
2472 SDNode *N1 = N->getOperand(1).getNode();
2473 return N0->hasOneUse() && N1->hasOneUse() &&
2474 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2475 }
2476 return false;
2477}
2478
2479static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2480 // Multiplications are only custom-lowered for 128-bit vectors so that
2481 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2482 EVT VT = Op.getValueType();
2483 assert(VT.is128BitVector() && VT.isInteger() &&
2484 "unexpected type for custom-lowering ISD::MUL");
2485 SDNode *N0 = Op.getOperand(0).getNode();
2486 SDNode *N1 = Op.getOperand(1).getNode();
2487 unsigned NewOpc = 0;
2488 bool isMLA = false;
2489 bool isN0SExt = isSignExtended(N0, DAG);
2490 bool isN1SExt = isSignExtended(N1, DAG);
2491 if (isN0SExt && isN1SExt)
2492 NewOpc = AArch64ISD::SMULL;
2493 else {
2494 bool isN0ZExt = isZeroExtended(N0, DAG);
2495 bool isN1ZExt = isZeroExtended(N1, DAG);
2496 if (isN0ZExt && isN1ZExt)
2497 NewOpc = AArch64ISD::UMULL;
2498 else if (isN1SExt || isN1ZExt) {
2499 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2500 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2501 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2502 NewOpc = AArch64ISD::SMULL;
2503 isMLA = true;
2504 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2505 NewOpc = AArch64ISD::UMULL;
2506 isMLA = true;
2507 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2508 std::swap(N0, N1);
2509 NewOpc = AArch64ISD::UMULL;
2510 isMLA = true;
2511 }
2512 }
2513
2514 if (!NewOpc) {
2515 if (VT == MVT::v2i64)
2516 // Fall through to expand this. It is not legal.
2517 return SDValue();
2518 else
2519 // Other vector multiplications are legal.
2520 return Op;
2521 }
2522 }
2523
2524 // Legalize to a S/UMULL instruction
2525 SDLoc DL(Op);
2526 SDValue Op0;
2527 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2528 if (!isMLA) {
2529 Op0 = skipExtensionForVectorMULL(N0, DAG);
2530 assert(Op0.getValueType().is64BitVector() &&
2531 Op1.getValueType().is64BitVector() &&
2532 "unexpected types for extended operands to VMULL");
2533 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2534 }
2535 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2536 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2537 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2538 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2539 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2540 EVT Op1VT = Op1.getValueType();
2541 return DAG.getNode(N0->getOpcode(), DL, VT,
2542 DAG.getNode(NewOpc, DL, VT,
2543 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2544 DAG.getNode(NewOpc, DL, VT,
2545 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2546}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002547
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002548SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2549 SelectionDAG &DAG) const {
2550 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2551 SDLoc dl(Op);
2552 switch (IntNo) {
2553 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002554 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002555 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2556 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2557 }
Simon Pilgrim7a28a3a2017-05-08 10:25:18 +00002558 case Intrinsic::aarch64_neon_abs:
2559 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2560 Op.getOperand(1));
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002561 case Intrinsic::aarch64_neon_smax:
2562 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2563 Op.getOperand(1), Op.getOperand(2));
2564 case Intrinsic::aarch64_neon_umax:
2565 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2566 Op.getOperand(1), Op.getOperand(2));
2567 case Intrinsic::aarch64_neon_smin:
2568 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2569 Op.getOperand(1), Op.getOperand(2));
2570 case Intrinsic::aarch64_neon_umin:
2571 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2572 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002573 }
2574}
2575
Tim Northover3b0846e2014-05-24 12:50:23 +00002576SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2577 SelectionDAG &DAG) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00002578 DEBUG(dbgs() << "Custom lowering: ");
2579 DEBUG(Op.dump());
2580
Tim Northover3b0846e2014-05-24 12:50:23 +00002581 switch (Op.getOpcode()) {
2582 default:
2583 llvm_unreachable("unimplemented operand");
2584 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002585 case ISD::BITCAST:
2586 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002587 case ISD::GlobalAddress:
2588 return LowerGlobalAddress(Op, DAG);
2589 case ISD::GlobalTLSAddress:
2590 return LowerGlobalTLSAddress(Op, DAG);
2591 case ISD::SETCC:
2592 return LowerSETCC(Op, DAG);
2593 case ISD::BR_CC:
2594 return LowerBR_CC(Op, DAG);
2595 case ISD::SELECT:
2596 return LowerSELECT(Op, DAG);
2597 case ISD::SELECT_CC:
2598 return LowerSELECT_CC(Op, DAG);
2599 case ISD::JumpTable:
2600 return LowerJumpTable(Op, DAG);
2601 case ISD::ConstantPool:
2602 return LowerConstantPool(Op, DAG);
2603 case ISD::BlockAddress:
2604 return LowerBlockAddress(Op, DAG);
2605 case ISD::VASTART:
2606 return LowerVASTART(Op, DAG);
2607 case ISD::VACOPY:
2608 return LowerVACOPY(Op, DAG);
2609 case ISD::VAARG:
2610 return LowerVAARG(Op, DAG);
2611 case ISD::ADDC:
2612 case ISD::ADDE:
2613 case ISD::SUBC:
2614 case ISD::SUBE:
2615 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2616 case ISD::SADDO:
2617 case ISD::UADDO:
2618 case ISD::SSUBO:
2619 case ISD::USUBO:
2620 case ISD::SMULO:
2621 case ISD::UMULO:
2622 return LowerXALUO(Op, DAG);
2623 case ISD::FADD:
2624 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2625 case ISD::FSUB:
2626 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2627 case ISD::FMUL:
2628 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2629 case ISD::FDIV:
2630 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2631 case ISD::FP_ROUND:
2632 return LowerFP_ROUND(Op, DAG);
2633 case ISD::FP_EXTEND:
2634 return LowerFP_EXTEND(Op, DAG);
2635 case ISD::FRAMEADDR:
2636 return LowerFRAMEADDR(Op, DAG);
2637 case ISD::RETURNADDR:
2638 return LowerRETURNADDR(Op, DAG);
2639 case ISD::INSERT_VECTOR_ELT:
2640 return LowerINSERT_VECTOR_ELT(Op, DAG);
2641 case ISD::EXTRACT_VECTOR_ELT:
2642 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2643 case ISD::BUILD_VECTOR:
2644 return LowerBUILD_VECTOR(Op, DAG);
2645 case ISD::VECTOR_SHUFFLE:
2646 return LowerVECTOR_SHUFFLE(Op, DAG);
2647 case ISD::EXTRACT_SUBVECTOR:
2648 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2649 case ISD::SRA:
2650 case ISD::SRL:
2651 case ISD::SHL:
2652 return LowerVectorSRA_SRL_SHL(Op, DAG);
2653 case ISD::SHL_PARTS:
2654 return LowerShiftLeftParts(Op, DAG);
2655 case ISD::SRL_PARTS:
2656 case ISD::SRA_PARTS:
2657 return LowerShiftRightParts(Op, DAG);
2658 case ISD::CTPOP:
2659 return LowerCTPOP(Op, DAG);
2660 case ISD::FCOPYSIGN:
2661 return LowerFCOPYSIGN(Op, DAG);
2662 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002663 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002664 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002665 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002666 case ISD::XOR:
2667 return LowerXOR(Op, DAG);
2668 case ISD::PREFETCH:
2669 return LowerPREFETCH(Op, DAG);
2670 case ISD::SINT_TO_FP:
2671 case ISD::UINT_TO_FP:
2672 return LowerINT_TO_FP(Op, DAG);
2673 case ISD::FP_TO_SINT:
2674 case ISD::FP_TO_UINT:
2675 return LowerFP_TO_INT(Op, DAG);
2676 case ISD::FSINCOS:
2677 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002678 case ISD::MUL:
2679 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002680 case ISD::INTRINSIC_WO_CHAIN:
2681 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +00002682 case ISD::VECREDUCE_ADD:
2683 case ISD::VECREDUCE_SMAX:
2684 case ISD::VECREDUCE_SMIN:
2685 case ISD::VECREDUCE_UMAX:
2686 case ISD::VECREDUCE_UMIN:
2687 case ISD::VECREDUCE_FMAX:
2688 case ISD::VECREDUCE_FMIN:
2689 return LowerVECREDUCE(Op, DAG);
Oliver Stannard42699172018-02-12 14:22:03 +00002690 case ISD::ATOMIC_LOAD_SUB:
2691 return LowerATOMIC_LOAD_SUB(Op, DAG);
Oliver Stannard02f08c92018-02-12 17:03:11 +00002692 case ISD::ATOMIC_LOAD_AND:
2693 return LowerATOMIC_LOAD_AND(Op, DAG);
Martin Storsjoa63a5b92018-02-17 14:26:32 +00002694 case ISD::DYNAMIC_STACKALLOC:
2695 return LowerDYNAMIC_STACKALLOC(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002696 }
2697}
2698
Tim Northover3b0846e2014-05-24 12:50:23 +00002699//===----------------------------------------------------------------------===//
2700// Calling Convention Implementation
2701//===----------------------------------------------------------------------===//
2702
2703#include "AArch64GenCallingConv.inc"
2704
Robin Morisset039781e2014-08-29 21:53:01 +00002705/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002706CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2707 bool IsVarArg) const {
2708 switch (CC) {
2709 default:
Alex Bradbury080f6972017-08-22 09:11:41 +00002710 report_fatal_error("Unsupported calling convention.");
Tim Northover3b0846e2014-05-24 12:50:23 +00002711 case CallingConv::WebKit_JS:
2712 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002713 case CallingConv::GHC:
2714 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002715 case CallingConv::C:
2716 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002717 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002718 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002719 case CallingConv::Swift:
Martin Storsjo68266fa2017-07-13 17:03:12 +00002720 if (Subtarget->isTargetWindows() && IsVarArg)
2721 return CC_AArch64_Win64_VarArg;
Tim Northover3b0846e2014-05-24 12:50:23 +00002722 if (!Subtarget->isTargetDarwin())
2723 return CC_AArch64_AAPCS;
2724 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
Martin Storsjo2f24e932017-07-17 20:05:19 +00002725 case CallingConv::Win64:
2726 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
Tim Northover3b0846e2014-05-24 12:50:23 +00002727 }
2728}
2729
Tim Northover406024a2016-08-10 21:44:01 +00002730CCAssignFn *
2731AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2732 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2733 : RetCC_AArch64_AAPCS;
2734}
2735
Tim Northover3b0846e2014-05-24 12:50:23 +00002736SDValue AArch64TargetLowering::LowerFormalArguments(
2737 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002738 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2739 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002740 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002741 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00002742 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00002743
2744 // Assign locations to all of the incoming arguments.
2745 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002746 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2747 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002748
2749 // At this point, Ins[].VT may already be promoted to i32. To correctly
2750 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2751 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2752 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2753 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2754 // LocVT.
2755 unsigned NumArgs = Ins.size();
Matthias Braunf1caa282017-12-15 22:22:58 +00002756 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
Tim Northover3b0846e2014-05-24 12:50:23 +00002757 unsigned CurArgIdx = 0;
2758 for (unsigned i = 0; i != NumArgs; ++i) {
2759 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002760 if (Ins[i].isOrigArg()) {
2761 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2762 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002763
Andrew Trick05938a52015-02-16 18:10:47 +00002764 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002765 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2766 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002767 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2768 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2769 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2770 ValVT = MVT::i8;
2771 else if (ActualMVT == MVT::i16)
2772 ValVT = MVT::i16;
2773 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002774 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2775 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002776 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002777 assert(!Res && "Call operand has unhandled type");
2778 (void)Res;
2779 }
2780 assert(ArgLocs.size() == Ins.size());
2781 SmallVector<SDValue, 16> ArgValues;
2782 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2783 CCValAssign &VA = ArgLocs[i];
2784
2785 if (Ins[i].Flags.isByVal()) {
2786 // Byval is used for HFAs in the PCS, but the system should work in a
2787 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002788 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002789 int Size = Ins[i].Flags.getByValSize();
2790 unsigned NumRegs = (Size + 7) / 8;
2791
2792 // FIXME: This works on big-endian for composite byvals, which are the common
2793 // case. It should also work for fundamental types too.
2794 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002795 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002796 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002797 InVals.push_back(FrameIdxN);
2798
2799 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002800 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002801
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002802 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002803 // Arguments stored in registers.
2804 EVT RegVT = VA.getLocVT();
2805
2806 SDValue ArgValue;
2807 const TargetRegisterClass *RC;
2808
2809 if (RegVT == MVT::i32)
2810 RC = &AArch64::GPR32RegClass;
2811 else if (RegVT == MVT::i64)
2812 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002813 else if (RegVT == MVT::f16)
2814 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002815 else if (RegVT == MVT::f32)
2816 RC = &AArch64::FPR32RegClass;
2817 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2818 RC = &AArch64::FPR64RegClass;
2819 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2820 RC = &AArch64::FPR128RegClass;
2821 else
2822 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2823
2824 // Transform the arguments in physical registers into virtual ones.
2825 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2826 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2827
2828 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2829 // to 64 bits. Insert an assert[sz]ext to capture this, then
2830 // truncate to the right size.
2831 switch (VA.getLocInfo()) {
2832 default:
2833 llvm_unreachable("Unknown loc info!");
2834 case CCValAssign::Full:
2835 break;
2836 case CCValAssign::BCvt:
2837 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2838 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002839 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002840 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002841 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002842 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2843 // nodes after our lowering.
2844 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002845 break;
2846 }
2847
2848 InVals.push_back(ArgValue);
2849
2850 } else { // VA.isRegLoc()
2851 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2852 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002853 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002854
2855 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002856 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2857 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002858 BEAlign = 8 - ArgSize;
2859
Matthias Braun941a7052016-07-28 18:40:00 +00002860 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002861
2862 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002863 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002864 SDValue ArgValue;
2865
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002866 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002867 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002868 MVT MemVT = VA.getValVT();
2869
Tim Northover47e003c2014-05-26 17:21:53 +00002870 switch (VA.getLocInfo()) {
2871 default:
2872 break;
Tim Northover6890add2014-06-03 13:54:53 +00002873 case CCValAssign::BCvt:
2874 MemVT = VA.getLocVT();
2875 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002876 case CCValAssign::SExt:
2877 ExtType = ISD::SEXTLOAD;
2878 break;
2879 case CCValAssign::ZExt:
2880 ExtType = ISD::ZEXTLOAD;
2881 break;
2882 case CCValAssign::AExt:
2883 ExtType = ISD::EXTLOAD;
2884 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002885 }
2886
Alex Lorenze40c8a22015-08-11 23:09:45 +00002887 ArgValue = DAG.getExtLoad(
2888 ExtType, DL, VA.getLocVT(), Chain, FIN,
2889 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002890 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002891
Tim Northover3b0846e2014-05-24 12:50:23 +00002892 InVals.push_back(ArgValue);
2893 }
2894 }
2895
2896 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002897 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002898 if (isVarArg) {
Martin Storsjo2f24e932017-07-17 20:05:19 +00002899 if (!Subtarget->isTargetDarwin() || IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002900 // The AAPCS variadic function ABI is identical to the non-variadic
2901 // one. As a result there may be more arguments in registers and we should
2902 // save them for future reference.
Martin Storsjo68266fa2017-07-13 17:03:12 +00002903 // Win64 variadic functions also pass arguments in registers, but all float
2904 // arguments are passed in integer registers.
Tim Northover3b0846e2014-05-24 12:50:23 +00002905 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2906 }
2907
Tim Northover3b0846e2014-05-24 12:50:23 +00002908 // This will point to the next argument passed via stack.
2909 unsigned StackOffset = CCInfo.getNextStackOffset();
2910 // We currently pass all varargs at 8-byte alignment.
2911 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002912 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002913 }
2914
Tim Northover3b0846e2014-05-24 12:50:23 +00002915 unsigned StackArgSize = CCInfo.getNextStackOffset();
2916 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2917 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2918 // This is a non-standard ABI so by fiat I say we're allowed to make full
2919 // use of the stack area to be popped, which must be aligned to 16 bytes in
2920 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002921 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002922
2923 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2924 // a multiple of 16.
2925 FuncInfo->setArgumentStackToRestore(StackArgSize);
2926
2927 // This realignment carries over to the available bytes below. Our own
2928 // callers will guarantee the space is free by giving an aligned value to
2929 // CALLSEQ_START.
2930 }
2931 // Even if we're not expected to free up the space, it's useful to know how
2932 // much is there while considering tail calls (because we can reuse it).
2933 FuncInfo->setBytesInStackArgArea(StackArgSize);
2934
2935 return Chain;
2936}
2937
2938void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002939 SelectionDAG &DAG,
2940 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002941 SDValue &Chain) const {
2942 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002943 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002944 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002945 auto PtrVT = getPointerTy(DAG.getDataLayout());
Matthias Braunf1caa282017-12-15 22:22:58 +00002946 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
Tim Northover3b0846e2014-05-24 12:50:23 +00002947
2948 SmallVector<SDValue, 8> MemOps;
2949
2950 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2951 AArch64::X3, AArch64::X4, AArch64::X5,
2952 AArch64::X6, AArch64::X7 };
2953 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002954 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002955
2956 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2957 int GPRIdx = 0;
2958 if (GPRSaveSize != 0) {
Martin Storsjo8cb36672017-07-25 05:20:01 +00002959 if (IsWin64) {
Martin Storsjo68266fa2017-07-13 17:03:12 +00002960 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
Martin Storsjo8cb36672017-07-25 05:20:01 +00002961 if (GPRSaveSize & 15)
2962 // The extra size here, if triggered, will always be 8.
2963 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
2964 } else
Martin Storsjo68266fa2017-07-13 17:03:12 +00002965 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002966
Mehdi Amini44ede332015-07-09 02:09:04 +00002967 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002968
2969 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2970 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2971 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002972 SDValue Store = DAG.getStore(
2973 Val.getValue(1), DL, Val, FIN,
Martin Storsjo2f24e932017-07-17 20:05:19 +00002974 IsWin64
Martin Storsjo68266fa2017-07-13 17:03:12 +00002975 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2976 GPRIdx,
2977 (i - FirstVariadicGPR) * 8)
2978 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002979 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002980 FIN =
2981 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002982 }
2983 }
2984 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2985 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2986
Martin Storsjo2f24e932017-07-17 20:05:19 +00002987 if (Subtarget->hasFPARMv8() && !IsWin64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002988 static const MCPhysReg FPRArgRegs[] = {
2989 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2990 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2991 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002992 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002993
2994 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2995 int FPRIdx = 0;
2996 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002997 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002998
Mehdi Amini44ede332015-07-09 02:09:04 +00002999 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003000
3001 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3002 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3003 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3004
Alex Lorenze40c8a22015-08-11 23:09:45 +00003005 SDValue Store = DAG.getStore(
3006 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00003007 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00003008 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00003009 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3010 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00003011 }
3012 }
3013 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3014 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3015 }
3016
3017 if (!MemOps.empty()) {
3018 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3019 }
3020}
3021
3022/// LowerCallResult - Lower the result values of a call into the
3023/// appropriate copies out of appropriate physical registers.
3024SDValue AArch64TargetLowering::LowerCallResult(
3025 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003026 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3027 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00003028 SDValue ThisVal) const {
3029 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3030 ? RetCC_AArch64_WebKit_JS
3031 : RetCC_AArch64_AAPCS;
3032 // Assign locations to each value returned by this call.
3033 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003034 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3035 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003036 CCInfo.AnalyzeCallResult(Ins, RetCC);
3037
3038 // Copy all of the result registers out of their specified physreg.
3039 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3040 CCValAssign VA = RVLocs[i];
3041
3042 // Pass 'this' value directly from the argument to return value, to avoid
3043 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00003044 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003045 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3046 "unexpected return calling convention register assignment");
3047 InVals.push_back(ThisVal);
3048 continue;
3049 }
3050
3051 SDValue Val =
3052 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3053 Chain = Val.getValue(1);
3054 InFlag = Val.getValue(2);
3055
3056 switch (VA.getLocInfo()) {
3057 default:
3058 llvm_unreachable("Unknown loc info!");
3059 case CCValAssign::Full:
3060 break;
3061 case CCValAssign::BCvt:
3062 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3063 break;
3064 }
3065
3066 InVals.push_back(Val);
3067 }
3068
3069 return Chain;
3070}
3071
Matthias Braun1af14142016-09-13 19:27:38 +00003072/// Return true if the calling convention is one that we can guarantee TCO for.
3073static bool canGuaranteeTCO(CallingConv::ID CC) {
3074 return CC == CallingConv::Fast;
3075}
3076
3077/// Return true if we might ever do TCO for calls with this calling convention.
3078static bool mayTailCallThisCC(CallingConv::ID CC) {
3079 switch (CC) {
3080 case CallingConv::C:
3081 case CallingConv::PreserveMost:
3082 case CallingConv::Swift:
3083 return true;
3084 default:
3085 return canGuaranteeTCO(CC);
3086 }
3087}
3088
Tim Northover3b0846e2014-05-24 12:50:23 +00003089bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3090 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00003091 const SmallVectorImpl<ISD::OutputArg> &Outs,
3092 const SmallVectorImpl<SDValue> &OutVals,
3093 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00003094 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00003095 return false;
3096
Matthias Braun8d414362016-03-30 22:46:04 +00003097 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braunf1caa282017-12-15 22:22:58 +00003098 const Function &CallerF = MF.getFunction();
3099 CallingConv::ID CallerCC = CallerF.getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00003100 bool CCMatch = CallerCC == CalleeCC;
3101
3102 // Byval parameters hand the function a pointer directly into the stack area
3103 // we want to reuse during a tail call. Working around this *is* possible (see
3104 // X86) but less efficient and uglier in LowerCall.
Matthias Braunf1caa282017-12-15 22:22:58 +00003105 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3106 e = CallerF.arg_end();
Tim Northover3b0846e2014-05-24 12:50:23 +00003107 i != e; ++i)
3108 if (i->hasByValAttr())
3109 return false;
3110
Matthias Braun1af14142016-09-13 19:27:38 +00003111 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3112 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00003113
Oliver Stannard12993dd2014-08-18 12:42:15 +00003114 // Externally-defined functions with weak linkage should not be
3115 // tail-called on AArch64 when the OS does not support dynamic
3116 // pre-emption of symbols, as the AAELF spec requires normal calls
3117 // to undefined weak functions to be replaced with a NOP or jump to the
3118 // next instruction. The behaviour of branch instructions in this
3119 // situation (as used for tail calls) is implementation-defined, so we
3120 // cannot rely on the linker replacing the tail call with a return.
3121 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3122 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00003123 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00003124 if (GV->hasExternalWeakLinkage() &&
3125 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00003126 return false;
3127 }
3128
Tim Northover3b0846e2014-05-24 12:50:23 +00003129 // Now we search for cases where we can use a tail call without changing the
3130 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3131 // concept.
3132
3133 // I want anyone implementing a new calling convention to think long and hard
3134 // about this assert.
3135 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3136 "Unexpected variadic calling convention");
3137
Matthias Braun8d414362016-03-30 22:46:04 +00003138 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00003139 if (isVarArg && !Outs.empty()) {
3140 // At least two cases here: if caller is fastcc then we can't have any
3141 // memory arguments (we'd be expected to clean up the stack afterwards). If
3142 // caller is C then we could potentially use its argument area.
3143
3144 // FIXME: for now we take the most conservative of these in both cases:
3145 // disallow all variadic memory operands.
3146 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003147 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003148
3149 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003150 for (const CCValAssign &ArgLoc : ArgLocs)
3151 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00003152 return false;
3153 }
3154
Matthias Braun8d414362016-03-30 22:46:04 +00003155 // Check that the call results are passed in the same way.
3156 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3157 CCAssignFnForCall(CalleeCC, isVarArg),
3158 CCAssignFnForCall(CallerCC, isVarArg)))
3159 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00003160 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00003161 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3162 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00003163 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00003164 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3165 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00003166 return false;
3167 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003168
3169 // Nothing more to check if the callee is taking no arguments
3170 if (Outs.empty())
3171 return true;
3172
3173 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00003174 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00003175
3176 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3177
3178 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3179
Matthias Braun74a0bd32016-04-13 21:43:16 +00003180 // If the stack arguments for this call do not fit into our own save area then
3181 // the call cannot be made tail.
3182 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3183 return false;
3184
Matthias Braun46b0f032016-04-14 01:10:42 +00003185 const MachineRegisterInfo &MRI = MF.getRegInfo();
3186 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3187 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00003188
3189 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00003190}
3191
3192SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3193 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00003194 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00003195 int ClobberedFI) const {
3196 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00003197 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3198 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003199
3200 // Include the original chain at the beginning of the list. When this is
3201 // used by target LowerCall hooks, this helps legalize find the
3202 // CALLSEQ_BEGIN node.
3203 ArgChains.push_back(Chain);
3204
3205 // Add a chain value for each stack argument corresponding
3206 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3207 UE = DAG.getEntryNode().getNode()->use_end();
3208 U != UE; ++U)
3209 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3210 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3211 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00003212 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00003213 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00003214 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00003215
3216 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3217 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3218 ArgChains.push_back(SDValue(L, 1));
3219 }
3220
3221 // Build a tokenfactor for all the chains.
3222 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3223}
3224
3225bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3226 bool TailCallOpt) const {
3227 return CallCC == CallingConv::Fast && TailCallOpt;
3228}
3229
Tim Northover3b0846e2014-05-24 12:50:23 +00003230/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3231/// and add input and output parameter nodes.
3232SDValue
3233AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3234 SmallVectorImpl<SDValue> &InVals) const {
3235 SelectionDAG &DAG = CLI.DAG;
3236 SDLoc &DL = CLI.DL;
3237 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3238 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3239 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3240 SDValue Chain = CLI.Chain;
3241 SDValue Callee = CLI.Callee;
3242 bool &IsTailCall = CLI.IsTailCall;
3243 CallingConv::ID CallConv = CLI.CallConv;
3244 bool IsVarArg = CLI.IsVarArg;
3245
3246 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00003247 bool IsThisReturn = false;
3248
3249 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3250 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3251 bool IsSibCall = false;
3252
3253 if (IsTailCall) {
3254 // Check if it's really possible to do a tail call.
3255 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003256 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Peter Collingbourne081ffe22017-07-26 19:15:29 +00003257 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00003258 report_fatal_error("failed to perform tail call elimination on a call "
3259 "site marked musttail");
3260
3261 // A sibling call is one where we're under the usual C ABI and not planning
3262 // to change that but can still do a tail call:
3263 if (!TailCallOpt && IsTailCall)
3264 IsSibCall = true;
3265
3266 if (IsTailCall)
3267 ++NumTailCalls;
3268 }
3269
3270 // Analyze operands of the call, assigning locations to each operand.
3271 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003272 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3273 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003274
3275 if (IsVarArg) {
3276 // Handle fixed and variable vector arguments differently.
3277 // Variable vector arguments always go into memory.
3278 unsigned NumArgs = Outs.size();
3279
3280 for (unsigned i = 0; i != NumArgs; ++i) {
3281 MVT ArgVT = Outs[i].VT;
3282 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3283 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3284 /*IsVarArg=*/ !Outs[i].IsFixed);
3285 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3286 assert(!Res && "Call operand has unhandled type");
3287 (void)Res;
3288 }
3289 } else {
3290 // At this point, Outs[].VT may already be promoted to i32. To correctly
3291 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3292 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3293 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3294 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3295 // LocVT.
3296 unsigned NumArgs = Outs.size();
3297 for (unsigned i = 0; i != NumArgs; ++i) {
3298 MVT ValVT = Outs[i].VT;
3299 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003300 EVT ActualVT = getValueType(DAG.getDataLayout(),
3301 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003302 /*AllowUnknown*/ true);
3303 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3304 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3305 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003306 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003307 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003308 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003309 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003310
3311 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003312 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003313 assert(!Res && "Call operand has unhandled type");
3314 (void)Res;
3315 }
3316 }
3317
3318 // Get a count of how many bytes are to be pushed on the stack.
3319 unsigned NumBytes = CCInfo.getNextStackOffset();
3320
3321 if (IsSibCall) {
3322 // Since we're not changing the ABI to make this a tail call, the memory
3323 // operands are already available in the caller's incoming argument space.
3324 NumBytes = 0;
3325 }
3326
3327 // FPDiff is the byte offset of the call's argument area from the callee's.
3328 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3329 // by this amount for a tail call. In a sibling call it must be 0 because the
3330 // caller will deallocate the entire stack and the callee still expects its
3331 // arguments to begin at SP+0. Completely unused for non-tail calls.
3332 int FPDiff = 0;
3333
3334 if (IsTailCall && !IsSibCall) {
3335 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3336
3337 // Since callee will pop argument stack as a tail call, we must keep the
3338 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003339 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003340
3341 // FPDiff will be negative if this tail call requires more space than we
3342 // would automatically have in our incoming argument space. Positive if we
3343 // can actually shrink the stack.
3344 FPDiff = NumReusableBytes - NumBytes;
3345
3346 // The stack pointer must be 16-byte aligned at all times it's used for a
3347 // memory operation, which in practice means at *all* times and in
3348 // particular across call boundaries. Therefore our own arguments started at
3349 // a 16-byte aligned SP and the delta applied for the tail call should
3350 // satisfy the same constraint.
3351 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3352 }
3353
3354 // Adjust the stack pointer for the new arguments...
3355 // These operations are automatically eliminated by the prolog/epilog pass
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003356 if (!IsSibCall)
Serge Pavlovd526b132017-05-09 13:35:13 +00003357 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003358
Mehdi Amini44ede332015-07-09 02:09:04 +00003359 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3360 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003361
3362 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3363 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003364 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003365
3366 // Walk the register/memloc assignments, inserting copies/loads.
3367 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3368 ++i, ++realArgIdx) {
3369 CCValAssign &VA = ArgLocs[i];
3370 SDValue Arg = OutVals[realArgIdx];
3371 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3372
3373 // Promote the value if needed.
3374 switch (VA.getLocInfo()) {
3375 default:
3376 llvm_unreachable("Unknown loc info!");
3377 case CCValAssign::Full:
3378 break;
3379 case CCValAssign::SExt:
3380 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3381 break;
3382 case CCValAssign::ZExt:
3383 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3384 break;
3385 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003386 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3387 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3388 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3389 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3390 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003391 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3392 break;
3393 case CCValAssign::BCvt:
3394 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3395 break;
3396 case CCValAssign::FPExt:
3397 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3398 break;
3399 }
3400
3401 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003402 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3403 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003404 assert(VA.getLocVT() == MVT::i64 &&
3405 "unexpected calling convention register assignment");
3406 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3407 "unexpected use of 'returned'");
3408 IsThisReturn = true;
3409 }
3410 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3411 } else {
3412 assert(VA.isMemLoc());
3413
3414 SDValue DstAddr;
3415 MachinePointerInfo DstInfo;
3416
3417 // FIXME: This works on big-endian for composite byvals, which are the
3418 // common case. It should also work for fundamental types too.
3419 uint32_t BEAlign = 0;
3420 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003421 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003422 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003423 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3424 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003425 if (OpSize < 8)
3426 BEAlign = 8 - OpSize;
3427 }
3428 unsigned LocMemOffset = VA.getLocMemOffset();
3429 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003430 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003431 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003432
3433 if (IsTailCall) {
3434 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003435 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003436
Mehdi Amini44ede332015-07-09 02:09:04 +00003437 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003438 DstInfo =
3439 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003440
3441 // Make sure any stack arguments overlapping with where we're storing
3442 // are loaded before this eventual operation. Otherwise they'll be
3443 // clobbered.
3444 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3445 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003446 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003447
Mehdi Amini44ede332015-07-09 02:09:04 +00003448 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003449 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3450 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003451 }
3452
3453 if (Outs[i].Flags.isByVal()) {
3454 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003455 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003456 SDValue Cpy = DAG.getMemcpy(
3457 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003458 /*isVol = */ false, /*AlwaysInline = */ false,
3459 /*isTailCall = */ false,
3460 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003461
3462 MemOpChains.push_back(Cpy);
3463 } else {
3464 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3465 // promoted to a legal register type i32, we should truncate Arg back to
3466 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003467 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3468 VA.getValVT() == MVT::i16)
3469 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003470
Justin Lebar9c375812016-07-15 18:27:10 +00003471 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003472 MemOpChains.push_back(Store);
3473 }
3474 }
3475 }
3476
3477 if (!MemOpChains.empty())
3478 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3479
3480 // Build a sequence of copy-to-reg nodes chained together with token chain
3481 // and flag operands which copy the outgoing args into the appropriate regs.
3482 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003483 for (auto &RegToPass : RegsToPass) {
3484 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3485 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003486 InFlag = Chain.getValue(1);
3487 }
3488
3489 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3490 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3491 // node so that legalize doesn't hack it.
Tim Northover879a0b22017-04-17 17:27:56 +00003492 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3493 auto GV = G->getGlobal();
3494 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3495 AArch64II::MO_GOT) {
3496 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3497 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003498 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3499 assert(Subtarget->isTargetWindows() &&
3500 "Windows is the only supported COFF target");
3501 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
Tim Northover879a0b22017-04-17 17:27:56 +00003502 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +00003503 const GlobalValue *GV = G->getGlobal();
Tim Northover879a0b22017-04-17 17:27:56 +00003504 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3505 }
3506 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3507 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3508 Subtarget->isTargetMachO()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003509 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003510 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3511 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover879a0b22017-04-17 17:27:56 +00003512 } else {
3513 const char *Sym = S->getSymbol();
3514 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003515 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003516 }
3517
3518 // We don't usually want to end the call-sequence here because we would tidy
3519 // the frame up *after* the call, however in the ABI-changing tail-call case
3520 // we've carefully laid out the parameters so that when sp is reset they'll be
3521 // in the correct location.
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003522 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003523 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3524 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003525 InFlag = Chain.getValue(1);
3526 }
3527
3528 std::vector<SDValue> Ops;
3529 Ops.push_back(Chain);
3530 Ops.push_back(Callee);
3531
3532 if (IsTailCall) {
3533 // Each tail call may have to adjust the stack by a different amount, so
3534 // this information must travel along with the operation for eventual
3535 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003536 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003537 }
3538
3539 // Add argument registers to the end of the list so that they are known live
3540 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003541 for (auto &RegToPass : RegsToPass)
3542 Ops.push_back(DAG.getRegister(RegToPass.first,
3543 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003544
3545 // Add a register mask operand representing the call-preserved registers.
3546 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003547 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003548 if (IsThisReturn) {
3549 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003550 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003551 if (!Mask) {
3552 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003553 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003554 }
3555 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003556 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003557
3558 assert(Mask && "Missing call preserved mask for calling convention");
3559 Ops.push_back(DAG.getRegisterMask(Mask));
3560
3561 if (InFlag.getNode())
3562 Ops.push_back(InFlag);
3563
3564 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3565
3566 // If we're doing a tall call, use a TC_RETURN here rather than an
3567 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003568 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003569 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003570 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003571 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003572
3573 // Returns a chain and a flag for retval copy to use.
3574 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3575 InFlag = Chain.getValue(1);
3576
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003577 uint64_t CalleePopBytes =
3578 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003579
Jun Bum Limfc7d56d2018-01-29 19:56:42 +00003580 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3581 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3582 InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003583 if (!Ins.empty())
3584 InFlag = Chain.getValue(1);
3585
3586 // Handle result values, copying them out of physregs into vregs that we
3587 // return.
3588 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3589 InVals, IsThisReturn,
3590 IsThisReturn ? OutVals[0] : SDValue());
3591}
3592
3593bool AArch64TargetLowering::CanLowerReturn(
3594 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3595 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3596 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3597 ? RetCC_AArch64_WebKit_JS
3598 : RetCC_AArch64_AAPCS;
3599 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003600 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003601 return CCInfo.CheckReturn(Outs, RetCC);
3602}
3603
3604SDValue
3605AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3606 bool isVarArg,
3607 const SmallVectorImpl<ISD::OutputArg> &Outs,
3608 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003609 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003610 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3611 ? RetCC_AArch64_WebKit_JS
3612 : RetCC_AArch64_AAPCS;
3613 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003614 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3615 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003616 CCInfo.AnalyzeReturn(Outs, RetCC);
3617
3618 // Copy the result values into the output registers.
3619 SDValue Flag;
3620 SmallVector<SDValue, 4> RetOps(1, Chain);
3621 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3622 ++i, ++realRVLocIdx) {
3623 CCValAssign &VA = RVLocs[i];
3624 assert(VA.isRegLoc() && "Can only return in registers!");
3625 SDValue Arg = OutVals[realRVLocIdx];
3626
3627 switch (VA.getLocInfo()) {
3628 default:
3629 llvm_unreachable("Unknown loc info!");
3630 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003631 if (Outs[i].ArgVT == MVT::i1) {
3632 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3633 // value. This is strictly redundant on Darwin (which uses "zeroext
3634 // i1"), but will be optimised out before ISel.
3635 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3636 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3637 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003638 break;
3639 case CCValAssign::BCvt:
3640 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3641 break;
3642 }
3643
3644 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3645 Flag = Chain.getValue(1);
3646 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3647 }
Manman Rencbe4f942015-12-16 21:04:19 +00003648 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3649 const MCPhysReg *I =
3650 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3651 if (I) {
3652 for (; *I; ++I) {
3653 if (AArch64::GPR64RegClass.contains(*I))
3654 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3655 else if (AArch64::FPR64RegClass.contains(*I))
3656 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3657 else
3658 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3659 }
3660 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003661
3662 RetOps[0] = Chain; // Update chain.
3663
3664 // Add the flag if we have it.
3665 if (Flag.getNode())
3666 RetOps.push_back(Flag);
3667
3668 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3669}
3670
3671//===----------------------------------------------------------------------===//
3672// Other Lowering Code
3673//===----------------------------------------------------------------------===//
3674
Joel Jonesa7c4a522017-04-21 17:31:03 +00003675SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3676 SelectionDAG &DAG,
3677 unsigned Flag) const {
3678 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3679}
3680
3681SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3682 SelectionDAG &DAG,
3683 unsigned Flag) const {
3684 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3685}
3686
3687SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3688 SelectionDAG &DAG,
3689 unsigned Flag) const {
3690 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3691 N->getOffset(), Flag);
3692}
3693
3694SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3695 SelectionDAG &DAG,
3696 unsigned Flag) const {
3697 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3698}
3699
3700// (loadGOT sym)
3701template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003702SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3703 unsigned Flags) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003704 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3705 SDLoc DL(N);
3706 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003707 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003708 // FIXME: Once remat is capable of dealing with instructions with register
3709 // operands, expand this into two nodes instead of using a wrapper node.
3710 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3711}
3712
3713// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3714template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003715SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3716 unsigned Flags) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003717 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3718 SDLoc DL(N);
3719 EVT Ty = getPointerTy(DAG.getDataLayout());
3720 const unsigned char MO_NC = AArch64II::MO_NC;
3721 return DAG.getNode(
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003722 AArch64ISD::WrapperLarge, DL, Ty,
3723 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3724 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3725 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3726 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
Joel Jonesa7c4a522017-04-21 17:31:03 +00003727}
3728
3729// (addlow (adrp %hi(sym)) %lo(sym))
3730template <class NodeTy>
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003731SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3732 unsigned Flags) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003733 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3734 SDLoc DL(N);
3735 EVT Ty = getPointerTy(DAG.getDataLayout());
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003736 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003737 SDValue Lo = getTargetNode(N, Ty, DAG,
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003738 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
Joel Jonesa7c4a522017-04-21 17:31:03 +00003739 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3740 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3741}
3742
Tim Northover3b0846e2014-05-24 12:50:23 +00003743SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3744 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00003745 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003746 const GlobalValue *GV = GN->getGlobal();
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003747 const AArch64II::TOF TargetFlags =
3748 (GV->hasDLLImportStorageClass() ? AArch64II::MO_DLLIMPORT
3749 : AArch64II::MO_NO_FLAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003750 unsigned char OpFlags =
3751 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3752
3753 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3754 "unexpected offset in global node");
3755
Joel Jonesa7c4a522017-04-21 17:31:03 +00003756 // This also catches the large code model case for Darwin.
Tim Northover3b0846e2014-05-24 12:50:23 +00003757 if ((OpFlags & AArch64II::MO_GOT) != 0) {
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003758 return getGOT(GN, DAG, TargetFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003759 }
3760
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003761 SDValue Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00003762 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003763 Result = getAddrLarge(GN, DAG, TargetFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003764 } else {
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003765 Result = getAddr(GN, DAG, TargetFlags);
Tim Northover3b0846e2014-05-24 12:50:23 +00003766 }
Martin Storsjo373c8ef2017-10-25 07:25:18 +00003767 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3768 SDLoc DL(GN);
3769 if (GV->hasDLLImportStorageClass())
3770 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3771 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3772 return Result;
Tim Northover3b0846e2014-05-24 12:50:23 +00003773}
3774
3775/// \brief Convert a TLS address reference into the correct sequence of loads
3776/// and calls to compute the variable's address (for Darwin, currently) and
3777/// return an SDValue containing the final node.
3778
3779/// Darwin only has one TLS scheme which must be capable of dealing with the
3780/// fully general situation, in the worst case. This means:
3781/// + "extern __thread" declaration.
3782/// + Defined in a possibly unknown dynamic library.
3783///
3784/// The general system is that each __thread variable has a [3 x i64] descriptor
3785/// which contains information used by the runtime to calculate the address. The
3786/// only part of this the compiler needs to know about is the first xword, which
3787/// contains a function pointer that must be called with the address of the
3788/// entire descriptor in "x0".
3789///
3790/// Since this descriptor may be in a different unit, in general even the
3791/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3792/// is:
3793/// adrp x0, _var@TLVPPAGE
3794/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3795/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3796/// ; the function pointer
3797/// blr x1 ; Uses descriptor address in x0
3798/// ; Address of _var is now in x0.
3799///
3800/// If the address of _var's descriptor *is* known to the linker, then it can
3801/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3802/// a slight efficiency gain.
3803SDValue
3804AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3805 SelectionDAG &DAG) const {
Martin Storsjo4629f522017-11-14 19:57:59 +00003806 assert(Subtarget->isTargetDarwin() &&
3807 "This function expects a Darwin target");
Tim Northover3b0846e2014-05-24 12:50:23 +00003808
3809 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003810 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003811 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3812
3813 SDValue TLVPAddr =
3814 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3815 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3816
3817 // The first entry in the descriptor is a function pointer that we must call
3818 // to obtain the address of the variable.
3819 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00003820 SDValue FuncTLVGet = DAG.getLoad(
3821 MVT::i64, DL, Chain, DescAddr,
3822 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3823 /* Alignment = */ 8,
3824 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3825 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00003826 Chain = FuncTLVGet.getValue(1);
3827
Matthias Braun941a7052016-07-28 18:40:00 +00003828 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3829 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003830
3831 // TLS calls preserve all registers except those that absolutely must be
3832 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3833 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003834 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003835 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003836
3837 // Finally, we can make the call. This is just a degenerate version of a
3838 // normal AArch64 call node: x0 takes the address of the descriptor, and
3839 // returns the address of the variable in this thread.
3840 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3841 Chain =
3842 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3843 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3844 DAG.getRegisterMask(Mask), Chain.getValue(1));
3845 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3846}
3847
3848/// When accessing thread-local variables under either the general-dynamic or
3849/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3850/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003851/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003852///
Kristof Beylsaea84612015-03-04 09:12:08 +00003853/// The sequence is:
3854/// adrp x0, :tlsdesc:var
3855/// ldr x1, [x0, #:tlsdesc_lo12:var]
3856/// add x0, x0, #:tlsdesc_lo12:var
3857/// .tlsdesccall var
3858/// blr x1
3859/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003860///
Kristof Beylsaea84612015-03-04 09:12:08 +00003861/// The above sequence must be produced unscheduled, to enable the linker to
3862/// optimize/relax this sequence.
3863/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3864/// above sequence, and expanded really late in the compilation flow, to ensure
3865/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003866SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3867 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003868 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003869 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003870
Kristof Beylsaea84612015-03-04 09:12:08 +00003871 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003872 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003873
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003874 Chain =
3875 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003876 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003877
3878 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3879}
3880
3881SDValue
3882AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3883 SelectionDAG &DAG) const {
3884 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
Petr Hosek9eb0a1e2017-04-04 19:51:53 +00003885 assert(Subtarget->useSmallAddressing() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003886 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003887 // Different choices can be made for the maximum size of the TLS area for a
3888 // module. For the small address model, the default TLS size is 16MiB and the
3889 // maximum TLS size is 4GiB.
3890 // FIXME: add -mtls-size command line option and make it control the 16MiB
3891 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003892 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3893
3894 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003895
Kristof Beylsaea84612015-03-04 09:12:08 +00003896 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3897 if (Model == TLSModel::LocalDynamic)
3898 Model = TLSModel::GeneralDynamic;
3899 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003900
3901 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003902 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003903 SDLoc DL(Op);
3904 const GlobalValue *GV = GA->getGlobal();
3905
3906 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3907
3908 if (Model == TLSModel::LocalExec) {
3909 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003910 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003911 SDValue LoVar = DAG.getTargetGlobalAddress(
3912 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003913 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003914
Kristof Beylsaea84612015-03-04 09:12:08 +00003915 SDValue TPWithOff_lo =
3916 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003917 HiVar,
3918 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003919 0);
3920 SDValue TPWithOff =
3921 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003922 LoVar,
3923 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003924 0);
3925 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003926 } else if (Model == TLSModel::InitialExec) {
3927 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3928 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3929 } else if (Model == TLSModel::LocalDynamic) {
3930 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3931 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3932 // the beginning of the module's TLS region, followed by a DTPREL offset
3933 // calculation.
3934
3935 // These accesses will need deduplicating if there's more than one.
3936 AArch64FunctionInfo *MFI =
3937 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3938 MFI->incNumLocalDynamicTLSAccesses();
3939
Tim Northover3b0846e2014-05-24 12:50:23 +00003940 // The call needs a relocation too for linker relaxation. It doesn't make
3941 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3942 // the address.
3943 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3944 AArch64II::MO_TLS);
3945
3946 // Now we can calculate the offset from TPIDR_EL0 to this module's
3947 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003948 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003949
3950 // Now use :dtprel_whatever: operations to calculate this variable's offset
3951 // in its thread-storage area.
3952 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003953 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003954 SDValue LoVar = DAG.getTargetGlobalAddress(
3955 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003956 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3957
Kristof Beylsaea84612015-03-04 09:12:08 +00003958 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003959 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003960 0);
3961 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003962 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003963 0);
3964 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003965 // The call needs a relocation too for linker relaxation. It doesn't make
3966 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3967 // the address.
3968 SDValue SymAddr =
3969 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3970
3971 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003972 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003973 } else
3974 llvm_unreachable("Unsupported ELF TLS access model");
3975
3976 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3977}
3978
3979SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3980 SelectionDAG &DAG) const {
Martin Storsjoeca862d2017-12-04 09:09:04 +00003981 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
Chih-Hung Hsieh9f9e4682018-02-28 17:48:55 +00003982 if (DAG.getTarget().useEmulatedTLS())
Martin Storsjoeca862d2017-12-04 09:09:04 +00003983 return LowerToTLSEmulatedModel(GA, DAG);
3984
Tim Northover3b0846e2014-05-24 12:50:23 +00003985 if (Subtarget->isTargetDarwin())
3986 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00003987 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00003988 return LowerELFGlobalTLSAddress(Op, DAG);
3989
3990 llvm_unreachable("Unexpected platform trying to use TLS");
3991}
Eugene Zelenko049b0172017-01-06 00:30:53 +00003992
Tim Northover3b0846e2014-05-24 12:50:23 +00003993SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3994 SDValue Chain = Op.getOperand(0);
3995 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3996 SDValue LHS = Op.getOperand(2);
3997 SDValue RHS = Op.getOperand(3);
3998 SDValue Dest = Op.getOperand(4);
3999 SDLoc dl(Op);
4000
4001 // Handle f128 first, since lowering it will result in comparing the return
4002 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4003 // is expecting to deal with.
4004 if (LHS.getValueType() == MVT::f128) {
4005 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4006
4007 // If softenSetCCOperands returned a scalar, we need to compare the result
4008 // against zero to select between true and false values.
4009 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004010 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004011 CC = ISD::SETNE;
4012 }
4013 }
4014
4015 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4016 // instruction.
Joel Galenson3e408832017-12-05 21:33:12 +00004017 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4018 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004019 // Only lower legal XALUO ops.
4020 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4021 return SDValue();
4022
4023 // The actual operation with overflow check.
4024 AArch64CC::CondCode OFCC;
4025 SDValue Value, Overflow;
4026 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4027
4028 if (CC == ISD::SETNE)
4029 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004030 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004031
Ahmed Bougachadf956a22015-02-06 23:15:39 +00004032 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4033 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00004034 }
4035
4036 if (LHS.getValueType().isInteger()) {
4037 assert((LHS.getValueType() == RHS.getValueType()) &&
4038 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4039
4040 // If the RHS of the comparison is zero, we can potentially fold this
4041 // to a specialized branch.
4042 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4043 if (RHSC && RHSC->getZExtValue() == 0) {
4044 if (CC == ISD::SETEQ) {
4045 // See if we can use a TBZ to fold in an AND as well.
4046 // TBZ has a smaller branch displacement than CBZ. If the offset is
4047 // out of bounds, a late MI-layer pass rewrites branches.
4048 // 403.gcc is an example that hits this case.
4049 if (LHS.getOpcode() == ISD::AND &&
4050 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4051 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4052 SDValue Test = LHS.getOperand(0);
4053 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004054 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004055 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4056 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004057 }
4058
4059 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4060 } else if (CC == ISD::SETNE) {
4061 // See if we can use a TBZ to fold in an AND as well.
4062 // TBZ has a smaller branch displacement than CBZ. If the offset is
4063 // out of bounds, a late MI-layer pass rewrites branches.
4064 // 403.gcc is an example that hits this case.
4065 if (LHS.getOpcode() == ISD::AND &&
4066 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4067 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4068 SDValue Test = LHS.getOperand(0);
4069 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00004070 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004071 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4072 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004073 }
4074
4075 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004076 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4077 // Don't combine AND since emitComparison converts the AND to an ANDS
4078 // (a.k.a. TST) and the test in the test bit and branch instruction
4079 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004080 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004081 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004082 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00004083 }
4084 }
Chad Rosier579c02c2014-08-01 14:48:56 +00004085 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4086 LHS.getOpcode() != ISD::AND) {
4087 // Don't combine AND since emitComparison converts the AND to an ANDS
4088 // (a.k.a. TST) and the test in the test bit and branch instruction
4089 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004090 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00004091 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004092 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00004093 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004094
4095 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004096 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004097 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4098 Cmp);
4099 }
4100
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004101 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4102 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004103
4104 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4105 // clean. Some of them require two branches to implement.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004106 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004107 AArch64CC::CondCode CC1, CC2;
4108 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004109 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004110 SDValue BR1 =
4111 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4112 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004113 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004114 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4115 Cmp);
4116 }
4117
4118 return BR1;
4119}
4120
4121SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4122 SelectionDAG &DAG) const {
4123 EVT VT = Op.getValueType();
4124 SDLoc DL(Op);
4125
4126 SDValue In1 = Op.getOperand(0);
4127 SDValue In2 = Op.getOperand(1);
4128 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00004129
4130 if (SrcVT.bitsLT(VT))
4131 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4132 else if (SrcVT.bitsGT(VT))
4133 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004134
4135 EVT VecVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004136 uint64_t EltMask;
4137 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00004138
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004139 auto setVecVal = [&] (int Idx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004140 if (!VT.isVector()) {
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004141 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004142 DAG.getUNDEF(VecVT), In1);
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004143 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
Tim Northover3b0846e2014-05-24 12:50:23 +00004144 DAG.getUNDEF(VecVT), In2);
4145 } else {
4146 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4147 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4148 }
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004149 };
4150
4151 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4152 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4153 EltMask = 0x80000000ULL;
4154 setVecVal(AArch64::ssub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004155 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004156 VecVT = MVT::v2i64;
4157
Eric Christopher572e03a2015-06-19 01:53:21 +00004158 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00004159 // immediate moves cannot materialize that in a single instruction for
4160 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00004161 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004162
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004163 setVecVal(AArch64::dsub);
4164 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4165 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4166 EltMask = 0x8000ULL;
4167 setVecVal(AArch64::hsub);
Tim Northover3b0846e2014-05-24 12:50:23 +00004168 } else {
4169 llvm_unreachable("Invalid type for copysign!");
4170 }
4171
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004172 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004173
4174 // If we couldn't materialize the mask above, then the mask vector will be
4175 // the zero vector, and we need to negate it here.
4176 if (VT == MVT::f64 || VT == MVT::v2f64) {
4177 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4178 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4179 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4180 }
4181
4182 SDValue Sel =
4183 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4184
Sjoerd Meijerafc2cd32017-08-24 09:21:10 +00004185 if (VT == MVT::f16)
4186 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
Tim Northover3b0846e2014-05-24 12:50:23 +00004187 if (VT == MVT::f32)
4188 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4189 else if (VT == MVT::f64)
4190 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4191 else
4192 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4193}
4194
4195SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00004196 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00004197 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00004198 return SDValue();
4199
Weiming Zhao7a2d1562014-11-19 00:29:14 +00004200 if (!Subtarget->hasNEON())
4201 return SDValue();
4202
Tim Northover3b0846e2014-05-24 12:50:23 +00004203 // While there is no integer popcount instruction, it can
4204 // be more efficiently lowered to the following sequence that uses
4205 // AdvSIMD registers/instructions as long as the copies to/from
4206 // the AdvSIMD registers are cheap.
4207 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4208 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4209 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4210 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4211 SDValue Val = Op.getOperand(0);
4212 SDLoc DL(Op);
4213 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004214
Hao Liue0335d72015-01-30 02:13:53 +00004215 if (VT == MVT::i32)
4216 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4217 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004218
Hao Liue0335d72015-01-30 02:13:53 +00004219 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00004220 SDValue UaddLV = DAG.getNode(
4221 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004222 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00004223
4224 if (VT == MVT::i64)
4225 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4226 return UaddLV;
4227}
4228
4229SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4230
4231 if (Op.getValueType().isVector())
4232 return LowerVSETCC(Op, DAG);
4233
4234 SDValue LHS = Op.getOperand(0);
4235 SDValue RHS = Op.getOperand(1);
4236 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4237 SDLoc dl(Op);
4238
4239 // We chose ZeroOrOneBooleanContents, so use zero and one.
4240 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004241 SDValue TVal = DAG.getConstant(1, dl, VT);
4242 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004243
4244 // Handle f128 first, since one possible outcome is a normal integer
4245 // comparison which gets picked up by the next if statement.
4246 if (LHS.getValueType() == MVT::f128) {
4247 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4248
4249 // If softenSetCCOperands returned a scalar, use it.
4250 if (!RHS.getNode()) {
4251 assert(LHS.getValueType() == Op.getValueType() &&
4252 "Unexpected setcc expansion!");
4253 return LHS;
4254 }
4255 }
4256
4257 if (LHS.getValueType().isInteger()) {
4258 SDValue CCVal;
4259 SDValue Cmp =
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004260 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
Tim Northover3b0846e2014-05-24 12:50:23 +00004261
4262 // Note that we inverted the condition above, so we reverse the order of
4263 // the true and false operands here. This will allow the setcc to be
4264 // matched to a single CSINC instruction.
4265 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4266 }
4267
4268 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004269 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4270 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004271
4272 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4273 // and do the comparison.
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004274 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004275
4276 AArch64CC::CondCode CC1, CC2;
4277 changeFPCCToAArch64CC(CC, CC1, CC2);
4278 if (CC2 == AArch64CC::AL) {
4279 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004280 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004281
4282 // Note that we inverted the condition above, so we reverse the order of
4283 // the true and false operands here. This will allow the setcc to be
4284 // matched to a single CSINC instruction.
4285 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4286 } else {
4287 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4288 // totally clean. Some of them require two CSELs to implement. As is in
4289 // this case, we emit the first CSEL and then emit a second using the output
4290 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4291
4292 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004293 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004294 SDValue CS1 =
4295 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4296
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004297 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004298 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4299 }
4300}
4301
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004302SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4303 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00004304 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00004305 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004306 // Handle f128 first, because it will result in a comparison of some RTLIB
4307 // call result against zero.
4308 if (LHS.getValueType() == MVT::f128) {
4309 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4310
4311 // If softenSetCCOperands returned a scalar, we need to compare the result
4312 // against zero to select between true and false values.
4313 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004314 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004315 CC = ISD::SETNE;
4316 }
4317 }
4318
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004319 // Also handle f16, for which we need to do a f32 comparison.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004320 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004321 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4322 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4323 }
4324
4325 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004326 if (LHS.getValueType().isInteger()) {
4327 assert((LHS.getValueType() == RHS.getValueType()) &&
4328 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4329
4330 unsigned Opcode = AArch64ISD::CSEL;
4331
4332 // If both the TVal and the FVal are constants, see if we can swap them in
4333 // order to for a CSINV or CSINC out of them.
4334 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4335 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4336
4337 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4338 std::swap(TVal, FVal);
4339 std::swap(CTVal, CFVal);
4340 CC = ISD::getSetCCInverse(CC, true);
4341 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4342 std::swap(TVal, FVal);
4343 std::swap(CTVal, CFVal);
4344 CC = ISD::getSetCCInverse(CC, true);
4345 } else if (TVal.getOpcode() == ISD::XOR) {
4346 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4347 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004348 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004349 std::swap(TVal, FVal);
4350 std::swap(CTVal, CFVal);
4351 CC = ISD::getSetCCInverse(CC, true);
4352 }
4353 } else if (TVal.getOpcode() == ISD::SUB) {
4354 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4355 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004356 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004357 std::swap(TVal, FVal);
4358 std::swap(CTVal, CFVal);
4359 CC = ISD::getSetCCInverse(CC, true);
4360 }
4361 } else if (CTVal && CFVal) {
4362 const int64_t TrueVal = CTVal->getSExtValue();
4363 const int64_t FalseVal = CFVal->getSExtValue();
4364 bool Swap = false;
4365
4366 // If both TVal and FVal are constants, see if FVal is the
4367 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4368 // instead of a CSEL in that case.
4369 if (TrueVal == ~FalseVal) {
4370 Opcode = AArch64ISD::CSINV;
4371 } else if (TrueVal == -FalseVal) {
4372 Opcode = AArch64ISD::CSNEG;
4373 } else if (TVal.getValueType() == MVT::i32) {
4374 // If our operands are only 32-bit wide, make sure we use 32-bit
4375 // arithmetic for the check whether we can use CSINC. This ensures that
4376 // the addition in the check will wrap around properly in case there is
4377 // an overflow (which would not be the case if we do the check with
4378 // 64-bit arithmetic).
4379 const uint32_t TrueVal32 = CTVal->getZExtValue();
4380 const uint32_t FalseVal32 = CFVal->getZExtValue();
4381
4382 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4383 Opcode = AArch64ISD::CSINC;
4384
4385 if (TrueVal32 > FalseVal32) {
4386 Swap = true;
4387 }
4388 }
4389 // 64-bit check whether we can use CSINC.
4390 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4391 Opcode = AArch64ISD::CSINC;
4392
4393 if (TrueVal > FalseVal) {
4394 Swap = true;
4395 }
4396 }
4397
4398 // Swap TVal and FVal if necessary.
4399 if (Swap) {
4400 std::swap(TVal, FVal);
4401 std::swap(CTVal, CFVal);
4402 CC = ISD::getSetCCInverse(CC, true);
4403 }
4404
4405 if (Opcode != AArch64ISD::CSEL) {
4406 // Drop FVal since we can get its value by simply inverting/negating
4407 // TVal.
4408 FVal = TVal;
4409 }
4410 }
4411
Chad Rosier58f505b2016-08-26 18:05:50 +00004412 // Avoid materializing a constant when possible by reusing a known value in
4413 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004414 // is one, zero or negative one in the case of a CSEL. We can always
4415 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4416 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004417 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4418 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4419 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4420 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4421 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4422 // "a != C ? x : a" to avoid materializing C.
4423 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4424 TVal = LHS;
4425 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4426 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004427 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4428 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4429 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4430 // avoid materializing C.
4431 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4432 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4433 Opcode = AArch64ISD::CSINV;
4434 TVal = LHS;
4435 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4436 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004437 }
4438
Tim Northover3b0846e2014-05-24 12:50:23 +00004439 SDValue CCVal;
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004440 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004441 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004442 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4443 }
4444
4445 // Now we know we're dealing with FP values.
Sjoerd Meijerec9581e2017-08-18 10:51:14 +00004446 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4447 LHS.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004448 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004449 EVT VT = TVal.getValueType();
Sjoerd Meijerb9de2b42017-08-22 09:21:08 +00004450 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004451
4452 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4453 // clean. Some of them require two CSELs to implement.
4454 AArch64CC::CondCode CC1, CC2;
4455 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004456
4457 if (DAG.getTarget().Options.UnsafeFPMath) {
4458 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4459 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4460 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4461 if (RHSVal && RHSVal->isZero()) {
4462 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4463 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4464
4465 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004466 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004467 TVal = LHS;
4468 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004469 CFVal && CFVal->isZero() &&
4470 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004471 FVal = LHS;
4472 }
4473 }
4474
4475 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004476 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004477 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4478
4479 // If we need a second CSEL, emit it, using the output of the first as the
4480 // RHS. We're effectively OR'ing the two CC's together.
4481 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004482 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004483 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4484 }
4485
4486 // Otherwise, return the output of the first CSEL.
4487 return CS1;
4488}
4489
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004490SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4491 SelectionDAG &DAG) const {
4492 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4493 SDValue LHS = Op.getOperand(0);
4494 SDValue RHS = Op.getOperand(1);
4495 SDValue TVal = Op.getOperand(2);
4496 SDValue FVal = Op.getOperand(3);
4497 SDLoc DL(Op);
4498 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4499}
4500
4501SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4502 SelectionDAG &DAG) const {
4503 SDValue CCVal = Op->getOperand(0);
4504 SDValue TVal = Op->getOperand(1);
4505 SDValue FVal = Op->getOperand(2);
4506 SDLoc DL(Op);
4507
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004508 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4509 // instruction.
Amara Emerson24ca39c2017-10-09 15:15:09 +00004510 if (isOverflowIntrOpRes(CCVal)) {
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004511 // Only lower legal XALUO ops.
4512 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4513 return SDValue();
4514
4515 AArch64CC::CondCode OFCC;
4516 SDValue Value, Overflow;
4517 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004518 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004519
4520 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4521 CCVal, Overflow);
4522 }
4523
4524 // Lower it the same way as we would lower a SELECT_CC node.
4525 ISD::CondCode CC;
4526 SDValue LHS, RHS;
4527 if (CCVal.getOpcode() == ISD::SETCC) {
4528 LHS = CCVal.getOperand(0);
4529 RHS = CCVal.getOperand(1);
4530 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4531 } else {
4532 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004533 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004534 CC = ISD::SETNE;
4535 }
4536 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4537}
4538
Tim Northover3b0846e2014-05-24 12:50:23 +00004539SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4540 SelectionDAG &DAG) const {
4541 // Jump table entries as PC relative offsets. No additional tweaking
4542 // is necessary here. Just get the address of the jump table.
4543 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004544
4545 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4546 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004547 return getAddrLarge(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004548 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004549 return getAddr(JT, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004550}
4551
4552SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4553 SelectionDAG &DAG) const {
4554 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004555
4556 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4557 // Use the GOT for the large code model on iOS.
4558 if (Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004559 return getGOT(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004560 }
Joel Jonesa7c4a522017-04-21 17:31:03 +00004561 return getAddrLarge(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004562 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004563 return getAddr(CP, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004564 }
4565}
4566
4567SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4568 SelectionDAG &DAG) const {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004569 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004570 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4571 !Subtarget->isTargetMachO()) {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004572 return getAddrLarge(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004573 } else {
Joel Jonesa7c4a522017-04-21 17:31:03 +00004574 return getAddr(BA, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004575 }
4576}
4577
4578SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4579 SelectionDAG &DAG) const {
4580 AArch64FunctionInfo *FuncInfo =
4581 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4582
4583 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004584 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4585 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004586 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4587 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004588 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004589}
4590
Martin Storsjo68266fa2017-07-13 17:03:12 +00004591SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4592 SelectionDAG &DAG) const {
4593 AArch64FunctionInfo *FuncInfo =
4594 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4595
4596 SDLoc DL(Op);
4597 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4598 ? FuncInfo->getVarArgsGPRIndex()
4599 : FuncInfo->getVarArgsStackIndex(),
4600 getPointerTy(DAG.getDataLayout()));
4601 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4602 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4603 MachinePointerInfo(SV));
4604}
4605
Tim Northover3b0846e2014-05-24 12:50:23 +00004606SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4607 SelectionDAG &DAG) const {
4608 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4609 // Standard, section B.3.
4610 MachineFunction &MF = DAG.getMachineFunction();
4611 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004612 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004613 SDLoc DL(Op);
4614
4615 SDValue Chain = Op.getOperand(0);
4616 SDValue VAList = Op.getOperand(1);
4617 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4618 SmallVector<SDValue, 4> MemOps;
4619
4620 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004621 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004622 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004623 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004624
4625 // void *__gr_top at offset 8
4626 int GPRSize = FuncInfo->getVarArgsGPRSize();
4627 if (GPRSize > 0) {
4628 SDValue GRTop, GRTopAddr;
4629
Mehdi Amini44ede332015-07-09 02:09:04 +00004630 GRTopAddr =
4631 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004632
Mehdi Amini44ede332015-07-09 02:09:04 +00004633 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4634 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4635 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004636
4637 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004638 MachinePointerInfo(SV, 8),
4639 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004640 }
4641
4642 // void *__vr_top at offset 16
4643 int FPRSize = FuncInfo->getVarArgsFPRSize();
4644 if (FPRSize > 0) {
4645 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004646 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4647 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004648
Mehdi Amini44ede332015-07-09 02:09:04 +00004649 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4650 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4651 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004652
4653 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004654 MachinePointerInfo(SV, 16),
4655 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004656 }
4657
4658 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004659 SDValue GROffsAddr =
4660 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004661 MemOps.push_back(DAG.getStore(
4662 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4663 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004664
4665 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004666 SDValue VROffsAddr =
4667 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004668 MemOps.push_back(DAG.getStore(
4669 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4670 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004671
4672 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4673}
4674
4675SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4676 SelectionDAG &DAG) const {
Martin Storsjo2f24e932017-07-17 20:05:19 +00004677 MachineFunction &MF = DAG.getMachineFunction();
4678
Matthias Braunf1caa282017-12-15 22:22:58 +00004679 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
Martin Storsjo68266fa2017-07-13 17:03:12 +00004680 return LowerWin64_VASTART(Op, DAG);
4681 else if (Subtarget->isTargetDarwin())
4682 return LowerDarwin_VASTART(Op, DAG);
4683 else
4684 return LowerAAPCS_VASTART(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00004685}
4686
4687SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4688 SelectionDAG &DAG) const {
4689 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4690 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004691 SDLoc DL(Op);
Martin Storsjo68266fa2017-07-13 17:03:12 +00004692 unsigned VaListSize =
4693 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
Tim Northover3b0846e2014-05-24 12:50:23 +00004694 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4695 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4696
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004697 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4698 Op.getOperand(2),
4699 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004700 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004701 MachinePointerInfo(SrcSV));
4702}
4703
4704SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4705 assert(Subtarget->isTargetDarwin() &&
4706 "automatic va_arg instruction only works on Darwin");
4707
4708 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4709 EVT VT = Op.getValueType();
4710 SDLoc DL(Op);
4711 SDValue Chain = Op.getOperand(0);
4712 SDValue Addr = Op.getOperand(1);
4713 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004714 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004715
Justin Lebar9c375812016-07-15 18:27:10 +00004716 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004717 Chain = VAList.getValue(1);
4718
4719 if (Align > 8) {
4720 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004721 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4722 DAG.getConstant(Align - 1, DL, PtrVT));
4723 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4724 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004725 }
4726
4727 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004728 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004729
4730 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4731 // up to 64 bits. At the very least, we have to increase the striding of the
4732 // vaargs list to match this, and for FP values we need to introduce
4733 // FP_ROUND nodes as well.
4734 if (VT.isInteger() && !VT.isVector())
4735 ArgSize = 8;
4736 bool NeedFPTrunc = false;
4737 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4738 ArgSize = 8;
4739 NeedFPTrunc = true;
4740 }
4741
4742 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004743 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4744 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004745 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004746 SDValue APStore =
4747 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004748
4749 // Load the actual argument out of the pointer VAList
4750 if (NeedFPTrunc) {
4751 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004752 SDValue WideFP =
4753 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004754 // Round the value down to an f32.
4755 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004756 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004757 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4758 // Merge the rounded value with the chain output of the load.
4759 return DAG.getMergeValues(Ops, DL);
4760 }
4761
Justin Lebar9c375812016-07-15 18:27:10 +00004762 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004763}
4764
4765SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4766 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004767 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4768 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004769
4770 EVT VT = Op.getValueType();
4771 SDLoc DL(Op);
4772 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4773 SDValue FrameAddr =
4774 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4775 while (Depth--)
4776 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004777 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004778 return FrameAddr;
4779}
4780
4781// FIXME? Maybe this could be a TableGen attribute on some registers and
4782// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004783unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4784 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004785 unsigned Reg = StringSwitch<unsigned>(RegName)
4786 .Case("sp", AArch64::SP)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00004787 .Case("x18", AArch64::X18)
4788 .Case("w18", AArch64::W18)
Tim Northover3b0846e2014-05-24 12:50:23 +00004789 .Default(0);
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00004790 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4791 !Subtarget->isX18Reserved())
4792 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004793 if (Reg)
4794 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004795 report_fatal_error(Twine("Invalid register name \""
4796 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004797}
4798
4799SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4800 SelectionDAG &DAG) const {
4801 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004802 MachineFrameInfo &MFI = MF.getFrameInfo();
4803 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004804
4805 EVT VT = Op.getValueType();
4806 SDLoc DL(Op);
4807 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4808 if (Depth) {
4809 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004810 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004811 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4812 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004813 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004814 }
4815
4816 // Return LR, which contains the return address. Mark it an implicit live-in.
4817 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4818 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4819}
4820
4821/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4822/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4823SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4824 SelectionDAG &DAG) const {
4825 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4826 EVT VT = Op.getValueType();
4827 unsigned VTBits = VT.getSizeInBits();
4828 SDLoc dl(Op);
4829 SDValue ShOpLo = Op.getOperand(0);
4830 SDValue ShOpHi = Op.getOperand(1);
4831 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004832 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4833
4834 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4835
4836 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004837 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004838 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4839
4840 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4841 // is "undef". We wanted 0, so CSEL it directly.
4842 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4843 ISD::SETEQ, dl, DAG);
4844 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4845 HiBitsForLo =
4846 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4847 HiBitsForLo, CCVal, Cmp);
4848
Tim Northover3b0846e2014-05-24 12:50:23 +00004849 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004850 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004851
Tim Northoverf3be9d52015-12-02 00:33:54 +00004852 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4853 SDValue LoForNormalShift =
4854 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004855
Tim Northoverf3be9d52015-12-02 00:33:54 +00004856 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4857 dl, DAG);
4858 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4859 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4860 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4861 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004862
4863 // AArch64 shifts larger than the register width are wrapped rather than
4864 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004865 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4866 SDValue HiForBigShift =
4867 Opc == ISD::SRA
4868 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4869 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4870 : DAG.getConstant(0, dl, VT);
4871 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4872 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004873
4874 SDValue Ops[2] = { Lo, Hi };
4875 return DAG.getMergeValues(Ops, dl);
4876}
4877
4878/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4879/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4880SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004881 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004882 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4883 EVT VT = Op.getValueType();
4884 unsigned VTBits = VT.getSizeInBits();
4885 SDLoc dl(Op);
4886 SDValue ShOpLo = Op.getOperand(0);
4887 SDValue ShOpHi = Op.getOperand(1);
4888 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004889
4890 assert(Op.getOpcode() == ISD::SHL_PARTS);
4891 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004892 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004893 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4894
4895 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4896 // is "undef". We wanted 0, so CSEL it directly.
4897 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4898 ISD::SETEQ, dl, DAG);
4899 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4900 LoBitsForHi =
4901 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4902 LoBitsForHi, CCVal, Cmp);
4903
Tim Northover3b0846e2014-05-24 12:50:23 +00004904 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004905 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004906 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4907 SDValue HiForNormalShift =
4908 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004909
Tim Northoverf3be9d52015-12-02 00:33:54 +00004910 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004911
Tim Northoverf3be9d52015-12-02 00:33:54 +00004912 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4913 dl, DAG);
4914 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4915 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4916 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004917
4918 // AArch64 shifts of larger than register sizes are wrapped rather than
4919 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004920 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4921 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4922 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4923 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004924
4925 SDValue Ops[2] = { Lo, Hi };
4926 return DAG.getMergeValues(Ops, dl);
4927}
4928
4929bool AArch64TargetLowering::isOffsetFoldingLegal(
4930 const GlobalAddressSDNode *GA) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004931 DEBUG(dbgs() << "Skipping offset folding global address: ");
4932 DEBUG(GA->dump());
4933 DEBUG(dbgs() << "AArch64 doesn't support folding offsets into global "
4934 "addresses\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00004935 return false;
4936}
4937
4938bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4939 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4940 // FIXME: We should be able to handle f128 as well with a clever lowering.
Sjoerd Meijer5ea465d2018-02-08 08:39:05 +00004941 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
4942 (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004943 DEBUG(dbgs() << "Legal fp imm: materialize 0 using the zero register\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00004944 return true;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004945 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004946
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004947 StringRef FPType;
4948 bool IsLegal = false;
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004949 SmallString<128> ImmStrVal;
4950 Imm.toString(ImmStrVal);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004951
4952 if (VT == MVT::f64) {
4953 FPType = "f64";
4954 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
4955 } else if (VT == MVT::f32) {
4956 FPType = "f32";
4957 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
4958 } else if (VT == MVT::f16 && Subtarget->hasFullFP16()) {
4959 FPType = "f16";
4960 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
4961 }
4962
4963 if (IsLegal) {
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004964 DEBUG(dbgs() << "Legal " << FPType << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004965 return true;
4966 }
4967
4968 if (!FPType.empty())
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004969 DEBUG(dbgs() << "Illegal " << FPType << " imm value: " << ImmStrVal << "\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004970 else
Sjoerd Meijerb0eb5fb2017-08-24 14:47:06 +00004971 DEBUG(dbgs() << "Illegal fp imm " << ImmStrVal << ": unsupported fp type\n");
Sjoerd Meijer24c98182017-08-23 08:18:37 +00004972
Tim Northover3b0846e2014-05-24 12:50:23 +00004973 return false;
4974}
4975
4976//===----------------------------------------------------------------------===//
4977// AArch64 Optimization Hooks
4978//===----------------------------------------------------------------------===//
4979
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004980static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4981 SDValue Operand, SelectionDAG &DAG,
4982 int &ExtraSteps) {
4983 EVT VT = Operand.getValueType();
4984 if (ST->hasNEON() &&
4985 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4986 VT == MVT::f32 || VT == MVT::v1f32 ||
4987 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4988 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4989 // For the reciprocal estimates, convergence is quadratic, so the number
4990 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4991 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4992 // the result for float (23 mantissa bits) is 2 and for double (52
4993 // mantissa bits) is 3.
Evandro Menezes9dcf0992017-11-03 18:56:36 +00004994 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004995
4996 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4997 }
4998
4999 return SDValue();
5000}
5001
Evandro Menezes21f9ce12016-11-10 23:31:06 +00005002SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5003 SelectionDAG &DAG, int Enabled,
5004 int &ExtraSteps,
5005 bool &UseOneConst,
5006 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005007 if (Enabled == ReciprocalEstimate::Enabled ||
5008 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5009 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5010 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00005011 SDLoc DL(Operand);
5012 EVT VT = Operand.getValueType();
5013
5014 SDNodeFlags Flags;
5015 Flags.setUnsafeAlgebra(true);
5016
5017 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5018 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5019 for (int i = ExtraSteps; i > 0; --i) {
5020 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005021 Flags);
5022 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5023 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005024 }
Evandro Menezes9fc54822016-11-14 23:29:01 +00005025 if (!Reciprocal) {
5026 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5027 VT);
5028 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5029 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5030
Amara Emersond28f0cd42017-05-01 15:17:51 +00005031 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005032 // Correct the result if the operand is 0.0.
5033 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5034 VT, Eq, Operand, Estimate);
5035 }
5036
5037 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005038 return Estimate;
5039 }
5040
5041 return SDValue();
5042}
5043
5044SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5045 SelectionDAG &DAG, int Enabled,
5046 int &ExtraSteps) const {
5047 if (Enabled == ReciprocalEstimate::Enabled)
5048 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00005049 DAG, ExtraSteps)) {
5050 SDLoc DL(Operand);
5051 EVT VT = Operand.getValueType();
5052
5053 SDNodeFlags Flags;
5054 Flags.setUnsafeAlgebra(true);
5055
5056 // Newton reciprocal iteration: E * (2 - X * E)
5057 // AArch64 reciprocal iteration instruction: (2 - M * N)
5058 for (int i = ExtraSteps; i > 0; --i) {
5059 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
Amara Emersond28f0cd42017-05-01 15:17:51 +00005060 Estimate, Flags);
5061 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
Evandro Menezes9fc54822016-11-14 23:29:01 +00005062 }
5063
5064 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005065 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00005066 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00005067
5068 return SDValue();
5069}
5070
Tim Northover3b0846e2014-05-24 12:50:23 +00005071//===----------------------------------------------------------------------===//
5072// AArch64 Inline Assembly Support
5073//===----------------------------------------------------------------------===//
5074
5075// Table of Constraints
5076// TODO: This is the current set of constraints supported by ARM for the
5077// compiler, not all of them may make sense, e.g. S may be difficult to support.
5078//
5079// r - A general register
5080// w - An FP/SIMD register of some size in the range v0-v31
5081// x - An FP/SIMD register of some size in the range v0-v15
5082// I - Constant that can be used with an ADD instruction
5083// J - Constant that can be used with a SUB instruction
5084// K - Constant that can be used with a 32-bit logical instruction
5085// L - Constant that can be used with a 64-bit logical instruction
5086// M - Constant that can be used as a 32-bit MOV immediate
5087// N - Constant that can be used as a 64-bit MOV immediate
5088// Q - A memory reference with base register and no offset
5089// S - A symbolic address
5090// Y - Floating point constant zero
5091// Z - Integer constant zero
5092//
5093// Note that general register operands will be output using their 64-bit x
5094// register name, whatever the size of the variable, unless the asm operand
5095// is prefixed by the %w modifier. Floating-point and SIMD register operands
5096// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5097// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00005098const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5099 // At this point, we have to lower this constraint to something else, so we
5100 // lower it to an "r" or "w". However, by doing this we will force the result
5101 // to be in register, while the X constraint is much more permissive.
5102 //
5103 // Although we are correct (we are free to emit anything, without
5104 // constraints), we might break use cases that would expect us to be more
5105 // efficient and emit something else.
5106 if (!Subtarget->hasFPARMv8())
5107 return "r";
5108
5109 if (ConstraintVT.isFloatingPoint())
5110 return "w";
5111
5112 if (ConstraintVT.isVector() &&
5113 (ConstraintVT.getSizeInBits() == 64 ||
5114 ConstraintVT.getSizeInBits() == 128))
5115 return "w";
5116
5117 return "r";
5118}
Tim Northover3b0846e2014-05-24 12:50:23 +00005119
5120/// getConstraintType - Given a constraint letter, return the type of
5121/// constraint it is for this target.
5122AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005123AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005124 if (Constraint.size() == 1) {
5125 switch (Constraint[0]) {
5126 default:
5127 break;
5128 case 'z':
5129 return C_Other;
5130 case 'x':
5131 case 'w':
5132 return C_RegisterClass;
5133 // An address with a single base register. Due to the way we
5134 // currently handle addresses it is the same as 'r'.
5135 case 'Q':
5136 return C_Memory;
5137 }
5138 }
5139 return TargetLowering::getConstraintType(Constraint);
5140}
5141
5142/// Examine constraint type and operand type and determine a weight value.
5143/// This object must already have been set up with the operand type
5144/// and the current alternative constraint selected.
5145TargetLowering::ConstraintWeight
5146AArch64TargetLowering::getSingleConstraintMatchWeight(
5147 AsmOperandInfo &info, const char *constraint) const {
5148 ConstraintWeight weight = CW_Invalid;
5149 Value *CallOperandVal = info.CallOperandVal;
5150 // If we don't have a value, we can't do a match,
5151 // but allow it at the lowest weight.
5152 if (!CallOperandVal)
5153 return CW_Default;
5154 Type *type = CallOperandVal->getType();
5155 // Look at the constraint type.
5156 switch (*constraint) {
5157 default:
5158 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5159 break;
5160 case 'x':
5161 case 'w':
5162 if (type->isFloatingPointTy() || type->isVectorTy())
5163 weight = CW_Register;
5164 break;
5165 case 'z':
5166 weight = CW_Constant;
5167 break;
5168 }
5169 return weight;
5170}
5171
5172std::pair<unsigned, const TargetRegisterClass *>
5173AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005174 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00005175 if (Constraint.size() == 1) {
5176 switch (Constraint[0]) {
5177 case 'r':
5178 if (VT.getSizeInBits() == 64)
5179 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5180 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5181 case 'w':
Amara Emerson614b44b2016-11-07 15:42:12 +00005182 if (VT.getSizeInBits() == 16)
5183 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00005184 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00005185 return std::make_pair(0U, &AArch64::FPR32RegClass);
5186 if (VT.getSizeInBits() == 64)
5187 return std::make_pair(0U, &AArch64::FPR64RegClass);
5188 if (VT.getSizeInBits() == 128)
5189 return std::make_pair(0U, &AArch64::FPR128RegClass);
5190 break;
5191 // The instructions that this constraint is designed for can
5192 // only take 128-bit registers so just use that regclass.
5193 case 'x':
5194 if (VT.getSizeInBits() == 128)
5195 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5196 break;
5197 }
5198 }
5199 if (StringRef("{cc}").equals_lower(Constraint))
5200 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5201
5202 // Use the default implementation in TargetLowering to convert the register
5203 // constraint into a member of a register class.
5204 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00005205 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00005206
5207 // Not found as a standard register?
5208 if (!Res.second) {
5209 unsigned Size = Constraint.size();
5210 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5211 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00005212 int RegNo;
5213 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5214 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00005215 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00005216 // By default we'll emit v0-v31 for this unless there's a modifier where
5217 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00005218 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5219 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5220 Res.second = &AArch64::FPR64RegClass;
5221 } else {
5222 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5223 Res.second = &AArch64::FPR128RegClass;
5224 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005225 }
5226 }
5227 }
5228
5229 return Res;
5230}
5231
5232/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5233/// vector. If it is invalid, don't add anything to Ops.
5234void AArch64TargetLowering::LowerAsmOperandForConstraint(
5235 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5236 SelectionDAG &DAG) const {
5237 SDValue Result;
5238
5239 // Currently only support length 1 constraints.
5240 if (Constraint.length() != 1)
5241 return;
5242
5243 char ConstraintLetter = Constraint[0];
5244 switch (ConstraintLetter) {
5245 default:
5246 break;
5247
5248 // This set of constraints deal with valid constants for various instructions.
5249 // Validate and return a target constant for them if we can.
5250 case 'z': {
5251 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00005252 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00005253 return;
5254
5255 if (Op.getValueType() == MVT::i64)
5256 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5257 else
5258 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5259 break;
5260 }
5261
5262 case 'I':
5263 case 'J':
5264 case 'K':
5265 case 'L':
5266 case 'M':
5267 case 'N':
5268 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5269 if (!C)
5270 return;
5271
5272 // Grab the value and do some validation.
5273 uint64_t CVal = C->getZExtValue();
5274 switch (ConstraintLetter) {
5275 // The I constraint applies only to simple ADD or SUB immediate operands:
5276 // i.e. 0 to 4095 with optional shift by 12
5277 // The J constraint applies only to ADD or SUB immediates that would be
5278 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5279 // instruction [or vice versa], in other words -1 to -4095 with optional
5280 // left shift by 12.
5281 case 'I':
5282 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5283 break;
5284 return;
5285 case 'J': {
5286 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00005287 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5288 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005289 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00005290 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005291 return;
5292 }
5293 // The K and L constraints apply *only* to logical immediates, including
5294 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5295 // been removed and MOV should be used). So these constraints have to
5296 // distinguish between bit patterns that are valid 32-bit or 64-bit
5297 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5298 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5299 // versa.
5300 case 'K':
5301 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5302 break;
5303 return;
5304 case 'L':
5305 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5306 break;
5307 return;
5308 // The M and N constraints are a superset of K and L respectively, for use
5309 // with the MOV (immediate) alias. As well as the logical immediates they
5310 // also match 32 or 64-bit immediates that can be loaded either using a
5311 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5312 // (M) or 64-bit 0x1234000000000000 (N) etc.
5313 // As a note some of this code is liberally stolen from the asm parser.
5314 case 'M': {
5315 if (!isUInt<32>(CVal))
5316 return;
5317 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5318 break;
5319 if ((CVal & 0xFFFF) == CVal)
5320 break;
5321 if ((CVal & 0xFFFF0000ULL) == CVal)
5322 break;
5323 uint64_t NCVal = ~(uint32_t)CVal;
5324 if ((NCVal & 0xFFFFULL) == NCVal)
5325 break;
5326 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5327 break;
5328 return;
5329 }
5330 case 'N': {
5331 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5332 break;
5333 if ((CVal & 0xFFFFULL) == CVal)
5334 break;
5335 if ((CVal & 0xFFFF0000ULL) == CVal)
5336 break;
5337 if ((CVal & 0xFFFF00000000ULL) == CVal)
5338 break;
5339 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5340 break;
5341 uint64_t NCVal = ~CVal;
5342 if ((NCVal & 0xFFFFULL) == NCVal)
5343 break;
5344 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5345 break;
5346 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5347 break;
5348 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5349 break;
5350 return;
5351 }
5352 default:
5353 return;
5354 }
5355
5356 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005357 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005358 break;
5359 }
5360
5361 if (Result.getNode()) {
5362 Ops.push_back(Result);
5363 return;
5364 }
5365
5366 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5367}
5368
5369//===----------------------------------------------------------------------===//
5370// AArch64 Advanced SIMD Support
5371//===----------------------------------------------------------------------===//
5372
5373/// WidenVector - Given a value in the V64 register class, produce the
5374/// equivalent value in the V128 register class.
5375static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5376 EVT VT = V64Reg.getValueType();
5377 unsigned NarrowSize = VT.getVectorNumElements();
5378 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5379 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5380 SDLoc DL(V64Reg);
5381
5382 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005383 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005384}
5385
5386/// getExtFactor - Determine the adjustment factor for the position when
5387/// generating an "extract from vector registers" instruction.
5388static unsigned getExtFactor(SDValue &V) {
5389 EVT EltType = V.getValueType().getVectorElementType();
5390 return EltType.getSizeInBits() / 8;
5391}
5392
5393/// NarrowVector - Given a value in the V128 register class, produce the
5394/// equivalent value in the V64 register class.
5395static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5396 EVT VT = V128Reg.getValueType();
5397 unsigned WideSize = VT.getVectorNumElements();
5398 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5399 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5400 SDLoc DL(V128Reg);
5401
5402 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5403}
5404
5405// Gather data to see if the operation can be modelled as a
5406// shuffle in combination with VEXTs.
5407SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5408 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005409 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005410 DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005411 SDLoc dl(Op);
5412 EVT VT = Op.getValueType();
5413 unsigned NumElts = VT.getVectorNumElements();
5414
Tim Northover7324e842014-07-24 15:39:55 +00005415 struct ShuffleSourceInfo {
5416 SDValue Vec;
5417 unsigned MinElt;
5418 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005419
Tim Northover7324e842014-07-24 15:39:55 +00005420 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5421 // be compatible with the shuffle we intend to construct. As a result
5422 // ShuffleVec will be some sliding window into the original Vec.
5423 SDValue ShuffleVec;
5424
5425 // Code should guarantee that element i in Vec starts at element "WindowBase
5426 // + i * WindowScale in ShuffleVec".
5427 int WindowBase;
5428 int WindowScale;
5429
Tim Northover7324e842014-07-24 15:39:55 +00005430 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005431 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5432 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5433
5434 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005435 };
5436
5437 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5438 // node.
5439 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005440 for (unsigned i = 0; i < NumElts; ++i) {
5441 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005442 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005443 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005444 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5445 !isa<ConstantSDNode>(V.getOperand(1))) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005446 DEBUG(dbgs() << "Reshuffle failed: "
5447 "a shuffle can only come from building a vector from "
5448 "various elements of other vectors, provided their "
5449 "indices are constant\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005450 return SDValue();
5451 }
5452
Tim Northover7324e842014-07-24 15:39:55 +00005453 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005454 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005455 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005456 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005457 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005458
Tim Northover7324e842014-07-24 15:39:55 +00005459 // Update the minimum and maximum lane number seen.
5460 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5461 Source->MinElt = std::min(Source->MinElt, EltNo);
5462 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005463 }
5464
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005465 if (Sources.size() > 2) {
5466 DEBUG(dbgs() << "Reshuffle failed: currently only do something sane when at "
5467 "most two source vectors are involved\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005468 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005469 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005470
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005471 // Find out the smallest element size among result and two sources, and use
5472 // it as element size to build the shuffle_vector.
5473 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005474 for (auto &Source : Sources) {
5475 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005476 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5477 SmallestEltTy = SrcEltTy;
5478 }
5479 }
5480 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005481 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005482 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5483 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005484
Tim Northover7324e842014-07-24 15:39:55 +00005485 // If the source vector is too wide or too narrow, we may nevertheless be able
5486 // to construct a compatible shuffle either by concatenating it with UNDEF or
5487 // extracting a suitable range of elements.
5488 for (auto &Src : Sources) {
5489 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005490
Tim Northover7324e842014-07-24 15:39:55 +00005491 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005492 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005493
5494 // This stage of the search produces a source with the same element type as
5495 // the original, but with a total width matching the BUILD_VECTOR output.
5496 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005497 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5498 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005499
5500 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5501 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005502 // We can pad out the smaller vector for free, so if it's part of a
5503 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005504 Src.ShuffleVec =
5505 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5506 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005507 continue;
5508 }
5509
Tim Northover7324e842014-07-24 15:39:55 +00005510 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005511
James Molloyf497d552014-10-17 17:06:31 +00005512 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005513 DEBUG(dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00005514 return SDValue();
5515 }
5516
James Molloyf497d552014-10-17 17:06:31 +00005517 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005518 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005519 Src.ShuffleVec =
5520 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005521 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005522 Src.WindowBase = -NumSrcElts;
5523 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005524 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005525 Src.ShuffleVec =
5526 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005527 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005528 } else {
5529 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005530 SDValue VEXTSrc1 =
5531 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005532 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005533 SDValue VEXTSrc2 =
5534 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005535 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005536 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5537
5538 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005539 VEXTSrc2,
5540 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005541 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005542 }
5543 }
5544
Tim Northover7324e842014-07-24 15:39:55 +00005545 // Another possible incompatibility occurs from the vector element types. We
5546 // can fix this by bitcasting the source vectors to the same type we intend
5547 // for the shuffle.
5548 for (auto &Src : Sources) {
5549 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5550 if (SrcEltTy == SmallestEltTy)
5551 continue;
5552 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5553 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5554 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5555 Src.WindowBase *= Src.WindowScale;
5556 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005557
Tim Northover7324e842014-07-24 15:39:55 +00005558 // Final sanity check before we try to actually produce a shuffle.
5559 DEBUG(
5560 for (auto Src : Sources)
5561 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5562 );
5563
5564 // The stars all align, our next step is to produce the mask for the shuffle.
5565 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005566 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005567 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005568 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005569 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005570 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005571
David Majnemer0d955d02016-08-11 22:21:41 +00005572 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005573 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5574
5575 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5576 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5577 // segment.
5578 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005579 int BitsDefined =
5580 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00005581 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5582
5583 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5584 // starting at the appropriate offset.
5585 int *LaneMask = &Mask[i * ResMultiplier];
5586
5587 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5588 ExtractBase += NumElts * (Src - Sources.begin());
5589 for (int j = 0; j < LanesDefined; ++j)
5590 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005591 }
5592
5593 // Final check before we try to produce nonsense...
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005594 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
5595 DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
Tim Northover7324e842014-07-24 15:39:55 +00005596 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005597 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005598
Tim Northover7324e842014-07-24 15:39:55 +00005599 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5600 for (unsigned i = 0; i < Sources.size(); ++i)
5601 ShuffleOps[i] = Sources[i].ShuffleVec;
5602
5603 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005604 ShuffleOps[1], Mask);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00005605 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5606
5607 DEBUG(
5608 dbgs() << "Reshuffle, creating node: ";
5609 Shuffle.dump();
5610 dbgs() << "Reshuffle, creating node: ";
5611 V.dump();
5612 );
5613
5614 return V;
Tim Northover3b0846e2014-05-24 12:50:23 +00005615}
5616
5617// check if an EXT instruction can handle the shuffle mask when the
5618// vector sources of the shuffle are the same.
5619static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5620 unsigned NumElts = VT.getVectorNumElements();
5621
5622 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5623 if (M[0] < 0)
5624 return false;
5625
5626 Imm = M[0];
5627
5628 // If this is a VEXT shuffle, the immediate value is the index of the first
5629 // element. The other shuffle indices must be the successive elements after
5630 // the first one.
5631 unsigned ExpectedElt = Imm;
5632 for (unsigned i = 1; i < NumElts; ++i) {
5633 // Increment the expected index. If it wraps around, just follow it
5634 // back to index zero and keep going.
5635 ++ExpectedElt;
5636 if (ExpectedElt == NumElts)
5637 ExpectedElt = 0;
5638
5639 if (M[i] < 0)
5640 continue; // ignore UNDEF indices
5641 if (ExpectedElt != static_cast<unsigned>(M[i]))
5642 return false;
5643 }
5644
5645 return true;
5646}
5647
5648// check if an EXT instruction can handle the shuffle mask when the
5649// vector sources of the shuffle are different.
5650static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5651 unsigned &Imm) {
5652 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005653 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005654
5655 // Benefit form APInt to handle overflow when calculating expected element.
5656 unsigned NumElts = VT.getVectorNumElements();
5657 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5658 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5659 // The following shuffle indices must be the successive elements after the
5660 // first real element.
5661 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5662 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5663 if (FirstWrongElt != M.end())
5664 return false;
5665
5666 // The index of an EXT is the first element if it is not UNDEF.
5667 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005668 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005669 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5670 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5671 // ExpectedElt is the last mask index plus 1.
5672 Imm = ExpectedElt.getZExtValue();
5673
5674 // There are two difference cases requiring to reverse input vectors.
5675 // For example, for vector <4 x i32> we have the following cases,
5676 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5677 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5678 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5679 // to reverse two input vectors.
5680 if (Imm < NumElts)
5681 ReverseEXT = true;
5682 else
5683 Imm -= NumElts;
5684
5685 return true;
5686}
5687
5688/// isREVMask - Check if a vector shuffle corresponds to a REV
5689/// instruction with the specified blocksize. (The order of the elements
5690/// within each block of the vector is reversed.)
5691static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5692 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5693 "Only possible block sizes for REV are: 16, 32, 64");
5694
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005695 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00005696 if (EltSz == 64)
5697 return false;
5698
5699 unsigned NumElts = VT.getVectorNumElements();
5700 unsigned BlockElts = M[0] + 1;
5701 // If the first shuffle index is UNDEF, be optimistic.
5702 if (M[0] < 0)
5703 BlockElts = BlockSize / EltSz;
5704
5705 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5706 return false;
5707
5708 for (unsigned i = 0; i < NumElts; ++i) {
5709 if (M[i] < 0)
5710 continue; // ignore UNDEF indices
5711 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5712 return false;
5713 }
5714
5715 return true;
5716}
5717
5718static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5719 unsigned NumElts = VT.getVectorNumElements();
5720 WhichResult = (M[0] == 0 ? 0 : 1);
5721 unsigned Idx = WhichResult * NumElts / 2;
5722 for (unsigned i = 0; i != NumElts; i += 2) {
5723 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5724 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5725 return false;
5726 Idx += 1;
5727 }
5728
5729 return true;
5730}
5731
5732static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5733 unsigned NumElts = VT.getVectorNumElements();
5734 WhichResult = (M[0] == 0 ? 0 : 1);
5735 for (unsigned i = 0; i != NumElts; ++i) {
5736 if (M[i] < 0)
5737 continue; // ignore UNDEF indices
5738 if ((unsigned)M[i] != 2 * i + WhichResult)
5739 return false;
5740 }
5741
5742 return true;
5743}
5744
5745static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5746 unsigned NumElts = VT.getVectorNumElements();
5747 WhichResult = (M[0] == 0 ? 0 : 1);
5748 for (unsigned i = 0; i < NumElts; i += 2) {
5749 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5750 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5751 return false;
5752 }
5753 return true;
5754}
5755
5756/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5757/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5758/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5759static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5760 unsigned NumElts = VT.getVectorNumElements();
5761 WhichResult = (M[0] == 0 ? 0 : 1);
5762 unsigned Idx = WhichResult * NumElts / 2;
5763 for (unsigned i = 0; i != NumElts; i += 2) {
5764 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5765 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5766 return false;
5767 Idx += 1;
5768 }
5769
5770 return true;
5771}
5772
5773/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5774/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5775/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5776static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5777 unsigned Half = VT.getVectorNumElements() / 2;
5778 WhichResult = (M[0] == 0 ? 0 : 1);
5779 for (unsigned j = 0; j != 2; ++j) {
5780 unsigned Idx = WhichResult;
5781 for (unsigned i = 0; i != Half; ++i) {
5782 int MIdx = M[i + j * Half];
5783 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5784 return false;
5785 Idx += 2;
5786 }
5787 }
5788
5789 return true;
5790}
5791
5792/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5793/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5794/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5795static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5796 unsigned NumElts = VT.getVectorNumElements();
5797 WhichResult = (M[0] == 0 ? 0 : 1);
5798 for (unsigned i = 0; i < NumElts; i += 2) {
5799 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5800 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5801 return false;
5802 }
5803 return true;
5804}
5805
5806static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5807 bool &DstIsLeft, int &Anomaly) {
5808 if (M.size() != static_cast<size_t>(NumInputElements))
5809 return false;
5810
5811 int NumLHSMatch = 0, NumRHSMatch = 0;
5812 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5813
5814 for (int i = 0; i < NumInputElements; ++i) {
5815 if (M[i] == -1) {
5816 ++NumLHSMatch;
5817 ++NumRHSMatch;
5818 continue;
5819 }
5820
5821 if (M[i] == i)
5822 ++NumLHSMatch;
5823 else
5824 LastLHSMismatch = i;
5825
5826 if (M[i] == i + NumInputElements)
5827 ++NumRHSMatch;
5828 else
5829 LastRHSMismatch = i;
5830 }
5831
5832 if (NumLHSMatch == NumInputElements - 1) {
5833 DstIsLeft = true;
5834 Anomaly = LastLHSMismatch;
5835 return true;
5836 } else if (NumRHSMatch == NumInputElements - 1) {
5837 DstIsLeft = false;
5838 Anomaly = LastRHSMismatch;
5839 return true;
5840 }
5841
5842 return false;
5843}
5844
5845static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5846 if (VT.getSizeInBits() != 128)
5847 return false;
5848
5849 unsigned NumElts = VT.getVectorNumElements();
5850
5851 for (int I = 0, E = NumElts / 2; I != E; I++) {
5852 if (Mask[I] != I)
5853 return false;
5854 }
5855
5856 int Offset = NumElts / 2;
5857 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5858 if (Mask[I] != I + SplitLHS * Offset)
5859 return false;
5860 }
5861
5862 return true;
5863}
5864
5865static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5866 SDLoc DL(Op);
5867 EVT VT = Op.getValueType();
5868 SDValue V0 = Op.getOperand(0);
5869 SDValue V1 = Op.getOperand(1);
5870 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5871
5872 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5873 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5874 return SDValue();
5875
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005876 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00005877
5878 if (!isConcatMask(Mask, VT, SplitV0))
5879 return SDValue();
5880
5881 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5882 VT.getVectorNumElements() / 2);
5883 if (SplitV0) {
5884 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005885 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005886 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005887 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005888 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005889 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005890 }
5891 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5892}
5893
5894/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5895/// the specified operations to build the shuffle.
5896static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5897 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005898 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005899 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5900 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5901 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5902
5903 enum {
5904 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5905 OP_VREV,
5906 OP_VDUP0,
5907 OP_VDUP1,
5908 OP_VDUP2,
5909 OP_VDUP3,
5910 OP_VEXT1,
5911 OP_VEXT2,
5912 OP_VEXT3,
5913 OP_VUZPL, // VUZP, left result
5914 OP_VUZPR, // VUZP, right result
5915 OP_VZIPL, // VZIP, left result
5916 OP_VZIPR, // VZIP, right result
5917 OP_VTRNL, // VTRN, left result
5918 OP_VTRNR // VTRN, right result
5919 };
5920
5921 if (OpNum == OP_COPY) {
5922 if (LHSID == (1 * 9 + 2) * 9 + 3)
5923 return LHS;
5924 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5925 return RHS;
5926 }
5927
5928 SDValue OpLHS, OpRHS;
5929 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5930 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5931 EVT VT = OpLHS.getValueType();
5932
5933 switch (OpNum) {
5934 default:
5935 llvm_unreachable("Unknown shuffle opcode!");
5936 case OP_VREV:
5937 // VREV divides the vector in half and swaps within the half.
5938 if (VT.getVectorElementType() == MVT::i32 ||
5939 VT.getVectorElementType() == MVT::f32)
5940 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5941 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005942 if (VT.getVectorElementType() == MVT::i16 ||
5943 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005944 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5945 // vrev <4 x i8> -> REV16
5946 assert(VT.getVectorElementType() == MVT::i8);
5947 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5948 case OP_VDUP0:
5949 case OP_VDUP1:
5950 case OP_VDUP2:
5951 case OP_VDUP3: {
5952 EVT EltTy = VT.getVectorElementType();
5953 unsigned Opcode;
5954 if (EltTy == MVT::i8)
5955 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005956 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005957 Opcode = AArch64ISD::DUPLANE16;
5958 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5959 Opcode = AArch64ISD::DUPLANE32;
5960 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5961 Opcode = AArch64ISD::DUPLANE64;
5962 else
5963 llvm_unreachable("Invalid vector element type?");
5964
5965 if (VT.getSizeInBits() == 64)
5966 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005967 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005968 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5969 }
5970 case OP_VEXT1:
5971 case OP_VEXT2:
5972 case OP_VEXT3: {
5973 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5974 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005975 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005976 }
5977 case OP_VUZPL:
5978 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5979 OpRHS);
5980 case OP_VUZPR:
5981 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5982 OpRHS);
5983 case OP_VZIPL:
5984 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5985 OpRHS);
5986 case OP_VZIPR:
5987 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5988 OpRHS);
5989 case OP_VTRNL:
5990 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5991 OpRHS);
5992 case OP_VTRNR:
5993 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5994 OpRHS);
5995 }
5996}
5997
5998static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5999 SelectionDAG &DAG) {
6000 // Check to see if we can use the TBL instruction.
6001 SDValue V1 = Op.getOperand(0);
6002 SDValue V2 = Op.getOperand(1);
6003 SDLoc DL(Op);
6004
6005 EVT EltVT = Op.getValueType().getVectorElementType();
6006 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6007
6008 SmallVector<SDValue, 8> TBLMask;
6009 for (int Val : ShuffleMask) {
6010 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6011 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006012 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006013 }
6014 }
6015
6016 MVT IndexVT = MVT::v8i8;
6017 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006018 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006019 IndexVT = MVT::v16i8;
6020 IndexLen = 16;
6021 }
6022
6023 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6024 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6025
6026 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00006027 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006028 if (IndexLen == 8)
6029 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6030 Shuffle = DAG.getNode(
6031 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006032 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006033 DAG.getBuildVector(IndexVT, DL,
6034 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006035 } else {
6036 if (IndexLen == 8) {
6037 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6038 Shuffle = DAG.getNode(
6039 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006040 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006041 DAG.getBuildVector(IndexVT, DL,
6042 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006043 } else {
6044 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6045 // cannot currently represent the register constraints on the input
6046 // table registers.
6047 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006048 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6049 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00006050 Shuffle = DAG.getNode(
6051 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006052 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6053 V2Cst, DAG.getBuildVector(IndexVT, DL,
6054 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00006055 }
6056 }
6057 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6058}
6059
6060static unsigned getDUPLANEOp(EVT EltType) {
6061 if (EltType == MVT::i8)
6062 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00006063 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006064 return AArch64ISD::DUPLANE16;
6065 if (EltType == MVT::i32 || EltType == MVT::f32)
6066 return AArch64ISD::DUPLANE32;
6067 if (EltType == MVT::i64 || EltType == MVT::f64)
6068 return AArch64ISD::DUPLANE64;
6069
6070 llvm_unreachable("Invalid vector element type?");
6071}
6072
6073SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6074 SelectionDAG &DAG) const {
6075 SDLoc dl(Op);
6076 EVT VT = Op.getValueType();
6077
6078 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6079
6080 // Convert shuffles that are directly supported on NEON to target-specific
6081 // DAG nodes, instead of keeping them as shuffles and matching them again
6082 // during code selection. This is more efficient and avoids the possibility
6083 // of inconsistencies between legalization and selection.
6084 ArrayRef<int> ShuffleMask = SVN->getMask();
6085
6086 SDValue V1 = Op.getOperand(0);
6087 SDValue V2 = Op.getOperand(1);
6088
Craig Topperbc56e3b2016-06-30 04:38:51 +00006089 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006090 int Lane = SVN->getSplatIndex();
6091 // If this is undef splat, generate it via "just" vdup, if possible.
6092 if (Lane == -1)
6093 Lane = 0;
6094
6095 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6096 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6097 V1.getOperand(0));
6098 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6099 // constant. If so, we can just reference the lane's definition directly.
6100 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6101 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6102 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6103
6104 // Otherwise, duplicate from the lane of the input vector.
6105 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6106
6107 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6108 // to make a vector of the same size as this SHUFFLE. We can ignore the
6109 // extract entirely, and canonicalise the concat using WidenVector.
6110 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6111 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6112 V1 = V1.getOperand(0);
6113 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6114 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6115 Lane -= Idx * VT.getVectorNumElements() / 2;
6116 V1 = WidenVector(V1.getOperand(Idx), DAG);
6117 } else if (VT.getSizeInBits() == 64)
6118 V1 = WidenVector(V1, DAG);
6119
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006120 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00006121 }
6122
6123 if (isREVMask(ShuffleMask, VT, 64))
6124 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6125 if (isREVMask(ShuffleMask, VT, 32))
6126 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6127 if (isREVMask(ShuffleMask, VT, 16))
6128 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6129
6130 bool ReverseEXT = false;
6131 unsigned Imm;
6132 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6133 if (ReverseEXT)
6134 std::swap(V1, V2);
6135 Imm *= getExtFactor(V1);
6136 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006137 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00006138 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006139 Imm *= getExtFactor(V1);
6140 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006141 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006142 }
6143
6144 unsigned WhichResult;
6145 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6146 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6147 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6148 }
6149 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6150 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6151 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6152 }
6153 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6154 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6155 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6156 }
6157
6158 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6159 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6160 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6161 }
6162 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6163 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6164 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6165 }
6166 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6167 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6168 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6169 }
6170
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006171 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006172 return Concat;
6173
6174 bool DstIsLeft;
6175 int Anomaly;
6176 int NumInputElements = V1.getValueType().getVectorNumElements();
6177 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6178 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006179 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006180
6181 SDValue SrcVec = V1;
6182 int SrcLane = ShuffleMask[Anomaly];
6183 if (SrcLane >= NumInputElements) {
6184 SrcVec = V2;
6185 SrcLane -= VT.getVectorNumElements();
6186 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006187 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006188
6189 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00006190
6191 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006192 ScalarVT = MVT::i32;
6193
6194 return DAG.getNode(
6195 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6196 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6197 DstLaneV);
6198 }
6199
6200 // If the shuffle is not directly supported and it has 4 elements, use
6201 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6202 unsigned NumElts = VT.getVectorNumElements();
6203 if (NumElts == 4) {
6204 unsigned PFIndexes[4];
6205 for (unsigned i = 0; i != 4; ++i) {
6206 if (ShuffleMask[i] < 0)
6207 PFIndexes[i] = 8;
6208 else
6209 PFIndexes[i] = ShuffleMask[i];
6210 }
6211
6212 // Compute the index in the perfect shuffle table.
6213 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6214 PFIndexes[2] * 9 + PFIndexes[3];
6215 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6216 unsigned Cost = (PFEntry >> 30);
6217
6218 if (Cost <= 4)
6219 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6220 }
6221
6222 return GenerateTBL(Op, ShuffleMask, DAG);
6223}
6224
6225static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6226 APInt &UndefBits) {
6227 EVT VT = BVN->getValueType(0);
6228 APInt SplatBits, SplatUndef;
6229 unsigned SplatBitSize;
6230 bool HasAnyUndefs;
6231 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6232 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6233
6234 for (unsigned i = 0; i < NumSplats; ++i) {
6235 CnstBits <<= SplatBitSize;
6236 UndefBits <<= SplatBitSize;
6237 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6238 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6239 }
6240
6241 return true;
6242 }
6243
6244 return false;
6245}
6246
Evandro Menezes72f39832018-02-20 20:31:45 +00006247// Try 64-bit splatted SIMD immediate.
6248static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6249 const APInt &Bits) {
6250 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6251 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6252 EVT VT = Op.getValueType();
6253 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6254
6255 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6256 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6257
6258 SDLoc dl(Op);
6259 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6260 DAG.getConstant(Value, dl, MVT::i32));
6261 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6262 }
6263 }
6264
6265 return SDValue();
6266}
6267
6268// Try 32-bit splatted SIMD immediate.
6269static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6270 const APInt &Bits,
6271 const SDValue *LHS = nullptr) {
6272 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6273 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6274 EVT VT = Op.getValueType();
6275 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6276 bool isAdvSIMDModImm = false;
6277 uint64_t Shift;
6278
6279 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6280 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6281 Shift = 0;
6282 }
6283 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6284 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6285 Shift = 8;
6286 }
6287 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6288 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6289 Shift = 16;
6290 }
6291 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6292 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6293 Shift = 24;
6294 }
6295
6296 if (isAdvSIMDModImm) {
6297 SDLoc dl(Op);
6298 SDValue Mov;
6299
6300 if (LHS)
6301 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6302 DAG.getConstant(Value, dl, MVT::i32),
6303 DAG.getConstant(Shift, dl, MVT::i32));
6304 else
6305 Mov = DAG.getNode(NewOp, dl, MovTy,
6306 DAG.getConstant(Value, dl, MVT::i32),
6307 DAG.getConstant(Shift, dl, MVT::i32));
6308
6309 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6310 }
6311 }
6312
6313 return SDValue();
6314}
6315
6316// Try 16-bit splatted SIMD immediate.
6317static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6318 const APInt &Bits,
6319 const SDValue *LHS = nullptr) {
6320 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6321 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6322 EVT VT = Op.getValueType();
6323 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6324 bool isAdvSIMDModImm = false;
6325 uint64_t Shift;
6326
6327 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6328 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6329 Shift = 0;
6330 }
6331 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6332 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6333 Shift = 8;
6334 }
6335
6336 if (isAdvSIMDModImm) {
6337 SDLoc dl(Op);
6338 SDValue Mov;
6339
6340 if (LHS)
6341 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6342 DAG.getConstant(Value, dl, MVT::i32),
6343 DAG.getConstant(Shift, dl, MVT::i32));
6344 else
6345 Mov = DAG.getNode(NewOp, dl, MovTy,
6346 DAG.getConstant(Value, dl, MVT::i32),
6347 DAG.getConstant(Shift, dl, MVT::i32));
6348
6349 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6350 }
6351 }
6352
6353 return SDValue();
6354}
6355
6356// Try 32-bit splatted SIMD immediate with shifted ones.
6357static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6358 SelectionDAG &DAG, const APInt &Bits) {
6359 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6360 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6361 EVT VT = Op.getValueType();
6362 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6363 bool isAdvSIMDModImm = false;
6364 uint64_t Shift;
6365
6366 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6367 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6368 Shift = 264;
6369 }
6370 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6371 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6372 Shift = 272;
6373 }
6374
6375 if (isAdvSIMDModImm) {
6376 SDLoc dl(Op);
6377 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6378 DAG.getConstant(Value, dl, MVT::i32),
6379 DAG.getConstant(Shift, dl, MVT::i32));
6380 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6381 }
6382 }
6383
6384 return SDValue();
6385}
6386
6387// Try 8-bit splatted SIMD immediate.
6388static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6389 const APInt &Bits) {
6390 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6391 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6392 EVT VT = Op.getValueType();
6393 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6394
6395 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6396 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6397
6398 SDLoc dl(Op);
6399 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6400 DAG.getConstant(Value, dl, MVT::i32));
6401 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6402 }
6403 }
6404
6405 return SDValue();
6406}
6407
6408// Try FP splatted SIMD immediate.
6409static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6410 const APInt &Bits) {
6411 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6412 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6413 EVT VT = Op.getValueType();
6414 bool isWide = (VT.getSizeInBits() == 128);
6415 MVT MovTy;
6416 bool isAdvSIMDModImm = false;
6417
6418 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6419 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6420 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6421 }
6422 else if (isWide &&
6423 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6424 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6425 MovTy = MVT::v2f64;
6426 }
6427
6428 if (isAdvSIMDModImm) {
6429 SDLoc dl(Op);
6430 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6431 DAG.getConstant(Value, dl, MVT::i32));
6432 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6433 }
6434 }
6435
6436 return SDValue();
6437}
6438
Tim Northover3b0846e2014-05-24 12:50:23 +00006439SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6440 SelectionDAG &DAG) const {
Hans Wennborgf381e942018-02-13 18:14:38 +00006441 SDValue LHS = Op.getOperand(0);
Hans Wennborgf381e942018-02-13 18:14:38 +00006442 EVT VT = Op.getValueType();
6443
Evandro Menezes72f39832018-02-20 20:31:45 +00006444 BuildVectorSDNode *BVN =
6445 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6446 if (!BVN) {
6447 // AND commutes, so try swapping the operands.
6448 LHS = Op.getOperand(1);
6449 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6450 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006451 if (!BVN)
6452 return Op;
6453
Evandro Menezes72f39832018-02-20 20:31:45 +00006454 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006455 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006456 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6457 SDValue NewOp;
6458
Tim Northover3b0846e2014-05-24 12:50:23 +00006459 // We only have BIC vector immediate instruction, which is and-not.
Evandro Menezes72f39832018-02-20 20:31:45 +00006460 DefBits = ~DefBits;
6461 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6462 DefBits, &LHS)) ||
6463 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6464 DefBits, &LHS)))
6465 return NewOp;
6466 else {
6467 DefBits = ~UndefBits;
6468 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
6469 DefBits, &LHS)) ||
6470 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
6471 DefBits, &LHS)))
6472 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006473 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006474 }
6475
Evandro Menezes72f39832018-02-20 20:31:45 +00006476 // We can always fall back to a non-immediate AND.
Tim Northover3b0846e2014-05-24 12:50:23 +00006477 return Op;
6478}
6479
6480// Specialized code to quickly find if PotentialBVec is a BuildVector that
6481// consists of only the same constant int value, returned in reference arg
6482// ConstVal
6483static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6484 uint64_t &ConstVal) {
6485 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6486 if (!Bvec)
6487 return false;
6488 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6489 if (!FirstElt)
6490 return false;
6491 EVT VT = Bvec->getValueType(0);
6492 unsigned NumElts = VT.getVectorNumElements();
6493 for (unsigned i = 1; i < NumElts; ++i)
6494 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6495 return false;
6496 ConstVal = FirstElt->getZExtValue();
6497 return true;
6498}
6499
6500static unsigned getIntrinsicID(const SDNode *N) {
6501 unsigned Opcode = N->getOpcode();
6502 switch (Opcode) {
6503 default:
6504 return Intrinsic::not_intrinsic;
6505 case ISD::INTRINSIC_WO_CHAIN: {
6506 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6507 if (IID < Intrinsic::num_intrinsics)
6508 return IID;
6509 return Intrinsic::not_intrinsic;
6510 }
6511 }
6512}
6513
6514// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6515// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6516// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6517// Also, logical shift right -> sri, with the same structure.
6518static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6519 EVT VT = N->getValueType(0);
6520
6521 if (!VT.isVector())
6522 return SDValue();
6523
6524 SDLoc DL(N);
6525
6526 // Is the first op an AND?
6527 const SDValue And = N->getOperand(0);
6528 if (And.getOpcode() != ISD::AND)
6529 return SDValue();
6530
6531 // Is the second op an shl or lshr?
6532 SDValue Shift = N->getOperand(1);
6533 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6534 // or AArch64ISD::VLSHR vector, #shift
6535 unsigned ShiftOpc = Shift.getOpcode();
6536 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6537 return SDValue();
6538 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6539
6540 // Is the shift amount constant?
6541 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6542 if (!C2node)
6543 return SDValue();
6544
6545 // Is the and mask vector all constant?
6546 uint64_t C1;
6547 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6548 return SDValue();
6549
6550 // Is C1 == ~C2, taking into account how much one can shift elements of a
6551 // particular size?
6552 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006553 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006554 if (C2 > ElemSizeInBits)
6555 return SDValue();
6556 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6557 if ((C1 & ElemMask) != (~C2 & ElemMask))
6558 return SDValue();
6559
6560 SDValue X = And.getOperand(0);
6561 SDValue Y = Shift.getOperand(0);
6562
6563 unsigned Intrin =
6564 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6565 SDValue ResultSLI =
6566 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006567 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6568 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00006569
6570 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6571 DEBUG(N->dump(&DAG));
6572 DEBUG(dbgs() << "into: \n");
6573 DEBUG(ResultSLI->dump(&DAG));
6574
6575 ++NumShiftInserts;
6576 return ResultSLI;
6577}
6578
6579SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6580 SelectionDAG &DAG) const {
6581 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6582 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006583 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006584 return Res;
6585 }
6586
Evandro Menezes72f39832018-02-20 20:31:45 +00006587 SDValue LHS = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006588 EVT VT = Op.getValueType();
6589
Evandro Menezes72f39832018-02-20 20:31:45 +00006590 BuildVectorSDNode *BVN =
6591 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006592 if (!BVN) {
Evandro Menezes72f39832018-02-20 20:31:45 +00006593 // OR commutes, so try swapping the operands.
6594 LHS = Op.getOperand(1);
6595 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006596 }
6597 if (!BVN)
6598 return Op;
6599
Evandro Menezes72f39832018-02-20 20:31:45 +00006600 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006601 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006602 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6603 SDValue NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006604
Evandro Menezes72f39832018-02-20 20:31:45 +00006605 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
6606 DefBits, &LHS)) ||
6607 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
6608 DefBits, &LHS)))
6609 return NewOp;
6610 else {
6611 DefBits = UndefBits;
6612 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
6613 DefBits, &LHS)) ||
6614 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
6615 DefBits, &LHS)))
6616 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006617 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006618 }
6619
Evandro Menezes72f39832018-02-20 20:31:45 +00006620 // We can always fall back to a non-immediate OR.
Tim Northover3b0846e2014-05-24 12:50:23 +00006621 return Op;
6622}
6623
Kevin Qin4473c192014-07-07 02:45:40 +00006624// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6625// be truncated to fit element width.
6626static SDValue NormalizeBuildVector(SDValue Op,
6627 SelectionDAG &DAG) {
6628 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006629 SDLoc dl(Op);
6630 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006631 EVT EltTy= VT.getVectorElementType();
6632
6633 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6634 return Op;
6635
6636 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006637 for (SDValue Lane : Op->ops()) {
6638 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006639 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006640 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006641 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006642 }
6643 Ops.push_back(Lane);
6644 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006645 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006646}
6647
6648SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6649 SelectionDAG &DAG) const {
6650 SDLoc dl(Op);
6651 EVT VT = Op.getValueType();
Evandro Menezes72f39832018-02-20 20:31:45 +00006652
Kevin Qin4473c192014-07-07 02:45:40 +00006653 Op = NormalizeBuildVector(Op, DAG);
6654 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Evandro Menezes72f39832018-02-20 20:31:45 +00006655 APInt DefBits(VT.getSizeInBits(), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006656 APInt UndefBits(VT.getSizeInBits(), 0);
Evandro Menezes72f39832018-02-20 20:31:45 +00006657 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
6658 // Certain magic vector constants (used to express things like NOT
6659 // and NEG) are passed through unmodified. This allows codegen patterns
6660 // for these operations to match. Special-purpose patterns will lower
6661 // these immediates to MOVI if it proves necessary.
6662 uint64_t DefVal = DefBits.zextOrTrunc(64).getZExtValue();
6663 if (DefBits.getHiBits(64) == DefBits.getLoBits(64) &&
6664 VT.isInteger() && (DefVal == 0 || DefVal == UINT64_MAX))
6665 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00006666
Evandro Menezes72f39832018-02-20 20:31:45 +00006667 SDValue NewOp;
6668 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
6669 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6670 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
6671 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6672 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
6673 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
6674 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006675
Evandro Menezes72f39832018-02-20 20:31:45 +00006676 DefBits = ~DefBits;
6677 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
6678 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
6679 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
6680 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006681
Evandro Menezes72f39832018-02-20 20:31:45 +00006682 DefBits = UndefBits;
6683 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
6684 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6685 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
6686 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
6687 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
6688 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
6689 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006690
Evandro Menezes72f39832018-02-20 20:31:45 +00006691 DefBits = ~UndefBits;
6692 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
6693 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
6694 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
6695 return NewOp;
Tim Northover3b0846e2014-05-24 12:50:23 +00006696 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006697
6698 // Scan through the operands to find some interesting properties we can
6699 // exploit:
6700 // 1) If only one value is used, we can use a DUP, or
6701 // 2) if only the low element is not undef, we can just insert that, or
6702 // 3) if only one constant value is used (w/ some non-constant lanes),
6703 // we can splat the constant value into the whole vector then fill
6704 // in the non-constant lanes.
6705 // 4) FIXME: If different constant values are used, but we can intelligently
6706 // select the values we'll be overwriting for the non-constant
6707 // lanes such that we can directly materialize the vector
6708 // some other way (MOVI, e.g.), we can be sneaky.
6709 unsigned NumElts = VT.getVectorNumElements();
6710 bool isOnlyLowElement = true;
6711 bool usesOnlyOneValue = true;
6712 bool usesOnlyOneConstantValue = true;
6713 bool isConstant = true;
6714 unsigned NumConstantLanes = 0;
6715 SDValue Value;
6716 SDValue ConstantValue;
6717 for (unsigned i = 0; i < NumElts; ++i) {
6718 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006719 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006720 continue;
6721 if (i > 0)
6722 isOnlyLowElement = false;
6723 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6724 isConstant = false;
6725
6726 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6727 ++NumConstantLanes;
6728 if (!ConstantValue.getNode())
6729 ConstantValue = V;
6730 else if (ConstantValue != V)
6731 usesOnlyOneConstantValue = false;
6732 }
6733
6734 if (!Value.getNode())
6735 Value = V;
6736 else if (V != Value)
6737 usesOnlyOneValue = false;
6738 }
6739
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006740 if (!Value.getNode()) {
6741 DEBUG(dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006742 return DAG.getUNDEF(VT);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006743 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006744
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006745 if (isOnlyLowElement) {
6746 DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
6747 "SCALAR_TO_VECTOR node\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006748 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006749 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006750
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006751 // Use DUP for non-constant splats. For f32 constant splats, reduce to
Tim Northover3b0846e2014-05-24 12:50:23 +00006752 // i32 and try again.
6753 if (usesOnlyOneValue) {
6754 if (!isConstant) {
6755 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006756 Value.getValueType() != VT) {
6757 DEBUG(dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006758 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006759 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006760
6761 // This is actually a DUPLANExx operation, which keeps everything vectory.
6762
Tim Northover3b0846e2014-05-24 12:50:23 +00006763 SDValue Lane = Value.getOperand(1);
6764 Value = Value.getOperand(0);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006765 if (Value.getValueSizeInBits() == 64) {
6766 DEBUG(dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
6767 "widening it\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006768 Value = WidenVector(Value, DAG);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006769 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006770
6771 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6772 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6773 }
6774
6775 if (VT.getVectorElementType().isFloatingPoint()) {
6776 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006777 EVT EltTy = VT.getVectorElementType();
6778 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6779 "Unsupported floating-point vector type");
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006780 DEBUG(dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
6781 "BITCASTS, and try again\n");
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006782 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006783 for (unsigned i = 0; i < NumElts; ++i)
6784 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6785 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006786 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006787 DEBUG(
6788 dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
6789 Val.dump();
6790 );
Tim Northover3b0846e2014-05-24 12:50:23 +00006791 Val = LowerBUILD_VECTOR(Val, DAG);
6792 if (Val.getNode())
6793 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6794 }
6795 }
6796
6797 // If there was only one constant value used and for more than one lane,
6798 // start by splatting that value, then replace the non-constant lanes. This
6799 // is better than the default, which will perform a separate initialization
6800 // for each lane.
6801 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6802 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6803 // Now insert the non-constant lanes.
6804 for (unsigned i = 0; i < NumElts; ++i) {
6805 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006806 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006807 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6808 // Note that type legalization likely mucked about with the VT of the
6809 // source operand, so we may have to convert it here before inserting.
6810 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6811 }
6812 }
6813 return Val;
6814 }
6815
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006816 // This will generate a load from the constant pool.
6817 if (isConstant) {
6818 DEBUG(dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
6819 "expansion\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006820 return SDValue();
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006821 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006822
6823 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6824 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006825 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006826 return shuffle;
6827 }
6828
6829 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6830 // know the default expansion would otherwise fall back on something even
6831 // worse. For a vector with one or two non-undef values, that's
6832 // scalar_to_vector for the elements followed by a shuffle (provided the
6833 // shuffle is valid for the target) and materialization element by element
6834 // on the stack followed by a load for everything else.
6835 if (!isConstant && !usesOnlyOneValue) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006836 DEBUG(dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
6837 "of INSERT_VECTOR_ELT\n");
6838
Tim Northover3b0846e2014-05-24 12:50:23 +00006839 SDValue Vec = DAG.getUNDEF(VT);
6840 SDValue Op0 = Op.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006841 unsigned i = 0;
Adam Nemetc5779462017-04-13 23:32:47 +00006842
6843 // Use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00006844 // a) Avoid a RMW dependency on the full vector register, and
6845 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00006846 // value is already in an S or D register, and we're forced to emit an
6847 // INSERT_SUBREG that we can't fold anywhere.
Adam Nemetc5779462017-04-13 23:32:47 +00006848 //
6849 // We also allow types like i8 and i16 which are illegal scalar but legal
6850 // vector element types. After type-legalization the inserted value is
6851 // extended (i32) and it is safe to cast them to the vector type by ignoring
6852 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6853 if (!Op0.isUndef()) {
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006854 DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00006855 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006856 ++i;
6857 }
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006858 DEBUG(
6859 if (i < NumElts)
6860 dbgs() << "Creating nodes for the other vector elements:\n";
6861 );
Tim Northover3b0846e2014-05-24 12:50:23 +00006862 for (; i < NumElts; ++i) {
6863 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006864 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006865 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006866 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006867 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6868 }
6869 return Vec;
6870 }
6871
Sjoerd Meijerbafde8f2017-09-12 10:24:12 +00006872 DEBUG(dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
6873 "better alternative\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00006874 return SDValue();
6875}
6876
6877SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6878 SelectionDAG &DAG) const {
6879 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6880
Tim Northovere4b8e132014-07-15 10:00:26 +00006881 // Check for non-constant or out of range lane.
6882 EVT VT = Op.getOperand(0).getValueType();
6883 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6884 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006885 return SDValue();
6886
Tim Northover3b0846e2014-05-24 12:50:23 +00006887
6888 // Insertion/extraction are legal for V128 types.
6889 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006890 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6891 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006892 return Op;
6893
6894 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006895 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006896 return SDValue();
6897
6898 // For V64 types, we perform insertion by expanding the value
6899 // to a V128 type and perform the insertion on that.
6900 SDLoc DL(Op);
6901 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6902 EVT WideTy = WideVec.getValueType();
6903
6904 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6905 Op.getOperand(1), Op.getOperand(2));
6906 // Re-narrow the resultant vector.
6907 return NarrowVector(Node, DAG);
6908}
6909
6910SDValue
6911AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6912 SelectionDAG &DAG) const {
6913 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6914
Tim Northovere4b8e132014-07-15 10:00:26 +00006915 // Check for non-constant or out of range lane.
6916 EVT VT = Op.getOperand(0).getValueType();
6917 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6918 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006919 return SDValue();
6920
Tim Northover3b0846e2014-05-24 12:50:23 +00006921
6922 // Insertion/extraction are legal for V128 types.
6923 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006924 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6925 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006926 return Op;
6927
6928 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006929 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006930 return SDValue();
6931
6932 // For V64 types, we perform extraction by expanding the value
6933 // to a V128 type and perform the extraction on that.
6934 SDLoc DL(Op);
6935 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6936 EVT WideTy = WideVec.getValueType();
6937
6938 EVT ExtrTy = WideTy.getVectorElementType();
6939 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6940 ExtrTy = MVT::i32;
6941
6942 // For extractions, we just return the result directly.
6943 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6944 Op.getOperand(1));
6945}
6946
6947SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6948 SelectionDAG &DAG) const {
6949 EVT VT = Op.getOperand(0).getValueType();
6950 SDLoc dl(Op);
6951 // Just in case...
6952 if (!VT.isVector())
6953 return SDValue();
6954
6955 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6956 if (!Cst)
6957 return SDValue();
6958 unsigned Val = Cst->getZExtValue();
6959
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006960 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006961
6962 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6963 if (Val == 0)
6964 return Op;
6965
Tim Northover3b0846e2014-05-24 12:50:23 +00006966 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6967 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006968 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006969 return Op;
6970
6971 return SDValue();
6972}
6973
Zvi Rackover1b736822017-07-26 08:06:58 +00006974bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00006975 if (VT.getVectorNumElements() == 4 &&
6976 (VT.is128BitVector() || VT.is64BitVector())) {
6977 unsigned PFIndexes[4];
6978 for (unsigned i = 0; i != 4; ++i) {
6979 if (M[i] < 0)
6980 PFIndexes[i] = 8;
6981 else
6982 PFIndexes[i] = M[i];
6983 }
6984
6985 // Compute the index in the perfect shuffle table.
6986 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6987 PFIndexes[2] * 9 + PFIndexes[3];
6988 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6989 unsigned Cost = (PFEntry >> 30);
6990
6991 if (Cost <= 4)
6992 return true;
6993 }
6994
6995 bool DummyBool;
6996 int DummyInt;
6997 unsigned DummyUnsigned;
6998
6999 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7000 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7001 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7002 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7003 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7004 isZIPMask(M, VT, DummyUnsigned) ||
7005 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7006 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7007 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7008 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7009 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7010}
7011
7012/// getVShiftImm - Check if this is a valid build_vector for the immediate
7013/// operand of a vector shift operation, where all the elements of the
7014/// build_vector must have the same constant integer value.
7015static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7016 // Ignore bit_converts.
7017 while (Op.getOpcode() == ISD::BITCAST)
7018 Op = Op.getOperand(0);
7019 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7020 APInt SplatBits, SplatUndef;
7021 unsigned SplatBitSize;
7022 bool HasAnyUndefs;
7023 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7024 HasAnyUndefs, ElementBits) ||
7025 SplatBitSize > ElementBits)
7026 return false;
7027 Cnt = SplatBits.getSExtValue();
7028 return true;
7029}
7030
7031/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7032/// operand of a vector shift left operation. That value must be in the range:
7033/// 0 <= Value < ElementBits for a left shift; or
7034/// 0 <= Value <= ElementBits for a long left shift.
7035static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7036 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007037 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007038 if (!getVShiftImm(Op, ElementBits, Cnt))
7039 return false;
7040 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7041}
7042
7043/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007044/// operand of a vector shift right operation. The value must be in the range:
7045/// 1 <= Value <= ElementBits for a right shift; or
7046static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007047 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007048 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007049 if (!getVShiftImm(Op, ElementBits, Cnt))
7050 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00007051 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7052}
7053
7054SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7055 SelectionDAG &DAG) const {
7056 EVT VT = Op.getValueType();
7057 SDLoc DL(Op);
7058 int64_t Cnt;
7059
7060 if (!Op.getOperand(1).getValueType().isVector())
7061 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007062 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007063
7064 switch (Op.getOpcode()) {
7065 default:
7066 llvm_unreachable("unexpected shift opcode");
7067
7068 case ISD::SHL:
7069 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007070 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7071 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007072 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007073 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7074 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007075 Op.getOperand(0), Op.getOperand(1));
7076 case ISD::SRA:
7077 case ISD::SRL:
7078 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00007079 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007080 unsigned Opc =
7081 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007082 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7083 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00007084 }
7085
7086 // Right shift register. Note, there is not a shift right register
7087 // instruction, but the shift left register instruction takes a signed
7088 // value, where negative numbers specify a right shift.
7089 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7090 : Intrinsic::aarch64_neon_ushl;
7091 // negate the shift amount
7092 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7093 SDValue NegShiftLeft =
7094 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007095 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7096 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00007097 return NegShiftLeft;
7098 }
7099
7100 return SDValue();
7101}
7102
7103static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7104 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00007105 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007106 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00007107 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7108 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00007109
7110 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7111 APInt CnstBits(VT.getSizeInBits(), 0);
7112 APInt UndefBits(VT.getSizeInBits(), 0);
7113 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7114 bool IsZero = IsCnst && (CnstBits == 0);
7115
7116 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7117 switch (CC) {
7118 default:
7119 return SDValue();
7120 case AArch64CC::NE: {
7121 SDValue Fcmeq;
7122 if (IsZero)
7123 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7124 else
7125 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7126 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7127 }
7128 case AArch64CC::EQ:
7129 if (IsZero)
7130 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7131 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7132 case AArch64CC::GE:
7133 if (IsZero)
7134 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7135 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7136 case AArch64CC::GT:
7137 if (IsZero)
7138 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7139 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7140 case AArch64CC::LS:
7141 if (IsZero)
7142 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7143 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7144 case AArch64CC::LT:
7145 if (!NoNans)
7146 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00007147 // If we ignore NaNs then we can use to the MI implementation.
7148 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00007149 case AArch64CC::MI:
7150 if (IsZero)
7151 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7152 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7153 }
7154 }
7155
7156 switch (CC) {
7157 default:
7158 return SDValue();
7159 case AArch64CC::NE: {
7160 SDValue Cmeq;
7161 if (IsZero)
7162 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7163 else
7164 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7165 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7166 }
7167 case AArch64CC::EQ:
7168 if (IsZero)
7169 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7170 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7171 case AArch64CC::GE:
7172 if (IsZero)
7173 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7174 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7175 case AArch64CC::GT:
7176 if (IsZero)
7177 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7178 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7179 case AArch64CC::LE:
7180 if (IsZero)
7181 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7182 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7183 case AArch64CC::LS:
7184 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7185 case AArch64CC::LO:
7186 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7187 case AArch64CC::LT:
7188 if (IsZero)
7189 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7190 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7191 case AArch64CC::HI:
7192 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7193 case AArch64CC::HS:
7194 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7195 }
7196}
7197
7198SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7199 SelectionDAG &DAG) const {
7200 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7201 SDValue LHS = Op.getOperand(0);
7202 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00007203 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00007204 SDLoc dl(Op);
7205
7206 if (LHS.getValueType().getVectorElementType().isInteger()) {
7207 assert(LHS.getValueType() == RHS.getValueType());
7208 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00007209 SDValue Cmp =
7210 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7211 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007212 }
7213
Carey Williamsda15b5b2018-01-22 14:16:11 +00007214 const bool FullFP16 =
7215 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7216
7217 // Make v4f16 (only) fcmp operations utilise vector instructions
7218 // v8f16 support will be a litle more complicated
7219 if (LHS.getValueType().getVectorElementType() == MVT::f16) {
7220 if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
7221 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7222 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7223 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7224 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7225 CmpVT = MVT::v4i32;
7226 } else
7227 return SDValue();
7228 }
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00007229
Tim Northover3b0846e2014-05-24 12:50:23 +00007230 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7231 LHS.getValueType().getVectorElementType() == MVT::f64);
7232
7233 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7234 // clean. Some of them require two branches to implement.
7235 AArch64CC::CondCode CC1, CC2;
7236 bool ShouldInvert;
7237 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7238
7239 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7240 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00007241 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007242 if (!Cmp.getNode())
7243 return SDValue();
7244
7245 if (CC2 != AArch64CC::AL) {
7246 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00007247 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00007248 if (!Cmp2.getNode())
7249 return SDValue();
7250
Tim Northover45aa89c2015-02-08 00:50:47 +00007251 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007252 }
7253
Tim Northover45aa89c2015-02-08 00:50:47 +00007254 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7255
Tim Northover3b0846e2014-05-24 12:50:23 +00007256 if (ShouldInvert)
7257 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7258
7259 return Cmp;
7260}
7261
Amara Emersonc9916d72017-05-16 21:29:22 +00007262static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7263 SelectionDAG &DAG) {
7264 SDValue VecOp = ScalarOp.getOperand(0);
7265 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7266 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7267 DAG.getConstant(0, DL, MVT::i64));
7268}
7269
7270SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7271 SelectionDAG &DAG) const {
7272 SDLoc dl(Op);
7273 switch (Op.getOpcode()) {
7274 case ISD::VECREDUCE_ADD:
7275 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7276 case ISD::VECREDUCE_SMAX:
7277 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7278 case ISD::VECREDUCE_SMIN:
7279 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7280 case ISD::VECREDUCE_UMAX:
7281 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7282 case ISD::VECREDUCE_UMIN:
7283 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7284 case ISD::VECREDUCE_FMAX: {
7285 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7286 return DAG.getNode(
7287 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7288 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7289 Op.getOperand(0));
7290 }
7291 case ISD::VECREDUCE_FMIN: {
7292 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7293 return DAG.getNode(
7294 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7295 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7296 Op.getOperand(0));
7297 }
7298 default:
7299 llvm_unreachable("Unhandled reduction");
7300 }
7301}
7302
Oliver Stannard42699172018-02-12 14:22:03 +00007303SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7304 SelectionDAG &DAG) const {
7305 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7306 if (!Subtarget.hasLSE())
7307 return SDValue();
7308
7309 // LSE has an atomic load-add instruction, but not a load-sub.
7310 SDLoc dl(Op);
7311 MVT VT = Op.getSimpleValueType();
7312 SDValue RHS = Op.getOperand(2);
7313 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7314 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7315 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7316 Op.getOperand(0), Op.getOperand(1), RHS,
7317 AN->getMemOperand());
7318}
7319
Oliver Stannard02f08c92018-02-12 17:03:11 +00007320SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7321 SelectionDAG &DAG) const {
7322 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7323 if (!Subtarget.hasLSE())
7324 return SDValue();
7325
7326 // LSE has an atomic load-clear instruction, but not a load-and.
7327 SDLoc dl(Op);
7328 MVT VT = Op.getSimpleValueType();
7329 SDValue RHS = Op.getOperand(2);
7330 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7331 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7332 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7333 Op.getOperand(0), Op.getOperand(1), RHS,
7334 AN->getMemOperand());
7335}
7336
Martin Storsjoa63a5b92018-02-17 14:26:32 +00007337SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7338 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7339 SDLoc dl(Op);
7340 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7341 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
7342
7343 const uint32_t *Mask =
7344 Subtarget->getRegisterInfo()->getWindowsStackProbePreservedMask();
7345
7346 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7347 DAG.getConstant(4, dl, MVT::i64));
7348 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7349 Chain =
7350 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7351 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7352 DAG.getRegisterMask(Mask), Chain.getValue(1));
7353 // To match the actual intent better, we should read the output from X15 here
7354 // again (instead of potentially spilling it to the stack), but rereading Size
7355 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7356 // here.
7357
7358 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7359 DAG.getConstant(4, dl, MVT::i64));
7360 return Chain;
7361}
7362
7363SDValue
7364AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7365 SelectionDAG &DAG) const {
7366 assert(Subtarget->isTargetWindows() &&
7367 "Only Windows alloca probing supported");
7368 SDLoc dl(Op);
7369 // Get the inputs.
7370 SDNode *Node = Op.getNode();
7371 SDValue Chain = Op.getOperand(0);
7372 SDValue Size = Op.getOperand(1);
7373 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7374 EVT VT = Node->getValueType(0);
7375
7376 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
7377
7378 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
7379
7380 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
7381 Chain = SP.getValue(1);
7382 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
7383 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7384
7385 if (Align) {
7386 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
7387 DAG.getConstant(-(uint64_t)Align, dl, VT));
7388 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
7389 }
7390
7391 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
7392 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
7393
7394 SDValue Ops[2] = {SP, Chain};
7395 return DAG.getMergeValues(Ops, dl);
7396}
7397
Tim Northover3b0846e2014-05-24 12:50:23 +00007398/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7399/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7400/// specified in the intrinsic calls.
7401bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7402 const CallInst &I,
Matt Arsenault7d7adf42017-12-14 22:34:10 +00007403 MachineFunction &MF,
Tim Northover3b0846e2014-05-24 12:50:23 +00007404 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007405 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00007406 switch (Intrinsic) {
7407 case Intrinsic::aarch64_neon_ld2:
7408 case Intrinsic::aarch64_neon_ld3:
7409 case Intrinsic::aarch64_neon_ld4:
7410 case Intrinsic::aarch64_neon_ld1x2:
7411 case Intrinsic::aarch64_neon_ld1x3:
7412 case Intrinsic::aarch64_neon_ld1x4:
7413 case Intrinsic::aarch64_neon_ld2lane:
7414 case Intrinsic::aarch64_neon_ld3lane:
7415 case Intrinsic::aarch64_neon_ld4lane:
7416 case Intrinsic::aarch64_neon_ld2r:
7417 case Intrinsic::aarch64_neon_ld3r:
7418 case Intrinsic::aarch64_neon_ld4r: {
7419 Info.opc = ISD::INTRINSIC_W_CHAIN;
7420 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007421 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007422 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7423 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7424 Info.offset = 0;
7425 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00007426 // volatile loads with NEON intrinsics not supported
7427 Info.flags = MachineMemOperand::MOLoad;
Tim Northover3b0846e2014-05-24 12:50:23 +00007428 return true;
7429 }
7430 case Intrinsic::aarch64_neon_st2:
7431 case Intrinsic::aarch64_neon_st3:
7432 case Intrinsic::aarch64_neon_st4:
7433 case Intrinsic::aarch64_neon_st1x2:
7434 case Intrinsic::aarch64_neon_st1x3:
7435 case Intrinsic::aarch64_neon_st1x4:
7436 case Intrinsic::aarch64_neon_st2lane:
7437 case Intrinsic::aarch64_neon_st3lane:
7438 case Intrinsic::aarch64_neon_st4lane: {
7439 Info.opc = ISD::INTRINSIC_VOID;
7440 // Conservatively set memVT to the entire set of vectors stored.
7441 unsigned NumElts = 0;
7442 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7443 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7444 if (!ArgTy->isVectorTy())
7445 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007446 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007447 }
7448 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7449 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7450 Info.offset = 0;
7451 Info.align = 0;
Matt Arsenault11171332017-12-14 21:39:51 +00007452 // volatile stores with NEON intrinsics not supported
7453 Info.flags = MachineMemOperand::MOStore;
Tim Northover3b0846e2014-05-24 12:50:23 +00007454 return true;
7455 }
7456 case Intrinsic::aarch64_ldaxr:
7457 case Intrinsic::aarch64_ldxr: {
7458 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7459 Info.opc = ISD::INTRINSIC_W_CHAIN;
7460 Info.memVT = MVT::getVT(PtrTy->getElementType());
7461 Info.ptrVal = I.getArgOperand(0);
7462 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007463 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00007464 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007465 return true;
7466 }
7467 case Intrinsic::aarch64_stlxr:
7468 case Intrinsic::aarch64_stxr: {
7469 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7470 Info.opc = ISD::INTRINSIC_W_CHAIN;
7471 Info.memVT = MVT::getVT(PtrTy->getElementType());
7472 Info.ptrVal = I.getArgOperand(1);
7473 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007474 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Matt Arsenault11171332017-12-14 21:39:51 +00007475 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007476 return true;
7477 }
7478 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007479 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007480 Info.opc = ISD::INTRINSIC_W_CHAIN;
7481 Info.memVT = MVT::i128;
7482 Info.ptrVal = I.getArgOperand(0);
7483 Info.offset = 0;
7484 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00007485 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007486 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007487 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007488 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007489 Info.opc = ISD::INTRINSIC_W_CHAIN;
7490 Info.memVT = MVT::i128;
7491 Info.ptrVal = I.getArgOperand(2);
7492 Info.offset = 0;
7493 Info.align = 16;
Matt Arsenault11171332017-12-14 21:39:51 +00007494 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
Tim Northover3b0846e2014-05-24 12:50:23 +00007495 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007496 default:
7497 break;
7498 }
7499
7500 return false;
7501}
7502
7503// Truncations from 64-bit GPR to 32-bit GPR is free.
7504bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7505 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7506 return false;
7507 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7508 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007509 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007510}
7511bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007512 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007513 return false;
7514 unsigned NumBits1 = VT1.getSizeInBits();
7515 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007516 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007517}
7518
Chad Rosier54390052015-02-23 19:15:16 +00007519/// Check if it is profitable to hoist instruction in then/else to if.
7520/// Not profitable if I and it's user can form a FMA instruction
7521/// because we prefer FMSUB/FMADD.
7522bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7523 if (I->getOpcode() != Instruction::FMul)
7524 return true;
7525
Davide Italiano3e9986f2017-04-18 00:29:54 +00007526 if (!I->hasOneUse())
Chad Rosier54390052015-02-23 19:15:16 +00007527 return true;
7528
7529 Instruction *User = I->user_back();
7530
7531 if (User &&
7532 !(User->getOpcode() == Instruction::FSub ||
7533 User->getOpcode() == Instruction::FAdd))
7534 return true;
7535
7536 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007537 const DataLayout &DL = I->getModule()->getDataLayout();
7538 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007539
Eric Christopher114fa1c2016-02-29 22:50:49 +00007540 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7541 isOperationLegalOrCustom(ISD::FMA, VT) &&
7542 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7543 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007544}
7545
Tim Northover3b0846e2014-05-24 12:50:23 +00007546// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7547// 64-bit GPR.
7548bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7549 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7550 return false;
7551 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7552 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007553 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007554}
7555bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007556 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007557 return false;
7558 unsigned NumBits1 = VT1.getSizeInBits();
7559 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007560 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007561}
7562
7563bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7564 EVT VT1 = Val.getValueType();
7565 if (isZExtFree(VT1, VT2)) {
7566 return true;
7567 }
7568
7569 if (Val.getOpcode() != ISD::LOAD)
7570 return false;
7571
7572 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007573 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7574 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7575 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007576}
7577
Quentin Colombet6843ac42015-03-31 20:52:32 +00007578bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7579 if (isa<FPExtInst>(Ext))
7580 return false;
7581
Haicheng Wu50692a22017-08-01 21:26:45 +00007582 // Vector types are not free.
Quentin Colombet6843ac42015-03-31 20:52:32 +00007583 if (Ext->getType()->isVectorTy())
7584 return false;
7585
7586 for (const Use &U : Ext->uses()) {
7587 // The extension is free if we can fold it with a left shift in an
7588 // addressing mode or an arithmetic operation: add, sub, and cmp.
7589
7590 // Is there a shift?
7591 const Instruction *Instr = cast<Instruction>(U.getUser());
7592
7593 // Is this a constant shift?
7594 switch (Instr->getOpcode()) {
7595 case Instruction::Shl:
7596 if (!isa<ConstantInt>(Instr->getOperand(1)))
7597 return false;
7598 break;
7599 case Instruction::GetElementPtr: {
7600 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007601 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00007602 std::advance(GTI, U.getOperandNo()-1);
7603 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007604 // This extension will end up with a shift because of the scaling factor.
7605 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7606 // Get the shift amount based on the scaling factor:
7607 // log2(sizeof(IdxTy)) - log2(8).
7608 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007609 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007610 // Is the constant foldable in the shift of the addressing mode?
7611 // I.e., shift amount is between 1 and 4 inclusive.
7612 if (ShiftAmt == 0 || ShiftAmt > 4)
7613 return false;
7614 break;
7615 }
7616 case Instruction::Trunc:
7617 // Check if this is a noop.
7618 // trunc(sext ty1 to ty2) to ty1.
7619 if (Instr->getType() == Ext->getOperand(0)->getType())
7620 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00007621 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007622 default:
7623 return false;
7624 }
7625
7626 // At this point we can use the bfm family, so this extension is free
7627 // for that use.
7628 }
7629 return true;
7630}
7631
Tim Northover3b0846e2014-05-24 12:50:23 +00007632bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7633 unsigned &RequiredAligment) const {
7634 if (!LoadedType.isSimple() ||
7635 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7636 return false;
7637 // Cyclone supports unaligned accesses.
7638 RequiredAligment = 0;
7639 unsigned NumBits = LoadedType.getSizeInBits();
7640 return NumBits == 32 || NumBits == 64;
7641}
7642
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007643/// A helper function for determining the number of interleaved accesses we
7644/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007645unsigned
7646AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7647 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007648 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7649}
7650
Geoff Berryb1e87142017-07-14 21:44:12 +00007651MachineMemOperand::Flags
7652AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
7653 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
7654 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
7655 return MOStridedAccess;
7656 return MachineMemOperand::MONone;
7657}
7658
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007659bool AArch64TargetLowering::isLegalInterleavedAccessType(
7660 VectorType *VecTy, const DataLayout &DL) const {
7661
7662 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7663 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7664
7665 // Ensure the number of vector elements is greater than 1.
7666 if (VecTy->getNumElements() < 2)
7667 return false;
7668
7669 // Ensure the element type is legal.
7670 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7671 return false;
7672
7673 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7674 // 128 will be split into multiple interleaved accesses.
7675 return VecSize == 64 || VecSize % 128 == 0;
7676}
7677
Hao Liu7ec8ee32015-06-26 02:32:07 +00007678/// \brief Lower an interleaved load into a ldN intrinsic.
7679///
7680/// E.g. Lower an interleaved load (Factor = 2):
7681/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7682/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7683/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7684///
7685/// Into:
7686/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7687/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7688/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7689bool AArch64TargetLowering::lowerInterleavedLoad(
7690 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7691 ArrayRef<unsigned> Indices, unsigned Factor) const {
7692 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7693 "Invalid interleave factor");
7694 assert(!Shuffles.empty() && "Empty shufflevector input");
7695 assert(Shuffles.size() == Indices.size() &&
7696 "Unmatched number of shufflevectors and indices");
7697
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007698 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007699
7700 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007701
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007702 // Skip if we do not have NEON and skip illegal vector types. We can
7703 // "legalize" wide vector types into multiple interleaved accesses as long as
7704 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007705 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007706 return false;
7707
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007708 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7709
Hao Liu7ec8ee32015-06-26 02:32:07 +00007710 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7711 // load integer vectors first and then convert to pointer vectors.
7712 Type *EltTy = VecTy->getVectorElementType();
7713 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007714 VecTy =
7715 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007716
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007717 IRBuilder<> Builder(LI);
7718
7719 // The base address of the load.
7720 Value *BaseAddr = LI->getPointerOperand();
7721
7722 if (NumLoads > 1) {
7723 // If we're going to generate more than one load, reset the sub-vector type
7724 // to something legal.
7725 VecTy = VectorType::get(VecTy->getVectorElementType(),
7726 VecTy->getVectorNumElements() / NumLoads);
7727
7728 // We will compute the pointer operand of each load from the original base
7729 // address using GEPs. Cast the base address to a pointer to the scalar
7730 // element type.
7731 BaseAddr = Builder.CreateBitCast(
7732 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7733 LI->getPointerAddressSpace()));
7734 }
7735
Hao Liu7ec8ee32015-06-26 02:32:07 +00007736 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7737 Type *Tys[2] = {VecTy, PtrTy};
7738 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7739 Intrinsic::aarch64_neon_ld3,
7740 Intrinsic::aarch64_neon_ld4};
7741 Function *LdNFunc =
7742 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7743
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007744 // Holds sub-vectors extracted from the load intrinsic return values. The
7745 // sub-vectors are associated with the shufflevector instructions they will
7746 // replace.
7747 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00007748
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007749 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00007750
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007751 // If we're generating more than one load, compute the base address of
7752 // subsequent loads as an offset from the previous.
7753 if (LoadCount > 0)
7754 BaseAddr = Builder.CreateConstGEP1_32(
7755 BaseAddr, VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007756
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007757 CallInst *LdN = Builder.CreateCall(
7758 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00007759
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007760 // Extract and store the sub-vectors returned by the load intrinsic.
7761 for (unsigned i = 0; i < Shuffles.size(); i++) {
7762 ShuffleVectorInst *SVI = Shuffles[i];
7763 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00007764
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007765 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7766
7767 // Convert the integer vector to pointer vector if the element is pointer.
7768 if (EltTy->isPointerTy())
Dehao Chen38f1bc72017-06-26 21:33:51 +00007769 SubVec = Builder.CreateIntToPtr(
7770 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
7771 VecTy->getVectorNumElements()));
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007772 SubVecs[SVI].push_back(SubVec);
7773 }
7774 }
7775
7776 // Replace uses of the shufflevector instructions with the sub-vectors
7777 // returned by the load intrinsic. If a shufflevector instruction is
7778 // associated with more than one sub-vector, those sub-vectors will be
7779 // concatenated into a single wide vector.
7780 for (ShuffleVectorInst *SVI : Shuffles) {
7781 auto &SubVec = SubVecs[SVI];
7782 auto *WideVec =
7783 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7784 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007785 }
7786
7787 return true;
7788}
7789
Hao Liu7ec8ee32015-06-26 02:32:07 +00007790/// \brief Lower an interleaved store into a stN intrinsic.
7791///
7792/// E.g. Lower an interleaved store (Factor = 3):
7793/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007794/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00007795/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7796///
7797/// Into:
7798/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7799/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7800/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7801/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7802///
7803/// Note that the new shufflevectors will be removed and we'll only generate one
7804/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007805///
7806/// Example for a more general valid mask (Factor 3). Lower:
7807/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7808/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7809/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7810///
7811/// Into:
7812/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7813/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7814/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7815/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00007816bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7817 ShuffleVectorInst *SVI,
7818 unsigned Factor) const {
7819 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7820 "Invalid interleave factor");
7821
7822 VectorType *VecTy = SVI->getType();
7823 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7824 "Invalid interleaved store");
7825
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007826 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00007827 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007828 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007829
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007830 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007831
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007832 // Skip if we do not have NEON and skip illegal vector types. We can
7833 // "legalize" wide vector types into multiple interleaved accesses as long as
7834 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007835 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007836 return false;
7837
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007838 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7839
Hao Liu7ec8ee32015-06-26 02:32:07 +00007840 Value *Op0 = SVI->getOperand(0);
7841 Value *Op1 = SVI->getOperand(1);
7842 IRBuilder<> Builder(SI);
7843
7844 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7845 // vectors to integer vectors.
7846 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007847 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007848 unsigned NumOpElts =
7849 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7850
7851 // Convert to the corresponding integer vector.
7852 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7853 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7854 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7855
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007856 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007857 }
7858
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007859 // The base address of the store.
7860 Value *BaseAddr = SI->getPointerOperand();
7861
7862 if (NumStores > 1) {
7863 // If we're going to generate more than one store, reset the lane length
7864 // and sub-vector type to something legal.
7865 LaneLen /= NumStores;
7866 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7867
7868 // We will compute the pointer operand of each store from the original base
7869 // address using GEPs. Cast the base address to a pointer to the scalar
7870 // element type.
7871 BaseAddr = Builder.CreateBitCast(
7872 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7873 SI->getPointerAddressSpace()));
7874 }
7875
7876 auto Mask = SVI->getShuffleMask();
7877
Hao Liu7ec8ee32015-06-26 02:32:07 +00007878 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7879 Type *Tys[2] = {SubVecTy, PtrTy};
7880 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7881 Intrinsic::aarch64_neon_st3,
7882 Intrinsic::aarch64_neon_st4};
7883 Function *StNFunc =
7884 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7885
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007886 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00007887
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007888 SmallVector<Value *, 5> Ops;
7889
7890 // Split the shufflevector operands into sub vectors for the new stN call.
7891 for (unsigned i = 0; i < Factor; i++) {
7892 unsigned IdxI = StoreCount * LaneLen * Factor + i;
7893 if (Mask[IdxI] >= 0) {
7894 Ops.push_back(Builder.CreateShuffleVector(
7895 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7896 } else {
7897 unsigned StartMask = 0;
7898 for (unsigned j = 1; j < LaneLen; j++) {
7899 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7900 if (Mask[IdxJ * Factor + IdxI] >= 0) {
7901 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7902 break;
7903 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007904 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007905 // Note: Filling undef gaps with random elements is ok, since
7906 // those elements were being written anyway (with undefs).
7907 // In the case of all undefs we're defaulting to using elems from 0
7908 // Note: StartMask cannot be negative, it's checked in
7909 // isReInterleaveMask
7910 Ops.push_back(Builder.CreateShuffleVector(
7911 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007912 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007913 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00007914
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007915 // If we generating more than one store, we compute the base address of
7916 // subsequent stores as an offset from the previous.
7917 if (StoreCount > 0)
7918 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7919
7920 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7921 Builder.CreateCall(StNFunc, Ops);
7922 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00007923 return true;
7924}
7925
Tim Northover3b0846e2014-05-24 12:50:23 +00007926static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7927 unsigned AlignCheck) {
7928 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7929 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7930}
7931
7932EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7933 unsigned SrcAlign, bool IsMemset,
7934 bool ZeroMemset,
7935 bool MemcpyStrSrc,
7936 MachineFunction &MF) const {
7937 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7938 // instruction to materialize the v2i64 zero and one store (with restrictive
7939 // addressing mode). Just do two i64 store of zero-registers.
7940 bool Fast;
Matthias Braunf1caa282017-12-15 22:22:58 +00007941 const Function &F = MF.getFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00007942 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Matthias Braunf1caa282017-12-15 22:22:58 +00007943 !F.hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007944 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007945 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007946 return MVT::f128;
7947
Lang Hames90333852015-04-09 03:40:33 +00007948 if (Size >= 8 &&
7949 (memOpAlign(SrcAlign, DstAlign, 8) ||
7950 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7951 return MVT::i64;
7952
7953 if (Size >= 4 &&
7954 (memOpAlign(SrcAlign, DstAlign, 4) ||
7955 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007956 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007957
7958 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007959}
7960
7961// 12-bit optionally shifted immediates are legal for adds.
7962bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Sjoerd Meijer24c98182017-08-23 08:18:37 +00007963 if (Immed == std::numeric_limits<int64_t>::min()) {
7964 DEBUG(dbgs() << "Illegal add imm " << Immed << ": avoid UB for INT64_MIN\n");
Geoff Berry486f49c2016-06-07 16:48:43 +00007965 return false;
Sjoerd Meijer24c98182017-08-23 08:18:37 +00007966 }
Geoff Berry486f49c2016-06-07 16:48:43 +00007967 // Same encoding for add/sub, just flip the sign.
7968 Immed = std::abs(Immed);
Sjoerd Meijer24c98182017-08-23 08:18:37 +00007969 bool IsLegal = ((Immed >> 12) == 0 ||
7970 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7971 DEBUG(dbgs() << "Is " << Immed << " legal add imm: " <<
7972 (IsLegal ? "yes" : "no") << "\n");
7973 return IsLegal;
Tim Northover3b0846e2014-05-24 12:50:23 +00007974}
7975
7976// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7977// immediates is the same as for an add or a sub.
7978bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007979 return isLegalAddImmediate(Immed);
7980}
7981
7982/// isLegalAddressingMode - Return true if the addressing mode represented
7983/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007984bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7985 const AddrMode &AM, Type *Ty,
Jonas Paulsson024e3192017-07-21 11:59:37 +00007986 unsigned AS, Instruction *I) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007987 // AArch64 has five basic addressing modes:
7988 // reg
7989 // reg + 9-bit signed offset
7990 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7991 // reg1 + reg2
7992 // reg + SIZE_IN_BYTES * reg
7993
7994 // No global is ever allowed as a base.
7995 if (AM.BaseGV)
7996 return false;
7997
7998 // No reg+reg+imm addressing.
7999 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8000 return false;
8001
8002 // check reg + imm case:
8003 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8004 uint64_t NumBytes = 0;
8005 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008006 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00008007 NumBytes = NumBits / 8;
8008 if (!isPowerOf2_64(NumBits))
8009 NumBytes = 0;
8010 }
8011
8012 if (!AM.Scale) {
8013 int64_t Offset = AM.BaseOffs;
8014
8015 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00008016 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00008017 return true;
8018
8019 // 12-bit unsigned offset
8020 unsigned shift = Log2_64(NumBytes);
8021 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8022 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8023 (Offset >> shift) << shift == Offset)
8024 return true;
8025 return false;
8026 }
8027
8028 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8029
Haicheng Wu6bb0e392016-12-21 21:40:47 +00008030 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00008031}
8032
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008033int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8034 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00008035 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00008036 // Scaling factors are not free at all.
8037 // Operands | Rt Latency
8038 // -------------------------------------------
8039 // Rt, [Xn, Xm] | 4
8040 // -------------------------------------------
8041 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8042 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00008043 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00008044 // Scale represents reg2 * scale, thus account for 1 if
8045 // it is not equal to 0 or 1.
8046 return AM.Scale != 0 && AM.Scale != 1;
8047 return -1;
8048}
8049
8050bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8051 VT = VT.getScalarType();
8052
8053 if (!VT.isSimple())
8054 return false;
8055
8056 switch (VT.getSimpleVT().SimpleTy) {
8057 case MVT::f32:
8058 case MVT::f64:
8059 return true;
8060 default:
8061 break;
8062 }
8063
8064 return false;
8065}
8066
8067const MCPhysReg *
8068AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8069 // LR is a callee-save register, but we must treat it as clobbered by any call
8070 // site. Hence we include LR in the scratch registers, which are in turn added
8071 // as implicit-defs for stackmaps and patchpoints.
8072 static const MCPhysReg ScratchRegs[] = {
8073 AArch64::X16, AArch64::X17, AArch64::LR, 0
8074 };
8075 return ScratchRegs;
8076}
8077
8078bool
8079AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
8080 EVT VT = N->getValueType(0);
8081 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8082 // it with shift to let it be lowered to UBFX.
8083 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8084 isa<ConstantSDNode>(N->getOperand(1))) {
8085 uint64_t TruncMask = N->getConstantOperandVal(1);
8086 if (isMask_64(TruncMask) &&
8087 N->getOperand(0).getOpcode() == ISD::SRL &&
8088 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8089 return false;
8090 }
8091 return true;
8092}
8093
8094bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8095 Type *Ty) const {
8096 assert(Ty->isIntegerTy());
8097
8098 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8099 if (BitSize == 0)
8100 return false;
8101
8102 int64_t Val = Imm.getSExtValue();
8103 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8104 return true;
8105
8106 if ((int64_t)Val < 0)
8107 Val = ~Val;
8108 if (BitSize == 32)
8109 Val &= (1LL << 32) - 1;
8110
8111 unsigned LZ = countLeadingZeros((uint64_t)Val);
8112 unsigned Shift = (63 - LZ) / 16;
8113 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00008114 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00008115}
8116
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008117/// Turn vector tests of the signbit in the form of:
8118/// xor (sra X, elt_size(X)-1), -1
8119/// into:
8120/// cmge X, X, #0
8121static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8122 const AArch64Subtarget *Subtarget) {
8123 EVT VT = N->getValueType(0);
8124 if (!Subtarget->hasNEON() || !VT.isVector())
8125 return SDValue();
8126
8127 // There must be a shift right algebraic before the xor, and the xor must be a
8128 // 'not' operation.
8129 SDValue Shift = N->getOperand(0);
8130 SDValue Ones = N->getOperand(1);
8131 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8132 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8133 return SDValue();
8134
8135 // The shift should be smearing the sign bit across each vector element.
8136 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8137 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8138 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8139 return SDValue();
8140
8141 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8142}
8143
Tim Northover3b0846e2014-05-24 12:50:23 +00008144// Generate SUBS and CSEL for integer abs.
8145static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8146 EVT VT = N->getValueType(0);
8147
8148 SDValue N0 = N->getOperand(0);
8149 SDValue N1 = N->getOperand(1);
8150 SDLoc DL(N);
8151
8152 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8153 // and change it to SUB and CSEL.
8154 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8155 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8156 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8157 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8158 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008159 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00008160 N0.getOperand(0));
8161 // Generate SUBS & CSEL.
8162 SDValue Cmp =
8163 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008164 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008165 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008166 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00008167 SDValue(Cmp.getNode(), 1));
8168 }
8169 return SDValue();
8170}
8171
Tim Northover3b0846e2014-05-24 12:50:23 +00008172static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8173 TargetLowering::DAGCombinerInfo &DCI,
8174 const AArch64Subtarget *Subtarget) {
8175 if (DCI.isBeforeLegalizeOps())
8176 return SDValue();
8177
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00008178 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8179 return Cmp;
8180
Tim Northover3b0846e2014-05-24 12:50:23 +00008181 return performIntegerAbsCombine(N, DAG);
8182}
8183
Chad Rosier17020f92014-07-23 14:57:52 +00008184SDValue
8185AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8186 SelectionDAG &DAG,
8187 std::vector<SDNode *> *Created) const {
Matthias Braunf1caa282017-12-15 22:22:58 +00008188 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00008189 if (isIntDivCheap(N->getValueType(0), Attr))
8190 return SDValue(N,0); // Lower SDIV as SDIV
8191
Chad Rosier17020f92014-07-23 14:57:52 +00008192 // fold (sdiv X, pow2)
8193 EVT VT = N->getValueType(0);
8194 if ((VT != MVT::i32 && VT != MVT::i64) ||
8195 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8196 return SDValue();
8197
8198 SDLoc DL(N);
8199 SDValue N0 = N->getOperand(0);
8200 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008201 SDValue Zero = DAG.getConstant(0, DL, VT);
8202 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00008203
8204 // Add (N0 < 0) ? Pow2 - 1 : 0;
8205 SDValue CCVal;
8206 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8207 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8208 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8209
8210 if (Created) {
8211 Created->push_back(Cmp.getNode());
8212 Created->push_back(Add.getNode());
8213 Created->push_back(CSel.getNode());
8214 }
8215
8216 // Divide by pow2.
8217 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008218 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00008219
8220 // If we're dividing by a positive value, we're done. Otherwise, we must
8221 // negate the result.
8222 if (Divisor.isNonNegative())
8223 return SRA;
8224
8225 if (Created)
8226 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008227 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00008228}
8229
Tim Northover3b0846e2014-05-24 12:50:23 +00008230static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8231 TargetLowering::DAGCombinerInfo &DCI,
8232 const AArch64Subtarget *Subtarget) {
8233 if (DCI.isBeforeLegalizeOps())
8234 return SDValue();
8235
Chad Rosier31ee8132016-11-11 17:07:37 +00008236 // The below optimizations require a constant RHS.
8237 if (!isa<ConstantSDNode>(N->getOperand(1)))
8238 return SDValue();
8239
8240 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8241 const APInt &ConstValue = C->getAPIntValue();
8242
Tim Northover3b0846e2014-05-24 12:50:23 +00008243 // Multiplication of a power of two plus/minus one can be done more
8244 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8245 // future CPUs have a cheaper MADD instruction, this may need to be
8246 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8247 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008248 // More aggressively, some multiplications N0 * C can be lowered to
8249 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8250 // e.g. 6=3*2=(2+1)*2.
8251 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8252 // which equals to (1+2)*16-(1+2).
8253 SDValue N0 = N->getOperand(0);
8254 // TrailingZeroes is used to test if the mul can be lowered to
8255 // shift+add+shift.
8256 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8257 if (TrailingZeroes) {
8258 // Conservatively do not lower to shift+add+shift if the mul might be
8259 // folded into smul or umul.
8260 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8261 isZeroExtended(N0.getNode(), DAG)))
8262 return SDValue();
8263 // Conservatively do not lower to shift+add+shift if the mul might be
8264 // folded into madd or msub.
8265 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8266 N->use_begin()->getOpcode() == ISD::SUB))
8267 return SDValue();
8268 }
8269 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8270 // and shift+add+shift.
8271 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8272
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008273 unsigned ShiftAmt, AddSubOpc;
8274 // Is the shifted value the LHS operand of the add/sub?
8275 bool ShiftValUseIsN0 = true;
8276 // Do we need to negate the result?
8277 bool NegateResult = false;
8278
Chad Rosier31ee8132016-11-11 17:07:37 +00008279 if (ConstValue.isNonNegative()) {
8280 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00008281 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00008282 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8283 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008284 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00008285 if (SCVMinus1.isPowerOf2()) {
8286 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008287 AddSubOpc = ISD::ADD;
8288 } else if (CVPlus1.isPowerOf2()) {
8289 ShiftAmt = CVPlus1.logBase2();
8290 AddSubOpc = ISD::SUB;
8291 } else
8292 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00008293 } else {
8294 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00008295 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008296 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00008297 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008298 if (CVNegPlus1.isPowerOf2()) {
8299 ShiftAmt = CVNegPlus1.logBase2();
8300 AddSubOpc = ISD::SUB;
8301 ShiftValUseIsN0 = false;
8302 } else if (CVNegMinus1.isPowerOf2()) {
8303 ShiftAmt = CVNegMinus1.logBase2();
8304 AddSubOpc = ISD::ADD;
8305 NegateResult = true;
8306 } else
8307 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008308 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008309
8310 SDLoc DL(N);
8311 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008312 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008313 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8314
8315 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8316 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8317 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00008318 assert(!(NegateResult && TrailingZeroes) &&
8319 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00008320 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00008321 if (NegateResult)
8322 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8323 // Shift the result.
8324 if (TrailingZeroes)
8325 return DAG.getNode(ISD::SHL, DL, VT, Res,
8326 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8327 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00008328}
8329
Jim Grosbachf7502c42014-07-18 00:40:52 +00008330static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8331 SelectionDAG &DAG) {
8332 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8333 // optimize away operation when it's from a constant.
8334 //
8335 // The general transformation is:
8336 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8337 // AND(VECTOR_CMP(x,y), constant2)
8338 // constant2 = UNARYOP(constant)
8339
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008340 // Early exit if this isn't a vector operation, the operand of the
8341 // unary operation isn't a bitwise AND, or if the sizes of the operations
8342 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00008343 EVT VT = N->getValueType(0);
8344 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00008345 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8346 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008347 return SDValue();
8348
Jim Grosbach724e4382014-07-23 20:41:43 +00008349 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00008350 // make the transformation for non-constant splats as well, but it's unclear
8351 // that would be a benefit as it would not eliminate any operations, just
8352 // perform one more step in scalar code before moving to the vector unit.
8353 if (BuildVectorSDNode *BV =
8354 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00008355 // Bail out if the vector isn't a constant.
8356 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00008357 return SDValue();
8358
8359 // Everything checks out. Build up the new and improved node.
8360 SDLoc DL(N);
8361 EVT IntVT = BV->getValueType(0);
8362 // Create a new constant of the appropriate type for the transformed
8363 // DAG.
8364 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8365 // The AND node needs bitcasts to/from an integer vector type around it.
8366 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8367 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8368 N->getOperand(0)->getOperand(0), MaskConst);
8369 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8370 return Res;
8371 }
8372
8373 return SDValue();
8374}
8375
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008376static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8377 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00008378 // First try to optimize away the conversion when it's conditionally from
8379 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008380 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00008381 return Res;
8382
Tim Northover3b0846e2014-05-24 12:50:23 +00008383 EVT VT = N->getValueType(0);
8384 if (VT != MVT::f32 && VT != MVT::f64)
8385 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00008386
Tim Northover3b0846e2014-05-24 12:50:23 +00008387 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008388 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00008389 return SDValue();
8390
8391 // If the result of an integer load is only used by an integer-to-float
8392 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00008393 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00008394 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00008395 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008396 // Do not change the width of a volatile load.
8397 !cast<LoadSDNode>(N0)->isVolatile()) {
8398 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8399 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00008400 LN0->getPointerInfo(), LN0->getAlignment(),
8401 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008402
8403 // Make sure successors of the original load stay after it by updating them
8404 // to use the new Chain.
8405 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8406
8407 unsigned Opcode =
8408 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8409 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8410 }
8411
8412 return SDValue();
8413}
8414
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008415/// Fold a floating-point multiply by power of two into floating-point to
8416/// fixed-point conversion.
8417static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00008418 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008419 const AArch64Subtarget *Subtarget) {
8420 if (!Subtarget->hasNEON())
8421 return SDValue();
8422
8423 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00008424 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8425 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008426 return SDValue();
8427
8428 SDValue ConstVec = Op->getOperand(1);
8429 if (!isa<BuildVectorSDNode>(ConstVec))
8430 return SDValue();
8431
8432 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8433 uint32_t FloatBits = FloatTy.getSizeInBits();
8434 if (FloatBits != 32 && FloatBits != 64)
8435 return SDValue();
8436
8437 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8438 uint32_t IntBits = IntTy.getSizeInBits();
8439 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8440 return SDValue();
8441
8442 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8443 if (IntBits > FloatBits)
8444 return SDValue();
8445
8446 BitVector UndefElements;
8447 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8448 int32_t Bits = IntBits == 64 ? 64 : 32;
8449 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8450 if (C == -1 || C == 0 || C > Bits)
8451 return SDValue();
8452
8453 MVT ResTy;
8454 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8455 switch (NumLanes) {
8456 default:
8457 return SDValue();
8458 case 2:
8459 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8460 break;
8461 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00008462 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008463 break;
8464 }
8465
Silviu Barangafa00ba32016-08-08 13:13:57 +00008466 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8467 return SDValue();
8468
8469 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8470 "Illegal vector type after legalization");
8471
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008472 SDLoc DL(N);
8473 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8474 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8475 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8476 SDValue FixConv =
8477 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8478 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8479 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8480 // We can handle smaller integers by generating an extra trunc.
8481 if (IntBits < FloatBits)
8482 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8483
8484 return FixConv;
8485}
8486
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008487/// Fold a floating-point divide by power of two into fixed-point to
8488/// floating-point conversion.
8489static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00008490 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008491 const AArch64Subtarget *Subtarget) {
8492 if (!Subtarget->hasNEON())
8493 return SDValue();
8494
8495 SDValue Op = N->getOperand(0);
8496 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00008497 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8498 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008499 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8500 return SDValue();
8501
8502 SDValue ConstVec = N->getOperand(1);
8503 if (!isa<BuildVectorSDNode>(ConstVec))
8504 return SDValue();
8505
8506 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8507 int32_t IntBits = IntTy.getSizeInBits();
8508 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8509 return SDValue();
8510
8511 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8512 int32_t FloatBits = FloatTy.getSizeInBits();
8513 if (FloatBits != 32 && FloatBits != 64)
8514 return SDValue();
8515
8516 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8517 if (IntBits > FloatBits)
8518 return SDValue();
8519
8520 BitVector UndefElements;
8521 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8522 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8523 if (C == -1 || C == 0 || C > FloatBits)
8524 return SDValue();
8525
8526 MVT ResTy;
8527 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8528 switch (NumLanes) {
8529 default:
8530 return SDValue();
8531 case 2:
8532 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8533 break;
8534 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00008535 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008536 break;
8537 }
8538
Tim Northover85cf5642016-08-26 18:52:31 +00008539 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8540 return SDValue();
8541
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008542 SDLoc DL(N);
8543 SDValue ConvInput = Op.getOperand(0);
8544 bool IsSigned = Opc == ISD::SINT_TO_FP;
8545 if (IntBits < FloatBits)
8546 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8547 ResTy, ConvInput);
8548
8549 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8550 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8551 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8552 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8553 DAG.getConstant(C, DL, MVT::i32));
8554}
8555
Tim Northover3b0846e2014-05-24 12:50:23 +00008556/// An EXTR instruction is made up of two shifts, ORed together. This helper
8557/// searches for and classifies those shifts.
8558static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8559 bool &FromHi) {
8560 if (N.getOpcode() == ISD::SHL)
8561 FromHi = false;
8562 else if (N.getOpcode() == ISD::SRL)
8563 FromHi = true;
8564 else
8565 return false;
8566
8567 if (!isa<ConstantSDNode>(N.getOperand(1)))
8568 return false;
8569
8570 ShiftAmount = N->getConstantOperandVal(1);
8571 Src = N->getOperand(0);
8572 return true;
8573}
8574
8575/// EXTR instruction extracts a contiguous chunk of bits from two existing
8576/// registers viewed as a high/low pair. This function looks for the pattern:
Joel Jones7466ccf2017-07-10 22:11:50 +00008577/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
8578/// with an EXTR. Can't quite be done in TableGen because the two immediates
8579/// aren't independent.
Tim Northover3b0846e2014-05-24 12:50:23 +00008580static SDValue tryCombineToEXTR(SDNode *N,
8581 TargetLowering::DAGCombinerInfo &DCI) {
8582 SelectionDAG &DAG = DCI.DAG;
8583 SDLoc DL(N);
8584 EVT VT = N->getValueType(0);
8585
8586 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8587
8588 if (VT != MVT::i32 && VT != MVT::i64)
8589 return SDValue();
8590
8591 SDValue LHS;
8592 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008593 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008594 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8595 return SDValue();
8596
8597 SDValue RHS;
8598 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008599 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008600 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8601 return SDValue();
8602
8603 // If they're both trying to come from the high part of the register, they're
8604 // not really an EXTR.
8605 if (LHSFromHi == RHSFromHi)
8606 return SDValue();
8607
8608 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8609 return SDValue();
8610
8611 if (LHSFromHi) {
8612 std::swap(LHS, RHS);
8613 std::swap(ShiftLHS, ShiftRHS);
8614 }
8615
8616 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008617 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008618}
8619
8620static SDValue tryCombineToBSL(SDNode *N,
8621 TargetLowering::DAGCombinerInfo &DCI) {
8622 EVT VT = N->getValueType(0);
8623 SelectionDAG &DAG = DCI.DAG;
8624 SDLoc DL(N);
8625
8626 if (!VT.isVector())
8627 return SDValue();
8628
8629 SDValue N0 = N->getOperand(0);
8630 if (N0.getOpcode() != ISD::AND)
8631 return SDValue();
8632
8633 SDValue N1 = N->getOperand(1);
8634 if (N1.getOpcode() != ISD::AND)
8635 return SDValue();
8636
8637 // We only have to look for constant vectors here since the general, variable
8638 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008639 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008640 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8641 for (int i = 1; i >= 0; --i)
8642 for (int j = 1; j >= 0; --j) {
8643 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8644 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8645 if (!BVN0 || !BVN1)
8646 continue;
8647
8648 bool FoundMatch = true;
8649 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8650 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8651 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8652 if (!CN0 || !CN1 ||
8653 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8654 FoundMatch = false;
8655 break;
8656 }
8657 }
8658
8659 if (FoundMatch)
8660 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8661 N0->getOperand(1 - i), N1->getOperand(1 - j));
8662 }
8663
8664 return SDValue();
8665}
8666
8667static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8668 const AArch64Subtarget *Subtarget) {
8669 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00008670 SelectionDAG &DAG = DCI.DAG;
8671 EVT VT = N->getValueType(0);
8672
8673 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8674 return SDValue();
8675
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008676 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008677 return Res;
8678
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008679 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008680 return Res;
8681
8682 return SDValue();
8683}
8684
Chad Rosier14aa2ad2016-05-26 19:41:33 +00008685static SDValue performSRLCombine(SDNode *N,
8686 TargetLowering::DAGCombinerInfo &DCI) {
8687 SelectionDAG &DAG = DCI.DAG;
8688 EVT VT = N->getValueType(0);
8689 if (VT != MVT::i32 && VT != MVT::i64)
8690 return SDValue();
8691
8692 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8693 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8694 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8695 SDValue N0 = N->getOperand(0);
8696 if (N0.getOpcode() == ISD::BSWAP) {
8697 SDLoc DL(N);
8698 SDValue N1 = N->getOperand(1);
8699 SDValue N00 = N0.getOperand(0);
8700 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8701 uint64_t ShiftAmt = C->getZExtValue();
8702 if (VT == MVT::i32 && ShiftAmt == 16 &&
8703 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8704 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8705 if (VT == MVT::i64 && ShiftAmt == 32 &&
8706 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8707 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8708 }
8709 }
8710 return SDValue();
8711}
8712
Tim Northover3b0846e2014-05-24 12:50:23 +00008713static SDValue performBitcastCombine(SDNode *N,
8714 TargetLowering::DAGCombinerInfo &DCI,
8715 SelectionDAG &DAG) {
8716 // Wait 'til after everything is legalized to try this. That way we have
8717 // legal vector types and such.
8718 if (DCI.isBeforeLegalizeOps())
8719 return SDValue();
8720
8721 // Remove extraneous bitcasts around an extract_subvector.
8722 // For example,
8723 // (v4i16 (bitconvert
8724 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8725 // becomes
8726 // (extract_subvector ((v8i16 ...), (i64 4)))
8727
8728 // Only interested in 64-bit vectors as the ultimate result.
8729 EVT VT = N->getValueType(0);
8730 if (!VT.isVector())
8731 return SDValue();
8732 if (VT.getSimpleVT().getSizeInBits() != 64)
8733 return SDValue();
8734 // Is the operand an extract_subvector starting at the beginning or halfway
8735 // point of the vector? A low half may also come through as an
8736 // EXTRACT_SUBREG, so look for that, too.
8737 SDValue Op0 = N->getOperand(0);
8738 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8739 !(Op0->isMachineOpcode() &&
8740 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8741 return SDValue();
8742 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8743 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8744 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8745 return SDValue();
8746 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8747 if (idx != AArch64::dsub)
8748 return SDValue();
8749 // The dsub reference is equivalent to a lane zero subvector reference.
8750 idx = 0;
8751 }
8752 // Look through the bitcast of the input to the extract.
8753 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8754 return SDValue();
8755 SDValue Source = Op0->getOperand(0)->getOperand(0);
8756 // If the source type has twice the number of elements as our destination
8757 // type, we know this is an extract of the high or low half of the vector.
8758 EVT SVT = Source->getValueType(0);
Evandro Menezes10ae20d2018-02-16 20:00:57 +00008759 if (!SVT.isVector() ||
8760 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00008761 return SDValue();
8762
8763 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8764
8765 // Create the simplified form to just extract the low or high half of the
8766 // vector directly rather than bothering with the bitcasts.
8767 SDLoc dl(N);
8768 unsigned NumElements = VT.getVectorNumElements();
8769 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008770 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008771 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8772 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008773 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008774 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8775 Source, SubReg),
8776 0);
8777 }
8778}
8779
8780static SDValue performConcatVectorsCombine(SDNode *N,
8781 TargetLowering::DAGCombinerInfo &DCI,
8782 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008783 SDLoc dl(N);
8784 EVT VT = N->getValueType(0);
8785 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8786
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008787 // Optimize concat_vectors of truncated vectors, where the intermediate
8788 // type is illegal, to avoid said illegality, e.g.,
8789 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8790 // (v2i16 (truncate (v2i64)))))
8791 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008792 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8793 // (v4i32 (bitcast (v2i64))),
8794 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008795 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8796 // on both input and result type, so we might generate worse code.
8797 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8798 if (N->getNumOperands() == 2 &&
8799 N0->getOpcode() == ISD::TRUNCATE &&
8800 N1->getOpcode() == ISD::TRUNCATE) {
8801 SDValue N00 = N0->getOperand(0);
8802 SDValue N10 = N1->getOperand(0);
8803 EVT N00VT = N00.getValueType();
8804
8805 if (N00VT == N10.getValueType() &&
8806 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8807 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008808 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8809 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8810 for (size_t i = 0; i < Mask.size(); ++i)
8811 Mask[i] = i * 2;
8812 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8813 DAG.getVectorShuffle(
8814 MidVT, dl,
8815 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8816 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008817 }
8818 }
8819
Tim Northover3b0846e2014-05-24 12:50:23 +00008820 // Wait 'til after everything is legalized to try this. That way we have
8821 // legal vector types and such.
8822 if (DCI.isBeforeLegalizeOps())
8823 return SDValue();
8824
Tim Northover3b0846e2014-05-24 12:50:23 +00008825 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8826 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8827 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008828 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008829 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008830 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008831 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008832 }
8833
8834 // Canonicalise concat_vectors so that the right-hand vector has as few
8835 // bit-casts as possible before its real operation. The primary matching
8836 // destination for these operations will be the narrowing "2" instructions,
8837 // which depend on the operation being performed on this right-hand vector.
8838 // For example,
8839 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8840 // becomes
8841 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8842
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008843 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008844 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008845 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008846 MVT RHSTy = RHS.getValueType().getSimpleVT();
8847 // If the RHS is not a vector, this is not the pattern we're looking for.
8848 if (!RHSTy.isVector())
8849 return SDValue();
8850
8851 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8852
8853 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8854 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008855 return DAG.getNode(ISD::BITCAST, dl, VT,
8856 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8857 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8858 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008859}
8860
8861static SDValue tryCombineFixedPointConvert(SDNode *N,
8862 TargetLowering::DAGCombinerInfo &DCI,
8863 SelectionDAG &DAG) {
Carey Williams22c49c62018-01-19 16:55:23 +00008864 // Wait until after everything is legalized to try this. That way we have
Tim Northover3b0846e2014-05-24 12:50:23 +00008865 // legal vector types and such.
8866 if (DCI.isBeforeLegalizeOps())
8867 return SDValue();
8868 // Transform a scalar conversion of a value from a lane extract into a
8869 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8870 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8871 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8872 //
8873 // The second form interacts better with instruction selection and the
8874 // register allocator to avoid cross-class register copies that aren't
8875 // coalescable due to a lane reference.
8876
8877 // Check the operand and see if it originates from a lane extract.
8878 SDValue Op1 = N->getOperand(1);
8879 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8880 // Yep, no additional predication needed. Perform the transform.
8881 SDValue IID = N->getOperand(0);
8882 SDValue Shift = N->getOperand(2);
8883 SDValue Vec = Op1.getOperand(0);
8884 SDValue Lane = Op1.getOperand(1);
8885 EVT ResTy = N->getValueType(0);
8886 EVT VecResTy;
8887 SDLoc DL(N);
8888
8889 // The vector width should be 128 bits by the time we get here, even
8890 // if it started as 64 bits (the extract_vector handling will have
8891 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008892 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008893 "unexpected vector size on extract_vector_elt!");
8894 if (Vec.getValueType() == MVT::v4i32)
8895 VecResTy = MVT::v4f32;
8896 else if (Vec.getValueType() == MVT::v2i64)
8897 VecResTy = MVT::v2f64;
8898 else
Craig Topper2a30d782014-06-18 05:05:13 +00008899 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008900
8901 SDValue Convert =
8902 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8903 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8904 }
8905 return SDValue();
8906}
8907
8908// AArch64 high-vector "long" operations are formed by performing the non-high
8909// version on an extract_subvector of each operand which gets the high half:
8910//
8911// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8912//
8913// However, there are cases which don't have an extract_high explicitly, but
8914// have another operation that can be made compatible with one for free. For
8915// example:
8916//
8917// (dupv64 scalar) --> (extract_high (dup128 scalar))
8918//
8919// This routine does the actual conversion of such DUPs, once outer routines
8920// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008921// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8922// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008923static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008924 switch (N.getOpcode()) {
8925 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008926 case AArch64ISD::DUPLANE8:
8927 case AArch64ISD::DUPLANE16:
8928 case AArch64ISD::DUPLANE32:
8929 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008930 case AArch64ISD::MOVI:
8931 case AArch64ISD::MOVIshift:
8932 case AArch64ISD::MOVIedit:
8933 case AArch64ISD::MOVImsl:
8934 case AArch64ISD::MVNIshift:
8935 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008936 break;
8937 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008938 // FMOV could be supported, but isn't very useful, as it would only occur
8939 // if you passed a bitcast' floating point immediate to an eligible long
8940 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008941 return SDValue();
8942 }
8943
8944 MVT NarrowTy = N.getSimpleValueType();
8945 if (!NarrowTy.is64BitVector())
8946 return SDValue();
8947
8948 MVT ElementTy = NarrowTy.getVectorElementType();
8949 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008950 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008951
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008952 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008953 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8954 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008955 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008956}
8957
8958static bool isEssentiallyExtractSubvector(SDValue N) {
8959 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8960 return true;
8961
8962 return N.getOpcode() == ISD::BITCAST &&
8963 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8964}
8965
8966/// \brief Helper structure to keep track of ISD::SET_CC operands.
8967struct GenericSetCCInfo {
8968 const SDValue *Opnd0;
8969 const SDValue *Opnd1;
8970 ISD::CondCode CC;
8971};
8972
8973/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8974struct AArch64SetCCInfo {
8975 const SDValue *Cmp;
8976 AArch64CC::CondCode CC;
8977};
8978
8979/// \brief Helper structure to keep track of SetCC information.
8980union SetCCInfo {
8981 GenericSetCCInfo Generic;
8982 AArch64SetCCInfo AArch64;
8983};
8984
8985/// \brief Helper structure to be able to read SetCC information. If set to
8986/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8987/// GenericSetCCInfo.
8988struct SetCCInfoAndKind {
8989 SetCCInfo Info;
8990 bool IsAArch64;
8991};
8992
8993/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8994/// an
8995/// AArch64 lowered one.
8996/// \p SetCCInfo is filled accordingly.
8997/// \post SetCCInfo is meanginfull only when this function returns true.
8998/// \return True when Op is a kind of SET_CC operation.
8999static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9000 // If this is a setcc, this is straight forward.
9001 if (Op.getOpcode() == ISD::SETCC) {
9002 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9003 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9004 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9005 SetCCInfo.IsAArch64 = false;
9006 return true;
9007 }
9008 // Otherwise, check if this is a matching csel instruction.
9009 // In other words:
9010 // - csel 1, 0, cc
9011 // - csel 0, 1, !cc
9012 if (Op.getOpcode() != AArch64ISD::CSEL)
9013 return false;
9014 // Set the information about the operands.
9015 // TODO: we want the operands of the Cmp not the csel
9016 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9017 SetCCInfo.IsAArch64 = true;
9018 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9019 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9020
9021 // Check that the operands matches the constraints:
9022 // (1) Both operands must be constants.
9023 // (2) One must be 1 and the other must be 0.
9024 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9025 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9026
9027 // Check (1).
9028 if (!TValue || !FValue)
9029 return false;
9030
9031 // Check (2).
9032 if (!TValue->isOne()) {
9033 // Update the comparison when we are interested in !cc.
9034 std::swap(TValue, FValue);
9035 SetCCInfo.Info.AArch64.CC =
9036 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9037 }
9038 return TValue->isOne() && FValue->isNullValue();
9039}
9040
9041// Returns true if Op is setcc or zext of setcc.
9042static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9043 if (isSetCC(Op, Info))
9044 return true;
9045 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9046 isSetCC(Op->getOperand(0), Info));
9047}
9048
9049// The folding we want to perform is:
9050// (add x, [zext] (setcc cc ...) )
9051// -->
9052// (csel x, (add x, 1), !cc ...)
9053//
9054// The latter will get matched to a CSINC instruction.
9055static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9056 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9057 SDValue LHS = Op->getOperand(0);
9058 SDValue RHS = Op->getOperand(1);
9059 SetCCInfoAndKind InfoAndKind;
9060
9061 // If neither operand is a SET_CC, give up.
9062 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9063 std::swap(LHS, RHS);
9064 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9065 return SDValue();
9066 }
9067
9068 // FIXME: This could be generatized to work for FP comparisons.
9069 EVT CmpVT = InfoAndKind.IsAArch64
9070 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9071 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9072 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9073 return SDValue();
9074
9075 SDValue CCVal;
9076 SDValue Cmp;
9077 SDLoc dl(Op);
9078 if (InfoAndKind.IsAArch64) {
9079 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009080 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9081 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00009082 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9083 } else
9084 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9085 *InfoAndKind.Info.Generic.Opnd1,
9086 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9087 CCVal, DAG, dl);
9088
9089 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009090 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00009091 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9092}
9093
9094// The basic add/sub long vector instructions have variants with "2" on the end
9095// which act on the high-half of their inputs. They are normally matched by
9096// patterns like:
9097//
9098// (add (zeroext (extract_high LHS)),
9099// (zeroext (extract_high RHS)))
9100// -> uaddl2 vD, vN, vM
9101//
9102// However, if one of the extracts is something like a duplicate, this
9103// instruction can still be used profitably. This function puts the DAG into a
9104// more appropriate form for those patterns to trigger.
9105static SDValue performAddSubLongCombine(SDNode *N,
9106 TargetLowering::DAGCombinerInfo &DCI,
9107 SelectionDAG &DAG) {
9108 if (DCI.isBeforeLegalizeOps())
9109 return SDValue();
9110
9111 MVT VT = N->getSimpleValueType(0);
9112 if (!VT.is128BitVector()) {
9113 if (N->getOpcode() == ISD::ADD)
9114 return performSetccAddFolding(N, DAG);
9115 return SDValue();
9116 }
9117
9118 // Make sure both branches are extended in the same way.
9119 SDValue LHS = N->getOperand(0);
9120 SDValue RHS = N->getOperand(1);
9121 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9122 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9123 LHS.getOpcode() != RHS.getOpcode())
9124 return SDValue();
9125
9126 unsigned ExtType = LHS.getOpcode();
9127
9128 // It's not worth doing if at least one of the inputs isn't already an
9129 // extract, but we don't know which it'll be so we have to try both.
9130 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9131 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9132 if (!RHS.getNode())
9133 return SDValue();
9134
9135 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9136 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9137 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9138 if (!LHS.getNode())
9139 return SDValue();
9140
9141 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9142 }
9143
9144 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9145}
9146
9147// Massage DAGs which we can use the high-half "long" operations on into
9148// something isel will recognize better. E.g.
9149//
9150// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9151// (aarch64_neon_umull (extract_high (v2i64 vec)))
9152// (extract_high (v2i64 (dup128 scalar)))))
9153//
Hal Finkelcd8664c2015-12-11 23:11:52 +00009154static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00009155 TargetLowering::DAGCombinerInfo &DCI,
9156 SelectionDAG &DAG) {
9157 if (DCI.isBeforeLegalizeOps())
9158 return SDValue();
9159
Hal Finkelcd8664c2015-12-11 23:11:52 +00009160 SDValue LHS = N->getOperand(1);
9161 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00009162 assert(LHS.getValueType().is64BitVector() &&
9163 RHS.getValueType().is64BitVector() &&
9164 "unexpected shape for long operation");
9165
9166 // Either node could be a DUP, but it's not worth doing both of them (you'd
9167 // just as well use the non-high version) so look for a corresponding extract
9168 // operation on the other "wing".
9169 if (isEssentiallyExtractSubvector(LHS)) {
9170 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9171 if (!RHS.getNode())
9172 return SDValue();
9173 } else if (isEssentiallyExtractSubvector(RHS)) {
9174 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9175 if (!LHS.getNode())
9176 return SDValue();
9177 }
9178
Hal Finkelcd8664c2015-12-11 23:11:52 +00009179 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9180 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00009181}
9182
9183static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9184 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9185 unsigned ElemBits = ElemTy.getSizeInBits();
9186
9187 int64_t ShiftAmount;
9188 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9189 APInt SplatValue, SplatUndef;
9190 unsigned SplatBitSize;
9191 bool HasAnyUndefs;
9192 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9193 HasAnyUndefs, ElemBits) ||
9194 SplatBitSize != ElemBits)
9195 return SDValue();
9196
9197 ShiftAmount = SplatValue.getSExtValue();
9198 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9199 ShiftAmount = CVN->getSExtValue();
9200 } else
9201 return SDValue();
9202
9203 unsigned Opcode;
9204 bool IsRightShift;
9205 switch (IID) {
9206 default:
9207 llvm_unreachable("Unknown shift intrinsic");
9208 case Intrinsic::aarch64_neon_sqshl:
9209 Opcode = AArch64ISD::SQSHL_I;
9210 IsRightShift = false;
9211 break;
9212 case Intrinsic::aarch64_neon_uqshl:
9213 Opcode = AArch64ISD::UQSHL_I;
9214 IsRightShift = false;
9215 break;
9216 case Intrinsic::aarch64_neon_srshl:
9217 Opcode = AArch64ISD::SRSHR_I;
9218 IsRightShift = true;
9219 break;
9220 case Intrinsic::aarch64_neon_urshl:
9221 Opcode = AArch64ISD::URSHR_I;
9222 IsRightShift = true;
9223 break;
9224 case Intrinsic::aarch64_neon_sqshlu:
9225 Opcode = AArch64ISD::SQSHLU_I;
9226 IsRightShift = false;
9227 break;
9228 }
9229
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009230 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9231 SDLoc dl(N);
9232 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9233 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9234 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9235 SDLoc dl(N);
9236 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9237 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9238 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009239
9240 return SDValue();
9241}
9242
9243// The CRC32[BH] instructions ignore the high bits of their data operand. Since
9244// the intrinsics must be legal and take an i32, this means there's almost
9245// certainly going to be a zext in the DAG which we can eliminate.
9246static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9247 SDValue AndN = N->getOperand(2);
9248 if (AndN.getOpcode() != ISD::AND)
9249 return SDValue();
9250
9251 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9252 if (!CMask || CMask->getZExtValue() != Mask)
9253 return SDValue();
9254
9255 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9256 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9257}
9258
Ahmed Bougachafab58922015-03-10 20:45:38 +00009259static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9260 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009261 SDLoc dl(N);
9262 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9263 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00009264 N->getOperand(1).getSimpleValueType(),
9265 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009266 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00009267}
9268
Tim Northover3b0846e2014-05-24 12:50:23 +00009269static SDValue performIntrinsicCombine(SDNode *N,
9270 TargetLowering::DAGCombinerInfo &DCI,
9271 const AArch64Subtarget *Subtarget) {
9272 SelectionDAG &DAG = DCI.DAG;
9273 unsigned IID = getIntrinsicID(N);
9274 switch (IID) {
9275 default:
9276 break;
9277 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9278 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9279 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00009280 case Intrinsic::aarch64_neon_saddv:
9281 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9282 case Intrinsic::aarch64_neon_uaddv:
9283 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9284 case Intrinsic::aarch64_neon_sminv:
9285 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9286 case Intrinsic::aarch64_neon_uminv:
9287 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9288 case Intrinsic::aarch64_neon_smaxv:
9289 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9290 case Intrinsic::aarch64_neon_umaxv:
9291 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009292 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00009293 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009294 N->getOperand(1), N->getOperand(2));
9295 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00009296 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00009297 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00009298 case Intrinsic::aarch64_neon_fmaxnm:
9299 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9300 N->getOperand(1), N->getOperand(2));
9301 case Intrinsic::aarch64_neon_fminnm:
9302 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9303 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009304 case Intrinsic::aarch64_neon_smull:
9305 case Intrinsic::aarch64_neon_umull:
9306 case Intrinsic::aarch64_neon_pmull:
9307 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00009308 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009309 case Intrinsic::aarch64_neon_sqshl:
9310 case Intrinsic::aarch64_neon_uqshl:
9311 case Intrinsic::aarch64_neon_sqshlu:
9312 case Intrinsic::aarch64_neon_srshl:
9313 case Intrinsic::aarch64_neon_urshl:
9314 return tryCombineShiftImm(IID, N, DAG);
9315 case Intrinsic::aarch64_crc32b:
9316 case Intrinsic::aarch64_crc32cb:
9317 return tryCombineCRC32(0xff, N, DAG);
9318 case Intrinsic::aarch64_crc32h:
9319 case Intrinsic::aarch64_crc32ch:
9320 return tryCombineCRC32(0xffff, N, DAG);
9321 }
9322 return SDValue();
9323}
9324
9325static SDValue performExtendCombine(SDNode *N,
9326 TargetLowering::DAGCombinerInfo &DCI,
9327 SelectionDAG &DAG) {
9328 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9329 // we can convert that DUP into another extract_high (of a bigger DUP), which
9330 // helps the backend to decide that an sabdl2 would be useful, saving a real
9331 // extract_high operation.
9332 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00009333 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009334 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00009335 unsigned IID = getIntrinsicID(ABDNode);
9336 if (IID == Intrinsic::aarch64_neon_sabd ||
9337 IID == Intrinsic::aarch64_neon_uabd) {
9338 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9339 if (!NewABD.getNode())
9340 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009341
Hal Finkelcd8664c2015-12-11 23:11:52 +00009342 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9343 NewABD);
9344 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009345 }
9346
9347 // This is effectively a custom type legalization for AArch64.
9348 //
9349 // Type legalization will split an extend of a small, legal, type to a larger
9350 // illegal type by first splitting the destination type, often creating
9351 // illegal source types, which then get legalized in isel-confusing ways,
9352 // leading to really terrible codegen. E.g.,
9353 // %result = v8i32 sext v8i8 %value
9354 // becomes
9355 // %losrc = extract_subreg %value, ...
9356 // %hisrc = extract_subreg %value, ...
9357 // %lo = v4i32 sext v4i8 %losrc
9358 // %hi = v4i32 sext v4i8 %hisrc
9359 // Things go rapidly downhill from there.
9360 //
9361 // For AArch64, the [sz]ext vector instructions can only go up one element
9362 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9363 // take two instructions.
9364 //
9365 // This implies that the most efficient way to do the extend from v8i8
9366 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9367 // the normal splitting to happen for the v8i16->v8i32.
9368
9369 // This is pre-legalization to catch some cases where the default
9370 // type legalization will create ill-tempered code.
9371 if (!DCI.isBeforeLegalizeOps())
9372 return SDValue();
9373
9374 // We're only interested in cleaning things up for non-legal vector types
9375 // here. If both the source and destination are legal, things will just
9376 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00009377 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00009378 EVT ResVT = N->getValueType(0);
9379 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9380 return SDValue();
9381 // If the vector type isn't a simple VT, it's beyond the scope of what
9382 // we're worried about here. Let legalization do its thing and hope for
9383 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00009384 SDValue Src = N->getOperand(0);
9385 EVT SrcVT = Src->getValueType(0);
9386 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00009387 return SDValue();
9388
Tim Northover3b0846e2014-05-24 12:50:23 +00009389 // If the source VT is a 64-bit vector, we can play games and get the
9390 // better results we want.
9391 if (SrcVT.getSizeInBits() != 64)
9392 return SDValue();
9393
Sanjay Patel1ed771f2016-09-14 16:37:15 +00009394 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00009395 unsigned ElementCount = SrcVT.getVectorNumElements();
9396 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9397 SDLoc DL(N);
9398 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9399
9400 // Now split the rest of the operation into two halves, each with a 64
9401 // bit source.
9402 EVT LoVT, HiVT;
9403 SDValue Lo, Hi;
9404 unsigned NumElements = ResVT.getVectorNumElements();
9405 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9406 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9407 ResVT.getVectorElementType(), NumElements / 2);
9408
9409 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9410 LoVT.getVectorNumElements());
9411 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009412 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009413 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009414 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009415 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9416 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9417
9418 // Now combine the parts back together so we still have a single result
9419 // like the combiner expects.
9420 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9421}
9422
Geoff Berry8301c642016-11-16 19:35:19 +00009423static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9424 SDValue SplatVal, unsigned NumVecElts) {
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009425 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +00009426 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009427
9428 // Create scalar stores. This is at least as good as the code sequence for a
9429 // split unaligned store which is a dup.s, ext.b, and two stores.
9430 // Most of the time the three stores should be replaced by store pair
9431 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009432 SDLoc DL(&St);
9433 SDValue BasePtr = St.getBasePtr();
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009434 uint64_t BaseOffset = 0;
Nirav Davebb20b5d2017-05-24 19:55:49 +00009435
John Brawn3a9c8422017-02-06 18:07:20 +00009436 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009437 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +00009438 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +00009439 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009440
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009441 // As this in ISel, we will not merge this add which may degrade results.
Nirav Davebb20b5d2017-05-24 19:55:49 +00009442 if (BasePtr->getOpcode() == ISD::ADD &&
9443 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9444 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9445 BasePtr = BasePtr->getOperand(0);
9446 }
9447
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009448 unsigned Offset = EltOffset;
9449 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +00009450 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Nirav Dave6ff50bf2017-05-26 12:53:10 +00009451 SDValue OffsetPtr =
9452 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9453 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009454 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +00009455 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009456 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009457 Offset += EltOffset;
9458 }
9459 return NewST1;
9460}
9461
Geoff Berry526c5052016-11-14 19:39:04 +00009462/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9463/// load store optimizer pass will merge them to store pair stores. This should
9464/// be better than a movi to create the vector zero followed by a vector store
9465/// if the zero constant is not re-used, since one instructions and one register
9466/// live range will be removed.
9467///
9468/// For example, the final generated code should be:
9469///
9470/// stp xzr, xzr, [x0]
9471///
9472/// instead of:
9473///
9474/// movi v0.2d, #0
9475/// str q0, [x0]
9476///
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009477static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9478 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +00009479 EVT VT = StVal.getValueType();
9480
Geoff Berry8301c642016-11-16 19:35:19 +00009481 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9482 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +00009483 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +00009484 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9485 VT.getVectorElementType().getSizeInBits() == 64) ||
9486 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9487 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +00009488 return SDValue();
9489
9490 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9491 return SDValue();
9492
9493 // If the zero constant has more than one use then the vector store could be
9494 // better since the constant mov will be amortized and stp q instructions
9495 // should be able to be formed.
9496 if (!StVal.hasOneUse())
9497 return SDValue();
9498
9499 // If the immediate offset of the address operand is too large for the stp
9500 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009501 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9502 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +00009503 if (Offset < -512 || Offset > 504)
9504 return SDValue();
9505 }
9506
9507 for (int I = 0; I < NumVecElts; ++I) {
9508 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +00009509 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +00009510 return SDValue();
9511 }
Geoff Berry8301c642016-11-16 19:35:19 +00009512
Geoff Berrybb23df92017-09-21 21:10:06 +00009513 // Use a CopyFromReg WZR/XZR here to prevent
9514 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
9515 SDLoc DL(&St);
9516 unsigned ZeroReg;
9517 EVT ZeroVT;
9518 if (VT.getVectorElementType().getSizeInBits() == 32) {
9519 ZeroReg = AArch64::WZR;
9520 ZeroVT = MVT::i32;
9521 } else {
9522 ZeroReg = AArch64::XZR;
9523 ZeroVT = MVT::i64;
9524 }
9525 SDValue SplatVal =
9526 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
Geoff Berry8301c642016-11-16 19:35:19 +00009527 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +00009528}
9529
Tim Northover3b0846e2014-05-24 12:50:23 +00009530/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9531/// value. The load store optimizer pass will merge them to store pair stores.
9532/// This has better performance than a splat of the scalar followed by a split
9533/// vector store. Even if the stores are not merged it is four stores vs a dup,
9534/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009535static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9536 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009537 EVT VT = StVal.getValueType();
9538
9539 // Don't replace floating point stores, they possibly won't be transformed to
9540 // stp because of the store pair suppress pass.
9541 if (VT.isFloatingPoint())
9542 return SDValue();
9543
Tim Northover3b0846e2014-05-24 12:50:23 +00009544 // We can express a splat as store pair(s) for 2 or 4 elements.
9545 unsigned NumVecElts = VT.getVectorNumElements();
9546 if (NumVecElts != 4 && NumVecElts != 2)
9547 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009548
9549 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +00009550 // Make sure that each of the relevant vector element locations are inserted
9551 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9552 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9553 SDValue SplatVal;
9554 for (unsigned I = 0; I < NumVecElts; ++I) {
9555 // Check for insert vector elements.
9556 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +00009557 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009558
9559 // Check that same value is inserted at each vector element.
9560 if (I == 0)
9561 SplatVal = StVal.getOperand(1);
9562 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +00009563 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009564
9565 // Check insert element index.
9566 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9567 if (!CIndex)
9568 return SDValue();
9569 uint64_t IndexVal = CIndex->getZExtValue();
9570 if (IndexVal >= NumVecElts)
9571 return SDValue();
9572 IndexNotInserted.reset(IndexVal);
9573
9574 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009575 }
Geoff Berry25fa4992016-11-11 19:25:20 +00009576 // Check that all vector element locations were inserted to.
9577 if (IndexNotInserted.any())
9578 return SDValue();
9579
Geoff Berry8301c642016-11-16 19:35:19 +00009580 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009581}
9582
Geoff Berry8301c642016-11-16 19:35:19 +00009583static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9584 SelectionDAG &DAG,
9585 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009586
9587 StoreSDNode *S = cast<StoreSDNode>(N);
Nirav Dave85e92222017-06-15 14:47:44 +00009588 if (S->isVolatile() || S->isIndexed())
Tim Northover3b0846e2014-05-24 12:50:23 +00009589 return SDValue();
9590
Geoff Berry526c5052016-11-14 19:39:04 +00009591 SDValue StVal = S->getValue();
9592 EVT VT = StVal.getValueType();
9593 if (!VT.isVector())
9594 return SDValue();
9595
9596 // If we get a splat of zeros, convert this vector store to a store of
9597 // scalars. They will be merged into store pairs of xzr thereby removing one
9598 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009599 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +00009600 return ReplacedZeroSplat;
9601
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00009602 // FIXME: The logic for deciding if an unaligned store should be split should
9603 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9604 // a call to that function here.
9605
Matthias Braun651cff42016-06-02 18:03:53 +00009606 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00009607 return SDValue();
9608
Sanjay Patel924879a2015-08-04 15:49:57 +00009609 // Don't split at -Oz.
Matthias Braunf1caa282017-12-15 22:22:58 +00009610 if (DAG.getMachineFunction().getFunction().optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00009611 return SDValue();
9612
Tim Northover3b0846e2014-05-24 12:50:23 +00009613 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9614 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +00009615 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +00009616 return SDValue();
9617
9618 // Split unaligned 16B stores. They are terrible for performance.
9619 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9620 // extensions can use this to mark that it does not want splitting to happen
9621 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9622 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9623 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9624 S->getAlignment() <= 2)
9625 return SDValue();
9626
9627 // If we get a splat of a scalar convert this vector store to a store of
9628 // scalars. They will be merged into store pairs thereby removing two
9629 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009630 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +00009631 return ReplacedSplat;
9632
9633 SDLoc DL(S);
9634 unsigned NumElts = VT.getVectorNumElements() / 2;
9635 // Split VT into two.
9636 EVT HalfVT =
9637 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9638 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009639 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009640 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009641 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009642 SDValue BasePtr = S->getBasePtr();
9643 SDValue NewST1 =
9644 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00009645 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009646 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009647 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009648 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00009649 S->getPointerInfo(), S->getAlignment(),
9650 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009651}
9652
9653/// Target-specific DAG combine function for post-increment LD1 (lane) and
9654/// post-increment LD1R.
9655static SDValue performPostLD1Combine(SDNode *N,
9656 TargetLowering::DAGCombinerInfo &DCI,
9657 bool IsLaneOp) {
9658 if (DCI.isBeforeLegalizeOps())
9659 return SDValue();
9660
9661 SelectionDAG &DAG = DCI.DAG;
9662 EVT VT = N->getValueType(0);
9663
9664 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9665 SDNode *LD = N->getOperand(LoadIdx).getNode();
9666 // If it is not LOAD, can not do such combine.
9667 if (LD->getOpcode() != ISD::LOAD)
9668 return SDValue();
9669
9670 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9671 EVT MemVT = LoadSDN->getMemoryVT();
9672 // Check if memory operand is the same type as the vector element.
9673 if (MemVT != VT.getVectorElementType())
9674 return SDValue();
9675
9676 // Check if there are other uses. If so, do not combine as it will introduce
9677 // an extra load.
9678 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9679 ++UI) {
9680 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9681 continue;
9682 if (*UI != N)
9683 return SDValue();
9684 }
9685
9686 SDValue Addr = LD->getOperand(1);
9687 SDValue Vector = N->getOperand(0);
9688 // Search for a use of the address operand that is an increment.
9689 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9690 Addr.getNode()->use_end(); UI != UE; ++UI) {
9691 SDNode *User = *UI;
9692 if (User->getOpcode() != ISD::ADD
9693 || UI.getUse().getResNo() != Addr.getResNo())
9694 continue;
9695
9696 // Check that the add is independent of the load. Otherwise, folding it
9697 // would create a cycle.
9698 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9699 continue;
9700 // Also check that add is not used in the vector operand. This would also
9701 // create a cycle.
9702 if (User->isPredecessorOf(Vector.getNode()))
9703 continue;
9704
9705 // If the increment is a constant, it must match the memory ref size.
9706 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9707 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9708 uint32_t IncVal = CInc->getZExtValue();
9709 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9710 if (IncVal != NumBytes)
9711 continue;
9712 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9713 }
9714
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00009715 // Finally, check that the vector doesn't depend on the load.
9716 // Again, this would create a cycle.
9717 // The load depending on the vector is fine, as that's the case for the
9718 // LD1*post we'll eventually generate anyway.
9719 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9720 continue;
9721
Tim Northover3b0846e2014-05-24 12:50:23 +00009722 SmallVector<SDValue, 8> Ops;
9723 Ops.push_back(LD->getOperand(0)); // Chain
9724 if (IsLaneOp) {
9725 Ops.push_back(Vector); // The vector to be inserted
9726 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9727 }
9728 Ops.push_back(Addr);
9729 Ops.push_back(Inc);
9730
9731 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00009732 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00009733 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9734 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9735 MemVT,
9736 LoadSDN->getMemOperand());
9737
9738 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00009739 SDValue NewResults[] = {
9740 SDValue(LD, 0), // The result of load
9741 SDValue(UpdN.getNode(), 2) // Chain
9742 };
Tim Northover3b0846e2014-05-24 12:50:23 +00009743 DCI.CombineTo(LD, NewResults);
9744 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9745 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9746
9747 break;
9748 }
9749 return SDValue();
9750}
9751
Joel Jones7466ccf2017-07-10 22:11:50 +00009752/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
Tim Northover339c83e2015-11-10 00:44:23 +00009753/// address translation.
9754static bool performTBISimplification(SDValue Addr,
9755 TargetLowering::DAGCombinerInfo &DCI,
9756 SelectionDAG &DAG) {
9757 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
Craig Topperd0af7e82017-04-28 05:31:46 +00009758 KnownBits Known;
Ahmed Bougacha87807c52017-07-27 21:27:25 +00009759 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9760 !DCI.isBeforeLegalizeOps());
Tim Northover339c83e2015-11-10 00:44:23 +00009761 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Craig Topperd0af7e82017-04-28 05:31:46 +00009762 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
Tim Northover339c83e2015-11-10 00:44:23 +00009763 DCI.CommitTargetLoweringOpt(TLO);
9764 return true;
9765 }
9766 return false;
9767}
9768
9769static SDValue performSTORECombine(SDNode *N,
9770 TargetLowering::DAGCombinerInfo &DCI,
9771 SelectionDAG &DAG,
9772 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +00009773 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00009774 return Split;
9775
9776 if (Subtarget->supportsAddressTopByteIgnored() &&
9777 performTBISimplification(N->getOperand(2), DCI, DAG))
9778 return SDValue(N, 0);
9779
9780 return SDValue();
9781}
9782
Chad Rosier6c36eff2015-09-03 18:13:57 +00009783
Tim Northover3b0846e2014-05-24 12:50:23 +00009784/// Target-specific DAG combine function for NEON load/store intrinsics
9785/// to merge base address updates.
9786static SDValue performNEONPostLDSTCombine(SDNode *N,
9787 TargetLowering::DAGCombinerInfo &DCI,
9788 SelectionDAG &DAG) {
9789 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9790 return SDValue();
9791
9792 unsigned AddrOpIdx = N->getNumOperands() - 1;
9793 SDValue Addr = N->getOperand(AddrOpIdx);
9794
9795 // Search for a use of the address operand that is an increment.
9796 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9797 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9798 SDNode *User = *UI;
9799 if (User->getOpcode() != ISD::ADD ||
9800 UI.getUse().getResNo() != Addr.getResNo())
9801 continue;
9802
9803 // Check that the add is independent of the load/store. Otherwise, folding
9804 // it would create a cycle.
9805 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9806 continue;
9807
9808 // Find the new opcode for the updating load/store.
9809 bool IsStore = false;
9810 bool IsLaneOp = false;
9811 bool IsDupOp = false;
9812 unsigned NewOpc = 0;
9813 unsigned NumVecs = 0;
9814 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9815 switch (IntNo) {
9816 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9817 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9818 NumVecs = 2; break;
9819 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9820 NumVecs = 3; break;
9821 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9822 NumVecs = 4; break;
9823 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9824 NumVecs = 2; IsStore = true; break;
9825 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9826 NumVecs = 3; IsStore = true; break;
9827 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9828 NumVecs = 4; IsStore = true; break;
9829 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9830 NumVecs = 2; break;
9831 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9832 NumVecs = 3; break;
9833 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9834 NumVecs = 4; break;
9835 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9836 NumVecs = 2; IsStore = true; break;
9837 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9838 NumVecs = 3; IsStore = true; break;
9839 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9840 NumVecs = 4; IsStore = true; break;
9841 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9842 NumVecs = 2; IsDupOp = true; break;
9843 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9844 NumVecs = 3; IsDupOp = true; break;
9845 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9846 NumVecs = 4; IsDupOp = true; break;
9847 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9848 NumVecs = 2; IsLaneOp = true; break;
9849 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9850 NumVecs = 3; IsLaneOp = true; break;
9851 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9852 NumVecs = 4; IsLaneOp = true; break;
9853 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9854 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9855 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9856 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9857 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9858 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9859 }
9860
9861 EVT VecTy;
9862 if (IsStore)
9863 VecTy = N->getOperand(2).getValueType();
9864 else
9865 VecTy = N->getValueType(0);
9866
9867 // If the increment is a constant, it must match the memory ref size.
9868 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9869 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9870 uint32_t IncVal = CInc->getZExtValue();
9871 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9872 if (IsLaneOp || IsDupOp)
9873 NumBytes /= VecTy.getVectorNumElements();
9874 if (IncVal != NumBytes)
9875 continue;
9876 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9877 }
9878 SmallVector<SDValue, 8> Ops;
9879 Ops.push_back(N->getOperand(0)); // Incoming chain
9880 // Load lane and store have vector list as input.
9881 if (IsLaneOp || IsStore)
9882 for (unsigned i = 2; i < AddrOpIdx; ++i)
9883 Ops.push_back(N->getOperand(i));
9884 Ops.push_back(Addr); // Base register
9885 Ops.push_back(Inc);
9886
9887 // Return Types.
9888 EVT Tys[6];
9889 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9890 unsigned n;
9891 for (n = 0; n < NumResultVecs; ++n)
9892 Tys[n] = VecTy;
9893 Tys[n++] = MVT::i64; // Type of write back register
9894 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009895 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009896
9897 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9898 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9899 MemInt->getMemoryVT(),
9900 MemInt->getMemOperand());
9901
9902 // Update the uses.
9903 std::vector<SDValue> NewResults;
9904 for (unsigned i = 0; i < NumResultVecs; ++i) {
9905 NewResults.push_back(SDValue(UpdN.getNode(), i));
9906 }
9907 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9908 DCI.CombineTo(N, NewResults);
9909 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9910
9911 break;
9912 }
9913 return SDValue();
9914}
9915
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009916// Checks to see if the value is the prescribed width and returns information
9917// about its extension mode.
9918static
9919bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9920 ExtType = ISD::NON_EXTLOAD;
9921 switch(V.getNode()->getOpcode()) {
9922 default:
9923 return false;
9924 case ISD::LOAD: {
9925 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9926 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9927 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9928 ExtType = LoadNode->getExtensionType();
9929 return true;
9930 }
9931 return false;
9932 }
9933 case ISD::AssertSext: {
9934 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9935 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9936 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9937 ExtType = ISD::SEXTLOAD;
9938 return true;
9939 }
9940 return false;
9941 }
9942 case ISD::AssertZext: {
9943 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9944 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9945 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9946 ExtType = ISD::ZEXTLOAD;
9947 return true;
9948 }
9949 return false;
9950 }
9951 case ISD::Constant:
9952 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009953 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9954 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009955 }
9956 }
9957
9958 return true;
9959}
9960
9961// This function does a whole lot of voodoo to determine if the tests are
9962// equivalent without and with a mask. Essentially what happens is that given a
9963// DAG resembling:
9964//
9965// +-------------+ +-------------+ +-------------+ +-------------+
9966// | Input | | AddConstant | | CompConstant| | CC |
9967// +-------------+ +-------------+ +-------------+ +-------------+
9968// | | | |
9969// V V | +----------+
9970// +-------------+ +----+ | |
9971// | ADD | |0xff| | |
9972// +-------------+ +----+ | |
9973// | | | |
9974// V V | |
9975// +-------------+ | |
9976// | AND | | |
9977// +-------------+ | |
9978// | | |
9979// +-----+ | |
9980// | | |
9981// V V V
9982// +-------------+
9983// | CMP |
9984// +-------------+
9985//
9986// The AND node may be safely removed for some combinations of inputs. In
9987// particular we need to take into account the extension type of the Input,
9988// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9989// width of the input (this can work for any width inputs, the above graph is
9990// specific to 8 bits.
9991//
9992// The specific equations were worked out by generating output tables for each
9993// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9994// problem was simplified by working with 4 bit inputs, which means we only
9995// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9996// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9997// patterns present in both extensions (0,7). For every distinct set of
9998// AddConstant and CompConstants bit patterns we can consider the masked and
9999// unmasked versions to be equivalent if the result of this function is true for
10000// all 16 distinct bit patterns of for the current extension type of Input (w0).
10001//
10002// sub w8, w0, w1
10003// and w10, w8, #0x0f
10004// cmp w8, w2
10005// cset w9, AArch64CC
10006// cmp w10, w2
10007// cset w11, AArch64CC
10008// cmp w9, w11
10009// cset w0, eq
10010// ret
10011//
10012// Since the above function shows when the outputs are equivalent it defines
10013// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10014// would be expensive to run during compiles. The equations below were written
10015// in a test harness that confirmed they gave equivalent outputs to the above
10016// for all inputs function, so they can be used determine if the removal is
10017// legal instead.
10018//
10019// isEquivalentMaskless() is the code for testing if the AND can be removed
10020// factored out of the DAG recognition as the DAG can take several forms.
10021
David Majnemere61e4bf2016-06-21 05:10:24 +000010022static bool isEquivalentMaskless(unsigned CC, unsigned width,
10023 ISD::LoadExtType ExtType, int AddConstant,
10024 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010025 // By being careful about our equations and only writing the in term
10026 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10027 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +000010028 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010029
10030 // For the purposes of these comparisons sign extending the type is
10031 // equivalent to zero extending the add and displacing it by half the integer
10032 // width. Provided we are careful and make sure our equations are valid over
10033 // the whole range we can just adjust the input and avoid writing equations
10034 // for sign extended inputs.
10035 if (ExtType == ISD::SEXTLOAD)
10036 AddConstant -= (1 << (width-1));
10037
10038 switch(CC) {
10039 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010040 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010041 if ((AddConstant == 0) ||
10042 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10043 (AddConstant >= 0 && CompConstant < 0) ||
10044 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10045 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010046 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010047 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010048 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010049 if ((AddConstant == 0) ||
10050 (AddConstant >= 0 && CompConstant <= 0) ||
10051 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10052 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010053 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010054 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010055 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010056 if ((AddConstant >= 0 && CompConstant < 0) ||
10057 (AddConstant <= 0 && CompConstant >= -1 &&
10058 CompConstant < AddConstant + MaxUInt))
10059 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010060 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010061 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010062 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010063 if ((AddConstant == 0) ||
10064 (AddConstant > 0 && CompConstant <= 0) ||
10065 (AddConstant < 0 && CompConstant <= AddConstant))
10066 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010067 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010068 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010069 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010070 if ((AddConstant >= 0 && CompConstant <= 0) ||
10071 (AddConstant <= 0 && CompConstant >= 0 &&
10072 CompConstant <= AddConstant + MaxUInt))
10073 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010074 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010075 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +000010076 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010077 if ((AddConstant > 0 && CompConstant < 0) ||
10078 (AddConstant < 0 && CompConstant >= 0 &&
10079 CompConstant < AddConstant + MaxUInt) ||
10080 (AddConstant >= 0 && CompConstant >= 0 &&
10081 CompConstant >= AddConstant) ||
10082 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010083 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010084 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010085 case AArch64CC::VS:
10086 case AArch64CC::VC:
10087 case AArch64CC::AL:
10088 case AArch64CC::NV:
10089 return true;
10090 case AArch64CC::Invalid:
10091 break;
10092 }
10093
10094 return false;
10095}
10096
10097static
10098SDValue performCONDCombine(SDNode *N,
10099 TargetLowering::DAGCombinerInfo &DCI,
10100 SelectionDAG &DAG, unsigned CCIndex,
10101 unsigned CmpIndex) {
10102 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10103 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10104 unsigned CondOpcode = SubsNode->getOpcode();
10105
10106 if (CondOpcode != AArch64ISD::SUBS)
10107 return SDValue();
10108
10109 // There is a SUBS feeding this condition. Is it fed by a mask we can
10110 // use?
10111
10112 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10113 unsigned MaskBits = 0;
10114
10115 if (AndNode->getOpcode() != ISD::AND)
10116 return SDValue();
10117
10118 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10119 uint32_t CNV = CN->getZExtValue();
10120 if (CNV == 255)
10121 MaskBits = 8;
10122 else if (CNV == 65535)
10123 MaskBits = 16;
10124 }
10125
10126 if (!MaskBits)
10127 return SDValue();
10128
10129 SDValue AddValue = AndNode->getOperand(0);
10130
10131 if (AddValue.getOpcode() != ISD::ADD)
10132 return SDValue();
10133
10134 // The basic dag structure is correct, grab the inputs and validate them.
10135
10136 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10137 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10138 SDValue SubsInputValue = SubsNode->getOperand(1);
10139
10140 // The mask is present and the provenance of all the values is a smaller type,
10141 // lets see if the mask is superfluous.
10142
10143 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10144 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10145 return SDValue();
10146
10147 ISD::LoadExtType ExtType;
10148
10149 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10150 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10151 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10152 return SDValue();
10153
10154 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10155 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10156 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10157 return SDValue();
10158
10159 // The AND is not necessary, remove it.
10160
10161 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10162 SubsNode->getValueType(1));
10163 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10164
10165 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10166 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10167
10168 return SDValue(N, 0);
10169}
10170
Tim Northover3b0846e2014-05-24 12:50:23 +000010171// Optimize compare with zero and branch.
10172static SDValue performBRCONDCombine(SDNode *N,
10173 TargetLowering::DAGCombinerInfo &DCI,
10174 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010175 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010176 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010177 SDValue Chain = N->getOperand(0);
10178 SDValue Dest = N->getOperand(1);
10179 SDValue CCVal = N->getOperand(2);
10180 SDValue Cmp = N->getOperand(3);
10181
10182 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10183 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10184 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10185 return SDValue();
10186
10187 unsigned CmpOpc = Cmp.getOpcode();
10188 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10189 return SDValue();
10190
10191 // Only attempt folding if there is only one use of the flag and no use of the
10192 // value.
10193 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10194 return SDValue();
10195
10196 SDValue LHS = Cmp.getOperand(0);
10197 SDValue RHS = Cmp.getOperand(1);
10198
10199 assert(LHS.getValueType() == RHS.getValueType() &&
10200 "Expected the value type to be the same for both operands!");
10201 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10202 return SDValue();
10203
Artyom Skrobov314ee042015-11-25 19:41:11 +000010204 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010205 std::swap(LHS, RHS);
10206
Artyom Skrobov314ee042015-11-25 19:41:11 +000010207 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010208 return SDValue();
10209
10210 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10211 LHS.getOpcode() == ISD::SRL)
10212 return SDValue();
10213
10214 // Fold the compare into the branch instruction.
10215 SDValue BR;
10216 if (CC == AArch64CC::EQ)
10217 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10218 else
10219 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10220
10221 // Do not add new nodes to DAG combiner worklist.
10222 DCI.CombineTo(N, BR, false);
10223
10224 return SDValue();
10225}
10226
Geoff Berry9e934b02016-01-04 18:55:47 +000010227// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10228// as well as whether the test should be inverted. This code is required to
10229// catch these cases (as opposed to standard dag combines) because
10230// AArch64ISD::TBZ is matched during legalization.
10231static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10232 SelectionDAG &DAG) {
10233
10234 if (!Op->hasOneUse())
10235 return Op;
10236
10237 // We don't handle undef/constant-fold cases below, as they should have
10238 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10239 // etc.)
10240
10241 // (tbz (trunc x), b) -> (tbz x, b)
10242 // This case is just here to enable more of the below cases to be caught.
10243 if (Op->getOpcode() == ISD::TRUNCATE &&
10244 Bit < Op->getValueType(0).getSizeInBits()) {
10245 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10246 }
10247
10248 if (Op->getNumOperands() != 2)
10249 return Op;
10250
10251 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10252 if (!C)
10253 return Op;
10254
10255 switch (Op->getOpcode()) {
10256 default:
10257 return Op;
10258
10259 // (tbz (and x, m), b) -> (tbz x, b)
10260 case ISD::AND:
10261 if ((C->getZExtValue() >> Bit) & 1)
10262 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10263 return Op;
10264
10265 // (tbz (shl x, c), b) -> (tbz x, b-c)
10266 case ISD::SHL:
10267 if (C->getZExtValue() <= Bit &&
10268 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10269 Bit = Bit - C->getZExtValue();
10270 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10271 }
10272 return Op;
10273
10274 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10275 case ISD::SRA:
10276 Bit = Bit + C->getZExtValue();
10277 if (Bit >= Op->getValueType(0).getSizeInBits())
10278 Bit = Op->getValueType(0).getSizeInBits() - 1;
10279 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10280
10281 // (tbz (srl x, c), b) -> (tbz x, b+c)
10282 case ISD::SRL:
10283 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10284 Bit = Bit + C->getZExtValue();
10285 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10286 }
10287 return Op;
10288
10289 // (tbz (xor x, -1), b) -> (tbnz x, b)
10290 case ISD::XOR:
10291 if ((C->getZExtValue() >> Bit) & 1)
10292 Invert = !Invert;
10293 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10294 }
10295}
10296
10297// Optimize test single bit zero/non-zero and branch.
10298static SDValue performTBZCombine(SDNode *N,
10299 TargetLowering::DAGCombinerInfo &DCI,
10300 SelectionDAG &DAG) {
10301 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10302 bool Invert = false;
10303 SDValue TestSrc = N->getOperand(1);
10304 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10305
10306 if (TestSrc == NewTestSrc)
10307 return SDValue();
10308
10309 unsigned NewOpc = N->getOpcode();
10310 if (Invert) {
10311 if (NewOpc == AArch64ISD::TBZ)
10312 NewOpc = AArch64ISD::TBNZ;
10313 else {
10314 assert(NewOpc == AArch64ISD::TBNZ);
10315 NewOpc = AArch64ISD::TBZ;
10316 }
10317 }
10318
10319 SDLoc DL(N);
10320 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10321 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10322}
10323
Tim Northover3b0846e2014-05-24 12:50:23 +000010324// vselect (v1i1 setcc) ->
10325// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10326// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10327// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10328// such VSELECT.
10329static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10330 SDValue N0 = N->getOperand(0);
10331 EVT CCVT = N0.getValueType();
10332
10333 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10334 CCVT.getVectorElementType() != MVT::i1)
10335 return SDValue();
10336
10337 EVT ResVT = N->getValueType(0);
10338 EVT CmpVT = N0.getOperand(0).getValueType();
10339 // Only combine when the result type is of the same size as the compared
10340 // operands.
10341 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10342 return SDValue();
10343
10344 SDValue IfTrue = N->getOperand(1);
10345 SDValue IfFalse = N->getOperand(2);
10346 SDValue SetCC =
10347 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10348 N0.getOperand(0), N0.getOperand(1),
10349 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10350 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10351 IfTrue, IfFalse);
10352}
10353
10354/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10355/// the compare-mask instructions rather than going via NZCV, even if LHS and
10356/// RHS are really scalar. This replaces any scalar setcc in the above pattern
10357/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000010358static SDValue performSelectCombine(SDNode *N,
10359 TargetLowering::DAGCombinerInfo &DCI) {
10360 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000010361 SDValue N0 = N->getOperand(0);
10362 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000010363
Ahmed Bougachac004c602015-04-27 21:43:12 +000010364 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000010365 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010366
Ahmed Bougachac004c602015-04-27 21:43:12 +000010367 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10368 // scalar SetCCResultType. We also don't expect vectors, because we assume
10369 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10370 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10371 "Scalar-SETCC feeding SELECT has unexpected result type!");
10372
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010373 // If NumMaskElts == 0, the comparison is larger than select result. The
10374 // largest real NEON comparison is 64-bits per lane, which means the result is
10375 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000010376 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000010377
10378 // Don't try to do this optimization when the setcc itself has i1 operands.
10379 // There are no legal vectors of i1, so this would be pointless.
10380 if (SrcVT == MVT::i1)
10381 return SDValue();
10382
Tim Northover3c0915e2014-08-29 15:34:58 +000010383 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010384 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000010385 return SDValue();
10386
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010387 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010388 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10389
Ahmed Bougacha89bba612015-04-27 21:01:20 +000010390 // Also bail out if the vector CCVT isn't the same size as ResVT.
10391 // This can happen if the SETCC operand size doesn't divide the ResVT size
10392 // (e.g., f64 vs v3f32).
10393 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10394 return SDValue();
10395
Ahmed Bougachac004c602015-04-27 21:43:12 +000010396 // Make sure we didn't create illegal types, if we're not supposed to.
10397 assert(DCI.isBeforeLegalize() ||
10398 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10399
Tim Northover3b0846e2014-05-24 12:50:23 +000010400 // First perform a vector comparison, where lane 0 is the one we're interested
10401 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010402 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010403 SDValue LHS =
10404 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10405 SDValue RHS =
10406 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10407 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10408
10409 // Now duplicate the comparison mask we want across all other lanes.
10410 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000010411 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010412 Mask = DAG.getNode(ISD::BITCAST, DL,
10413 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000010414
10415 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10416}
10417
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010418/// Get rid of unnecessary NVCASTs (that don't change the type).
10419static SDValue performNVCASTCombine(SDNode *N) {
10420 if (N->getValueType(0) == N->getOperand(0).getValueType())
10421 return N->getOperand(0);
10422
10423 return SDValue();
10424}
10425
Tim Northover3b0846e2014-05-24 12:50:23 +000010426SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10427 DAGCombinerInfo &DCI) const {
10428 SelectionDAG &DAG = DCI.DAG;
10429 switch (N->getOpcode()) {
10430 default:
Sjoerd Meijer24c98182017-08-23 08:18:37 +000010431 DEBUG(dbgs() << "Custom combining: skipping\n");
Tim Northover3b0846e2014-05-24 12:50:23 +000010432 break;
10433 case ISD::ADD:
10434 case ISD::SUB:
10435 return performAddSubLongCombine(N, DCI, DAG);
10436 case ISD::XOR:
10437 return performXorCombine(N, DAG, DCI, Subtarget);
10438 case ISD::MUL:
10439 return performMulCombine(N, DAG, DCI, Subtarget);
10440 case ISD::SINT_TO_FP:
10441 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000010442 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000010443 case ISD::FP_TO_SINT:
10444 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000010445 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000010446 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000010447 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010448 case ISD::OR:
10449 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000010450 case ISD::SRL:
10451 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010452 case ISD::INTRINSIC_WO_CHAIN:
10453 return performIntrinsicCombine(N, DCI, Subtarget);
10454 case ISD::ANY_EXTEND:
10455 case ISD::ZERO_EXTEND:
10456 case ISD::SIGN_EXTEND:
10457 return performExtendCombine(N, DCI, DAG);
10458 case ISD::BITCAST:
10459 return performBitcastCombine(N, DCI, DAG);
10460 case ISD::CONCAT_VECTORS:
10461 return performConcatVectorsCombine(N, DCI, DAG);
Amara Emersonc9916d72017-05-16 21:29:22 +000010462 case ISD::SELECT:
10463 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010464 case ISD::VSELECT:
10465 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000010466 case ISD::LOAD:
10467 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10468 return SDValue(N, 0);
10469 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000010470 case ISD::STORE:
10471 return performSTORECombine(N, DCI, DAG, Subtarget);
10472 case AArch64ISD::BRCOND:
10473 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000010474 case AArch64ISD::TBNZ:
10475 case AArch64ISD::TBZ:
10476 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010477 case AArch64ISD::CSEL:
10478 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000010479 case AArch64ISD::DUP:
10480 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010481 case AArch64ISD::NVCAST:
10482 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000010483 case ISD::INSERT_VECTOR_ELT:
10484 return performPostLD1Combine(N, DCI, true);
10485 case ISD::INTRINSIC_VOID:
10486 case ISD::INTRINSIC_W_CHAIN:
10487 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10488 case Intrinsic::aarch64_neon_ld2:
10489 case Intrinsic::aarch64_neon_ld3:
10490 case Intrinsic::aarch64_neon_ld4:
10491 case Intrinsic::aarch64_neon_ld1x2:
10492 case Intrinsic::aarch64_neon_ld1x3:
10493 case Intrinsic::aarch64_neon_ld1x4:
10494 case Intrinsic::aarch64_neon_ld2lane:
10495 case Intrinsic::aarch64_neon_ld3lane:
10496 case Intrinsic::aarch64_neon_ld4lane:
10497 case Intrinsic::aarch64_neon_ld2r:
10498 case Intrinsic::aarch64_neon_ld3r:
10499 case Intrinsic::aarch64_neon_ld4r:
10500 case Intrinsic::aarch64_neon_st2:
10501 case Intrinsic::aarch64_neon_st3:
10502 case Intrinsic::aarch64_neon_st4:
10503 case Intrinsic::aarch64_neon_st1x2:
10504 case Intrinsic::aarch64_neon_st1x3:
10505 case Intrinsic::aarch64_neon_st1x4:
10506 case Intrinsic::aarch64_neon_st2lane:
10507 case Intrinsic::aarch64_neon_st3lane:
10508 case Intrinsic::aarch64_neon_st4lane:
10509 return performNEONPostLDSTCombine(N, DCI, DAG);
10510 default:
10511 break;
10512 }
10513 }
10514 return SDValue();
10515}
10516
10517// Check if the return value is used as only a return value, as otherwise
10518// we can't perform a tail-call. In particular, we need to check for
10519// target ISD nodes that are returns and any other "odd" constructs
10520// that the generic analysis code won't necessarily catch.
10521bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10522 SDValue &Chain) const {
10523 if (N->getNumValues() != 1)
10524 return false;
10525 if (!N->hasNUsesOfValue(1, 0))
10526 return false;
10527
10528 SDValue TCChain = Chain;
10529 SDNode *Copy = *N->use_begin();
10530 if (Copy->getOpcode() == ISD::CopyToReg) {
10531 // If the copy has a glue operand, we conservatively assume it isn't safe to
10532 // perform a tail call.
10533 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10534 MVT::Glue)
10535 return false;
10536 TCChain = Copy->getOperand(0);
10537 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10538 return false;
10539
10540 bool HasRet = false;
10541 for (SDNode *Node : Copy->uses()) {
10542 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10543 return false;
10544 HasRet = true;
10545 }
10546
10547 if (!HasRet)
10548 return false;
10549
10550 Chain = TCChain;
10551 return true;
10552}
10553
10554// Return whether the an instruction can potentially be optimized to a tail
10555// call. This will cause the optimizers to attempt to move, or duplicate,
10556// return instructions to help enable tail call optimizations for this
10557// instruction.
Matt Arsenault31380752017-04-18 21:16:46 +000010558bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010559 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010560}
10561
10562bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10563 SDValue &Offset,
10564 ISD::MemIndexedMode &AM,
10565 bool &IsInc,
10566 SelectionDAG &DAG) const {
10567 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10568 return false;
10569
10570 Base = Op->getOperand(0);
10571 // All of the indexed addressing mode instructions take a signed
10572 // 9 bit immediate offset.
10573 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000010574 int64_t RHSC = RHS->getSExtValue();
10575 if (Op->getOpcode() == ISD::SUB)
10576 RHSC = -(uint64_t)RHSC;
10577 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000010578 return false;
10579 IsInc = (Op->getOpcode() == ISD::ADD);
10580 Offset = Op->getOperand(1);
10581 return true;
10582 }
10583 return false;
10584}
10585
10586bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10587 SDValue &Offset,
10588 ISD::MemIndexedMode &AM,
10589 SelectionDAG &DAG) const {
10590 EVT VT;
10591 SDValue Ptr;
10592 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10593 VT = LD->getMemoryVT();
10594 Ptr = LD->getBasePtr();
10595 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10596 VT = ST->getMemoryVT();
10597 Ptr = ST->getBasePtr();
10598 } else
10599 return false;
10600
10601 bool IsInc;
10602 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10603 return false;
10604 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10605 return true;
10606}
10607
10608bool AArch64TargetLowering::getPostIndexedAddressParts(
10609 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10610 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10611 EVT VT;
10612 SDValue Ptr;
10613 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10614 VT = LD->getMemoryVT();
10615 Ptr = LD->getBasePtr();
10616 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10617 VT = ST->getMemoryVT();
10618 Ptr = ST->getBasePtr();
10619 } else
10620 return false;
10621
10622 bool IsInc;
10623 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10624 return false;
10625 // Post-indexing updates the base, so it's not a valid transform
10626 // if that's not the same as the load's pointer.
10627 if (Ptr != Base)
10628 return false;
10629 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10630 return true;
10631}
10632
Tim Northoverf8bfe212014-07-18 13:07:05 +000010633static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10634 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010635 SDLoc DL(N);
10636 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010637
10638 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10639 return;
10640
Tim Northoverf8bfe212014-07-18 13:07:05 +000010641 Op = SDValue(
10642 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10643 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010644 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010645 0);
10646 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10647 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10648}
10649
Charlie Turner434d4592015-10-16 15:38:25 +000010650static void ReplaceReductionResults(SDNode *N,
10651 SmallVectorImpl<SDValue> &Results,
10652 SelectionDAG &DAG, unsigned InterOp,
10653 unsigned AcrossOp) {
10654 EVT LoVT, HiVT;
10655 SDValue Lo, Hi;
10656 SDLoc dl(N);
10657 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10658 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10659 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10660 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10661 Results.push_back(SplitVal);
10662}
10663
Tim Northover2f32e7f2016-08-04 19:32:28 +000010664static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10665 SDLoc DL(N);
10666 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10667 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10668 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10669 DAG.getConstant(64, DL, MVT::i64)));
10670 return std::make_pair(Lo, Hi);
10671}
10672
Oliver Stannarda9d2e002018-01-29 09:18:37 +000010673// Create an even/odd pair of X registers holding integer value V.
10674static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
10675 SDLoc dl(V.getNode());
10676 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
10677 SDValue VHi = DAG.getAnyExtOrTrunc(
10678 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
10679 dl, MVT::i64);
10680 if (DAG.getDataLayout().isBigEndian())
10681 std::swap (VLo, VHi);
10682 SDValue RegClass =
10683 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
10684 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
10685 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
10686 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
10687 return SDValue(
10688 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10689}
10690
Tim Northovercdf15292016-04-14 17:03:29 +000010691static void ReplaceCMP_SWAP_128Results(SDNode *N,
Oliver Stannarda9d2e002018-01-29 09:18:37 +000010692 SmallVectorImpl<SDValue> &Results,
10693 SelectionDAG &DAG,
10694 const AArch64Subtarget *Subtarget) {
Tim Northovercdf15292016-04-14 17:03:29 +000010695 assert(N->getValueType(0) == MVT::i128 &&
10696 "AtomicCmpSwap on types less than 128 should be legal");
Oliver Stannarda9d2e002018-01-29 09:18:37 +000010697
10698 if (Subtarget->hasLSE()) {
10699 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
10700 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
10701 SDValue Ops[] = {
10702 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
10703 createGPRPairNode(DAG, N->getOperand(3)), // Store value
10704 N->getOperand(1), // Ptr
10705 N->getOperand(0), // Chain in
10706 };
10707
10708 MachineFunction &MF = DAG.getMachineFunction();
10709 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10710 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10711
10712 unsigned Opcode;
10713 switch (MemOp[0]->getOrdering()) {
10714 case AtomicOrdering::Monotonic:
10715 Opcode = AArch64::CASPX;
10716 break;
10717 case AtomicOrdering::Acquire:
10718 Opcode = AArch64::CASPAX;
10719 break;
10720 case AtomicOrdering::Release:
10721 Opcode = AArch64::CASPLX;
10722 break;
10723 case AtomicOrdering::AcquireRelease:
10724 case AtomicOrdering::SequentiallyConsistent:
10725 Opcode = AArch64::CASPALX;
10726 break;
10727 default:
10728 llvm_unreachable("Unexpected ordering!");
10729 }
10730
10731 MachineSDNode *CmpSwap = DAG.getMachineNode(
10732 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
10733 CmpSwap->setMemRefs(MemOp, MemOp + 1);
10734
10735 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
10736 if (DAG.getDataLayout().isBigEndian())
10737 std::swap(SubReg1, SubReg2);
10738 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
10739 SDValue(CmpSwap, 0)));
10740 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
10741 SDValue(CmpSwap, 0)));
10742 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
10743 return;
10744 }
10745
Tim Northover2f32e7f2016-08-04 19:32:28 +000010746 auto Desired = splitInt128(N->getOperand(2), DAG);
10747 auto New = splitInt128(N->getOperand(3), DAG);
10748 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10749 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000010750 SDNode *CmpSwap = DAG.getMachineNode(
10751 AArch64::CMP_SWAP_128, SDLoc(N),
10752 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10753
10754 MachineFunction &MF = DAG.getMachineFunction();
10755 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10756 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10757 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10758
10759 Results.push_back(SDValue(CmpSwap, 0));
10760 Results.push_back(SDValue(CmpSwap, 1));
10761 Results.push_back(SDValue(CmpSwap, 3));
10762}
10763
Tim Northover3b0846e2014-05-24 12:50:23 +000010764void AArch64TargetLowering::ReplaceNodeResults(
10765 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10766 switch (N->getOpcode()) {
10767 default:
10768 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010769 case ISD::BITCAST:
10770 ReplaceBITCASTResults(N, Results, DAG);
10771 return;
Amara Emersonc9916d72017-05-16 21:29:22 +000010772 case ISD::VECREDUCE_ADD:
10773 case ISD::VECREDUCE_SMAX:
10774 case ISD::VECREDUCE_SMIN:
10775 case ISD::VECREDUCE_UMAX:
10776 case ISD::VECREDUCE_UMIN:
10777 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
10778 return;
10779
Charlie Turner434d4592015-10-16 15:38:25 +000010780 case AArch64ISD::SADDV:
10781 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10782 return;
10783 case AArch64ISD::UADDV:
10784 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10785 return;
10786 case AArch64ISD::SMINV:
10787 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10788 return;
10789 case AArch64ISD::UMINV:
10790 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10791 return;
10792 case AArch64ISD::SMAXV:
10793 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10794 return;
10795 case AArch64ISD::UMAXV:
10796 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10797 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010798 case ISD::FP_TO_UINT:
10799 case ISD::FP_TO_SINT:
10800 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10801 // Let normal code take care of it by not adding anything to Results.
10802 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010803 case ISD::ATOMIC_CMP_SWAP:
Oliver Stannarda9d2e002018-01-29 09:18:37 +000010804 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
Tim Northovercdf15292016-04-14 17:03:29 +000010805 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010806 }
10807}
10808
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010809bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000010810 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10811 return TargetLowering::useLoadStackGuardNode();
10812 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010813}
10814
Sanjay Patel1dd15592015-07-28 23:05:48 +000010815unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010816 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10817 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010818 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010819}
10820
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010821TargetLoweringBase::LegalizeTypeAction
10822AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10823 MVT SVT = VT.getSimpleVT();
10824 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10825 // v4i16, v2i32 instead of to promote.
10826 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10827 || SVT == MVT::v1f32)
10828 return TypeWidenVector;
10829
10830 return TargetLoweringBase::getPreferredVectorAction(VT);
10831}
10832
Robin Morisseted3d48f2014-09-03 21:29:59 +000010833// Loads and stores less than 128-bits are already atomic; ones above that
10834// are doomed anyway, so defer to the default libcall and blame the OS when
10835// things go wrong.
10836bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10837 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10838 return Size == 128;
10839}
10840
10841// Loads and stores less than 128-bits are already atomic; ones above that
10842// are doomed anyway, so defer to the default libcall and blame the OS when
10843// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010844TargetLowering::AtomicExpansionKind
10845AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010846 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010847 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010848}
10849
10850// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010851TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010852AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010853 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Christof Doumac1c28052017-06-21 10:58:31 +000010854 if (Size > 128) return AtomicExpansionKind::None;
10855 // Nand not supported in LSE.
10856 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
Christof Doumac1c28052017-06-21 10:58:31 +000010857 // Leave 128 bits to LLSC.
10858 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010859}
10860
Ahmed Bougacha52468672015-09-11 17:08:28 +000010861bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10862 AtomicCmpXchgInst *AI) const {
Christof Doumac1c28052017-06-21 10:58:31 +000010863 // If subtarget has LSE, leave cmpxchg intact for codegen.
10864 if (Subtarget->hasLSE()) return false;
Tim Northovercdf15292016-04-14 17:03:29 +000010865 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10866 // implement cmpxchg without spilling. If the address being exchanged is also
10867 // on the stack and close enough to the spill slot, this can lead to a
10868 // situation where the monitor always gets cleared and the atomic operation
10869 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10870 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010871}
10872
Tim Northover3b0846e2014-05-24 12:50:23 +000010873Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10874 AtomicOrdering Ord) const {
10875 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10876 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010877 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010878
10879 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10880 // intrinsic must return {i64, i64} and we have to recombine them into a
10881 // single i128 here.
10882 if (ValTy->getPrimitiveSizeInBits() == 128) {
10883 Intrinsic::ID Int =
10884 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010885 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000010886
10887 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10888 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10889
10890 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10891 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10892 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10893 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10894 return Builder.CreateOr(
10895 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10896 }
10897
10898 Type *Tys[] = { Addr->getType() };
10899 Intrinsic::ID Int =
10900 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010901 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010902
10903 return Builder.CreateTruncOrBitCast(
10904 Builder.CreateCall(Ldxr, Addr),
10905 cast<PointerType>(Addr->getType())->getElementType());
10906}
10907
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010908void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10909 IRBuilder<> &Builder) const {
10910 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000010911 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010912}
10913
Tim Northover3b0846e2014-05-24 12:50:23 +000010914Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10915 Value *Val, Value *Addr,
10916 AtomicOrdering Ord) const {
10917 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010918 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010919
10920 // Since the intrinsics must have legal type, the i128 intrinsics take two
10921 // parameters: "i64, i64". We must marshal Val into the appropriate form
10922 // before the call.
10923 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10924 Intrinsic::ID Int =
10925 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10926 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10927 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10928
10929 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10930 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10931 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010932 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010933 }
10934
10935 Intrinsic::ID Int =
10936 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10937 Type *Tys[] = { Addr->getType() };
10938 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10939
David Blaikieff6409d2015-05-18 22:13:54 +000010940 return Builder.CreateCall(Stxr,
10941 {Builder.CreateZExtOrBitCast(
10942 Val, Stxr->getFunctionType()->getParamType(0)),
10943 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010944}
Tim Northover3c55cca2014-11-27 21:02:42 +000010945
10946bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10947 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10948 return Ty->isArrayTy();
10949}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010950
10951bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10952 EVT) const {
10953 return false;
10954}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010955
Petr Hoseka7d59162017-02-24 03:10:10 +000010956static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010957 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10958 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010959 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010960 return IRB.CreatePointerCast(
Petr Hoseka7d59162017-02-24 03:10:10 +000010961 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010962 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10963}
10964
Petr Hoseka7d59162017-02-24 03:10:10 +000010965Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10966 // Android provides a fixed TLS slot for the stack cookie. See the definition
10967 // of TLS_SLOT_STACK_GUARD in
10968 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10969 if (Subtarget->isTargetAndroid())
10970 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010971
Petr Hoseka7d59162017-02-24 03:10:10 +000010972 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000010973 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000010974 if (Subtarget->isTargetFuchsia())
10975 return UseTlsOffset(IRB, -0x10);
10976
10977 return TargetLowering::getIRStackGuard(IRB);
10978}
10979
10980Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010981 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10982 // definition of TLS_SLOT_SAFESTACK in
10983 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000010984 if (Subtarget->isTargetAndroid())
10985 return UseTlsOffset(IRB, 0x48);
10986
10987 // Fuchsia is similar.
Petr Hosekc35fe2b2017-09-13 01:18:06 +000010988 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
Petr Hoseka7d59162017-02-24 03:10:10 +000010989 if (Subtarget->isTargetFuchsia())
10990 return UseTlsOffset(IRB, -0x8);
10991
10992 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010993}
Manman Rencbe4f942015-12-16 21:04:19 +000010994
Geoff Berry5d534b62017-02-21 18:53:14 +000010995bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10996 const Instruction &AndI) const {
10997 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10998 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
10999 // may be beneficial to sink in other cases, but we would have to check that
11000 // the cmp would not get folded into the br to form a cbz for these to be
11001 // beneficial.
11002 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11003 if (!Mask)
11004 return false;
Craig Topper4e22ee62017-08-04 16:59:29 +000011005 return Mask->getValue().isPowerOf2();
Geoff Berry5d534b62017-02-21 18:53:14 +000011006}
11007
Manman Rencbe4f942015-12-16 21:04:19 +000011008void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11009 // Update IsSplitCSR in AArch64unctionInfo.
11010 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11011 AFI->setIsSplitCSR(true);
11012}
11013
11014void AArch64TargetLowering::insertCopiesSplitCSR(
11015 MachineBasicBlock *Entry,
11016 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11017 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11018 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11019 if (!IStart)
11020 return;
11021
11022 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11023 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000011024 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000011025 for (const MCPhysReg *I = IStart; *I; ++I) {
11026 const TargetRegisterClass *RC = nullptr;
11027 if (AArch64::GPR64RegClass.contains(*I))
11028 RC = &AArch64::GPR64RegClass;
11029 else if (AArch64::FPR64RegClass.contains(*I))
11030 RC = &AArch64::FPR64RegClass;
11031 else
11032 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11033
11034 unsigned NewVR = MRI->createVirtualRegister(RC);
11035 // Create copy from CSR to a virtual register.
11036 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11037 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11038 // nounwind. If we want to generalize this later, we may need to emit
11039 // CFI pseudo-instructions.
Matthias Braunf1caa282017-12-15 22:22:58 +000011040 assert(Entry->getParent()->getFunction().hasFnAttribute(
Manman Rencbe4f942015-12-16 21:04:19 +000011041 Attribute::NoUnwind) &&
11042 "Function should be nounwind in insertCopiesSplitCSR!");
11043 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000011044 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000011045 .addReg(*I);
11046
Manman Ren4632e8e2016-01-15 20:13:28 +000011047 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000011048 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000011049 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11050 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000011051 .addReg(NewVR);
11052 }
11053}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011054
Reid Klecknerb5180542017-03-21 16:57:19 +000011055bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011056 // Integer division on AArch64 is expensive. However, when aggressively
11057 // optimizing for code size, we prefer to use a div instruction, as it is
11058 // usually smaller than the alternative sequence.
11059 // The exception to this is vector division. Since AArch64 doesn't have vector
11060 // integer division, leaving the division as-is is a loss even in terms of
11061 // size, because it will have to be scalarized, while the alternative code
11062 // sequence can be performed in vector form.
11063 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000011064 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000011065 return OptSize && !VT.isVector();
11066}
Tim Northoverf19d4672017-02-08 17:57:20 +000011067
Joel Jones07150922018-01-25 21:55:39 +000011068bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
11069 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
11070}
11071
Tim Northoverf19d4672017-02-08 17:57:20 +000011072unsigned
11073AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
Martin Storsjo68266fa2017-07-13 17:03:12 +000011074 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
Tim Northoverf19d4672017-02-08 17:57:20 +000011075 return getPointerTy(DL).getSizeInBits();
11076
11077 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
11078}
Matthias Braun5c290dc2018-01-19 03:16:36 +000011079
11080void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
11081 MF.getFrameInfo().computeMaxCallFrameSize(MF);
11082 TargetLoweringBase::finalizeLowering(MF);
11083}